assignment-user-matcher 1.1.1 → 1.1.6
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 +75 -0
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +397 -23
- package/package.json +6 -2
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 = {
|
|
@@ -40,13 +42,86 @@ export default class AssignmentMatcher {
|
|
|
40
42
|
pendingAssignmentsExpiryKey: string;
|
|
41
43
|
assignmentOwnerKey: string;
|
|
42
44
|
allTagsKey: string;
|
|
45
|
+
acceptedAssignmentsKey: string;
|
|
43
46
|
constructor(redisClient: RedisClientType, options?: options);
|
|
44
47
|
private initRedis;
|
|
45
48
|
addUser(user: User): Promise<User>;
|
|
46
49
|
addAssignment(assignment: Assignment): Promise<Assignment>;
|
|
47
50
|
removeAssignment(id: string): Promise<string>;
|
|
48
51
|
removeUser(userId: string): Promise<string>;
|
|
52
|
+
/**
|
|
53
|
+
* Get all assignments (queued, pending, and accepted).
|
|
54
|
+
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
55
|
+
*/
|
|
49
56
|
getAllAssignments(): Promise<Assignment[]>;
|
|
57
|
+
/**
|
|
58
|
+
* Get assignments with pagination support for efficient querying of large datasets.
|
|
59
|
+
* Uses cursor-based pagination across statuses.
|
|
60
|
+
*
|
|
61
|
+
* @param options.cursor - Cursor for pagination (null/undefined for first page)
|
|
62
|
+
* @param options.limit - Maximum number of assignments to return per page (default: 100)
|
|
63
|
+
* @param options.status - Filter by status: 'queued' | 'pending' | 'accepted' | 'all' (default: 'all')
|
|
64
|
+
* @param options.includeTotal - Whether to include total count (slower for large datasets)
|
|
65
|
+
*/
|
|
66
|
+
getAssignmentsPaginated(options?: {
|
|
67
|
+
cursor?: string | null;
|
|
68
|
+
limit?: number;
|
|
69
|
+
status?: 'queued' | 'pending' | 'accepted' | 'all';
|
|
70
|
+
includeTotal?: boolean;
|
|
71
|
+
}): Promise<{
|
|
72
|
+
assignments: Assignment[];
|
|
73
|
+
nextCursor: string | null;
|
|
74
|
+
hasMore: boolean;
|
|
75
|
+
total?: number;
|
|
76
|
+
}>;
|
|
77
|
+
/**
|
|
78
|
+
* Get assignment counts by status without fetching the data.
|
|
79
|
+
* Efficient for dashboards and monitoring.
|
|
80
|
+
*/
|
|
81
|
+
getAssignmentCounts(): Promise<{
|
|
82
|
+
queued: number;
|
|
83
|
+
pending: number;
|
|
84
|
+
accepted: number;
|
|
85
|
+
total: number;
|
|
86
|
+
}>;
|
|
87
|
+
/**
|
|
88
|
+
* Get a single assignment by ID from any status.
|
|
89
|
+
*/
|
|
90
|
+
getAssignment(id: string): Promise<(Assignment & {
|
|
91
|
+
_status?: string;
|
|
92
|
+
}) | null>;
|
|
93
|
+
/**
|
|
94
|
+
* Get multiple assignments by IDs efficiently.
|
|
95
|
+
*/
|
|
96
|
+
getAssignmentsByIds(ids: string[]): Promise<Assignment[]>;
|
|
97
|
+
/**
|
|
98
|
+
* Parse an IPv4 address into a BigInt representation
|
|
99
|
+
*/
|
|
100
|
+
private parseIPv4;
|
|
101
|
+
/**
|
|
102
|
+
* Parse an IPv6 address into a BigInt representation
|
|
103
|
+
* Handles full, compressed (::), and IPv4-mapped formats
|
|
104
|
+
*/
|
|
105
|
+
private parseIPv6;
|
|
106
|
+
/**
|
|
107
|
+
* Parse an IP address (auto-detect IPv4 or IPv6)
|
|
108
|
+
* Returns { value: BigInt, isIPv6: boolean } or null if invalid
|
|
109
|
+
*/
|
|
110
|
+
private parseIP;
|
|
111
|
+
/**
|
|
112
|
+
* Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
|
|
113
|
+
* Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
|
|
114
|
+
*/
|
|
115
|
+
private parseCIDR;
|
|
116
|
+
/**
|
|
117
|
+
* Check if an IP address is within a CIDR range
|
|
118
|
+
*/
|
|
119
|
+
private isIpInCidr;
|
|
120
|
+
/**
|
|
121
|
+
* Check if a user's IP matches any of the allowed CIDRs
|
|
122
|
+
* Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
|
|
123
|
+
*/
|
|
124
|
+
private checkCidrMatch;
|
|
50
125
|
private matchScore;
|
|
51
126
|
private calculatePriority;
|
|
52
127
|
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,MA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B;IAE1D,wBAAwB,CAAC,UAAU,GAAE,MAAc;IAOnD,uBAAuB;YAOT,kBAAkB;CAwBnC"}
|
package/dist/matcher.class.js
CHANGED
|
@@ -2,23 +2,23 @@
|
|
|
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.
|
|
21
|
-
this.
|
|
19
|
+
this.acceptedAssignmentsKey = this.redisPrefix + 'assignments:accepted';
|
|
20
|
+
this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
|
|
21
|
+
this.matchScore = options?.matchingFunction ?? this.matchScore;
|
|
22
22
|
this.initRedis();
|
|
23
23
|
}
|
|
24
24
|
async initRedis() {
|
|
@@ -78,7 +78,7 @@ class AssignmentMatcher {
|
|
|
78
78
|
// Fetch tags to remove from per-tag indices
|
|
79
79
|
const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
|
|
80
80
|
let tags = [];
|
|
81
|
-
if (
|
|
81
|
+
if (tagsCsv && tagsCsv.length > 0) {
|
|
82
82
|
tags = tagsCsv.split(',');
|
|
83
83
|
}
|
|
84
84
|
const multi = this.redisClient.multi();
|
|
@@ -104,10 +104,357 @@ class AssignmentMatcher {
|
|
|
104
104
|
await multi.exec();
|
|
105
105
|
return userId;
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Get all assignments (queued, pending, and accepted).
|
|
109
|
+
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
110
|
+
*/
|
|
107
111
|
async getAllAssignments() {
|
|
108
|
-
const
|
|
109
|
-
|
|
112
|
+
const [queuedAssignments, pendingAssignments, acceptedAssignments] = await Promise.all([
|
|
113
|
+
this.redisClient.hGetAll(this.assignmentsRefKey),
|
|
114
|
+
this.redisClient.hGetAll(this.pendingAssignmentsKey),
|
|
115
|
+
this.redisClient.hGetAll(this.acceptedAssignmentsKey),
|
|
116
|
+
]);
|
|
117
|
+
const allAssignments = { ...queuedAssignments, ...pendingAssignments, ...acceptedAssignments };
|
|
118
|
+
return Object.values(allAssignments).map((assignment) => JSON.parse(assignment));
|
|
110
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Get assignments with pagination support for efficient querying of large datasets.
|
|
122
|
+
* Uses cursor-based pagination across statuses.
|
|
123
|
+
*
|
|
124
|
+
* @param options.cursor - Cursor for pagination (null/undefined for first page)
|
|
125
|
+
* @param options.limit - Maximum number of assignments to return per page (default: 100)
|
|
126
|
+
* @param options.status - Filter by status: 'queued' | 'pending' | 'accepted' | 'all' (default: 'all')
|
|
127
|
+
* @param options.includeTotal - Whether to include total count (slower for large datasets)
|
|
128
|
+
*/
|
|
129
|
+
async getAssignmentsPaginated(options) {
|
|
130
|
+
const limit = options?.limit ?? 100;
|
|
131
|
+
const status = options?.status ?? 'all';
|
|
132
|
+
const includeTotal = options?.includeTotal ?? false;
|
|
133
|
+
const getKeyForStatus = (s) => {
|
|
134
|
+
switch (s) {
|
|
135
|
+
case 'queued': return this.assignmentsRefKey;
|
|
136
|
+
case 'pending': return this.pendingAssignmentsKey;
|
|
137
|
+
case 'accepted': return this.acceptedAssignmentsKey;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const statusOrder = status === 'all' ? ['queued', 'pending', 'accepted'] : [status];
|
|
141
|
+
// Parse cursor: "statusIndex:offset" where offset is how many we've seen in current status
|
|
142
|
+
let statusIndex = 0;
|
|
143
|
+
let offset = 0;
|
|
144
|
+
if (options?.cursor) {
|
|
145
|
+
const parts = options.cursor.split(':');
|
|
146
|
+
statusIndex = parseInt(parts[0], 10) || 0;
|
|
147
|
+
offset = parseInt(parts[1], 10) || 0;
|
|
148
|
+
}
|
|
149
|
+
const assignments = [];
|
|
150
|
+
let nextCursor = null;
|
|
151
|
+
let hasMore = false;
|
|
152
|
+
while (assignments.length < limit && statusIndex < statusOrder.length) {
|
|
153
|
+
const scanStatus = statusOrder[statusIndex];
|
|
154
|
+
const key = getKeyForStatus(scanStatus);
|
|
155
|
+
// Get count for this status
|
|
156
|
+
const totalInStatus = await this.redisClient.hLen(key);
|
|
157
|
+
const remainingInStatus = totalInStatus - offset;
|
|
158
|
+
if (remainingInStatus <= 0) {
|
|
159
|
+
// Move to next status
|
|
160
|
+
statusIndex++;
|
|
161
|
+
offset = 0;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
// Scan to get entries - we need to scan through and skip offset entries
|
|
165
|
+
const needed = limit - assignments.length;
|
|
166
|
+
let scanned = 0;
|
|
167
|
+
let cursor = '0';
|
|
168
|
+
const seenIds = new Set();
|
|
169
|
+
do {
|
|
170
|
+
const { cursor: newCursor, entries } = await this.redisClient.hScan(key, cursor, {
|
|
171
|
+
COUNT: Math.max(needed + offset - scanned, 100),
|
|
172
|
+
});
|
|
173
|
+
for (const entry of entries) {
|
|
174
|
+
if (seenIds.has(entry.field))
|
|
175
|
+
continue; // Skip duplicates from HSCAN
|
|
176
|
+
seenIds.add(entry.field);
|
|
177
|
+
if (scanned < offset) {
|
|
178
|
+
scanned++;
|
|
179
|
+
continue; // Skip already-seen entries
|
|
180
|
+
}
|
|
181
|
+
if (assignments.length >= limit) {
|
|
182
|
+
// We have enough, set cursor for next page
|
|
183
|
+
nextCursor = `${statusIndex}:${offset + (assignments.length - (assignments.filter(a => a._status === scanStatus).length - 1))}`;
|
|
184
|
+
hasMore = true;
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const assignment = JSON.parse(entry.value);
|
|
189
|
+
assignment._status = scanStatus;
|
|
190
|
+
assignments.push(assignment);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
// Skip invalid JSON
|
|
194
|
+
}
|
|
195
|
+
scanned++;
|
|
196
|
+
}
|
|
197
|
+
cursor = newCursor;
|
|
198
|
+
} while (cursor !== '0' && assignments.length < limit);
|
|
199
|
+
if (assignments.length >= limit) {
|
|
200
|
+
// Calculate correct offset for resume
|
|
201
|
+
const countFromCurrentStatus = assignments.filter(a => a._status === scanStatus).length;
|
|
202
|
+
nextCursor = `${statusIndex}:${offset + countFromCurrentStatus}`;
|
|
203
|
+
hasMore = true;
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
// Move to next status
|
|
207
|
+
statusIndex++;
|
|
208
|
+
offset = 0;
|
|
209
|
+
}
|
|
210
|
+
// Check if there's more data in remaining statuses
|
|
211
|
+
if (!hasMore && statusIndex < statusOrder.length) {
|
|
212
|
+
for (let i = statusIndex; i < statusOrder.length; i++) {
|
|
213
|
+
const count = await this.redisClient.hLen(getKeyForStatus(statusOrder[i]));
|
|
214
|
+
const processedInThisStatus = i === statusIndex ? offset : 0;
|
|
215
|
+
if (count > processedInThisStatus) {
|
|
216
|
+
nextCursor = `${i}:${processedInThisStatus}`;
|
|
217
|
+
hasMore = true;
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const result = {
|
|
223
|
+
assignments,
|
|
224
|
+
nextCursor: hasMore ? nextCursor : null,
|
|
225
|
+
hasMore,
|
|
226
|
+
};
|
|
227
|
+
// Optionally include total count
|
|
228
|
+
if (includeTotal) {
|
|
229
|
+
if (status === 'all') {
|
|
230
|
+
const [queuedCount, pendingCount, acceptedCount] = await Promise.all([
|
|
231
|
+
this.redisClient.hLen(this.assignmentsRefKey),
|
|
232
|
+
this.redisClient.hLen(this.pendingAssignmentsKey),
|
|
233
|
+
this.redisClient.hLen(this.acceptedAssignmentsKey),
|
|
234
|
+
]);
|
|
235
|
+
result.total = queuedCount + pendingCount + acceptedCount;
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
result.total = await this.redisClient.hLen(getKeyForStatus(status));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Get assignment counts by status without fetching the data.
|
|
245
|
+
* Efficient for dashboards and monitoring.
|
|
246
|
+
*/
|
|
247
|
+
async getAssignmentCounts() {
|
|
248
|
+
const [queued, pending, accepted] = await Promise.all([
|
|
249
|
+
this.redisClient.hLen(this.assignmentsRefKey),
|
|
250
|
+
this.redisClient.hLen(this.pendingAssignmentsKey),
|
|
251
|
+
this.redisClient.hLen(this.acceptedAssignmentsKey),
|
|
252
|
+
]);
|
|
253
|
+
return {
|
|
254
|
+
queued,
|
|
255
|
+
pending,
|
|
256
|
+
accepted,
|
|
257
|
+
total: queued + pending + accepted,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Get a single assignment by ID from any status.
|
|
262
|
+
*/
|
|
263
|
+
async getAssignment(id) {
|
|
264
|
+
// Check all three stores in parallel
|
|
265
|
+
const [queued, pending, accepted] = await Promise.all([
|
|
266
|
+
this.redisClient.hGet(this.assignmentsRefKey, id),
|
|
267
|
+
this.redisClient.hGet(this.pendingAssignmentsKey, id),
|
|
268
|
+
this.redisClient.hGet(this.acceptedAssignmentsKey, id),
|
|
269
|
+
]);
|
|
270
|
+
if (queued) {
|
|
271
|
+
const assignment = JSON.parse(queued);
|
|
272
|
+
assignment._status = 'queued';
|
|
273
|
+
return assignment;
|
|
274
|
+
}
|
|
275
|
+
if (pending) {
|
|
276
|
+
const assignment = JSON.parse(pending);
|
|
277
|
+
assignment._status = 'pending';
|
|
278
|
+
return assignment;
|
|
279
|
+
}
|
|
280
|
+
if (accepted) {
|
|
281
|
+
const assignment = JSON.parse(accepted);
|
|
282
|
+
assignment._status = 'accepted';
|
|
283
|
+
return assignment;
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Get multiple assignments by IDs efficiently.
|
|
289
|
+
*/
|
|
290
|
+
async getAssignmentsByIds(ids) {
|
|
291
|
+
if (ids.length === 0)
|
|
292
|
+
return [];
|
|
293
|
+
const multi = this.redisClient.multi();
|
|
294
|
+
for (const id of ids) {
|
|
295
|
+
multi.hGet(this.assignmentsRefKey, id);
|
|
296
|
+
multi.hGet(this.pendingAssignmentsKey, id);
|
|
297
|
+
multi.hGet(this.acceptedAssignmentsKey, id);
|
|
298
|
+
}
|
|
299
|
+
const results = await multi.exec();
|
|
300
|
+
const assignments = [];
|
|
301
|
+
for (let i = 0; i < ids.length; i++) {
|
|
302
|
+
const queued = results[i * 3];
|
|
303
|
+
const pending = results[i * 3 + 1];
|
|
304
|
+
const accepted = results[i * 3 + 2];
|
|
305
|
+
const json = queued || pending || accepted;
|
|
306
|
+
if (json) {
|
|
307
|
+
try {
|
|
308
|
+
const assignment = JSON.parse(json);
|
|
309
|
+
assignment._status = queued ? 'queued' : pending ? 'pending' : 'accepted';
|
|
310
|
+
assignments.push(assignment);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
// Skip invalid JSON
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return assignments;
|
|
318
|
+
}
|
|
319
|
+
// ==================== CIDR/IP Matching Utilities ====================
|
|
320
|
+
/**
|
|
321
|
+
* Parse an IPv4 address into a BigInt representation
|
|
322
|
+
*/
|
|
323
|
+
parseIPv4(ip) {
|
|
324
|
+
const parts = ip.split('.');
|
|
325
|
+
if (parts.length !== 4)
|
|
326
|
+
return null;
|
|
327
|
+
let result = 0n;
|
|
328
|
+
for (const part of parts) {
|
|
329
|
+
const num = parseInt(part, 10);
|
|
330
|
+
if (isNaN(num) || num < 0 || num > 255)
|
|
331
|
+
return null;
|
|
332
|
+
result = (result << 8n) | BigInt(num);
|
|
333
|
+
}
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Parse an IPv6 address into a BigInt representation
|
|
338
|
+
* Handles full, compressed (::), and IPv4-mapped formats
|
|
339
|
+
*/
|
|
340
|
+
parseIPv6(ip) {
|
|
341
|
+
// Handle IPv4-mapped IPv6 (::ffff:192.168.1.1)
|
|
342
|
+
const ipv4MappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
|
|
343
|
+
if (ipv4MappedMatch) {
|
|
344
|
+
const ipv4 = this.parseIPv4(ipv4MappedMatch[1]);
|
|
345
|
+
if (ipv4 === null)
|
|
346
|
+
return null;
|
|
347
|
+
return 0xffff00000000n | ipv4;
|
|
348
|
+
}
|
|
349
|
+
// Handle :: expansion
|
|
350
|
+
let fullIp = ip.toLowerCase();
|
|
351
|
+
if (fullIp.includes('::')) {
|
|
352
|
+
const parts = fullIp.split('::');
|
|
353
|
+
if (parts.length > 2)
|
|
354
|
+
return null; // Invalid: more than one ::
|
|
355
|
+
const leftParts = parts[0] ? parts[0].split(':') : [];
|
|
356
|
+
const rightParts = parts[1] ? parts[1].split(':') : [];
|
|
357
|
+
const missingGroups = 8 - leftParts.length - rightParts.length;
|
|
358
|
+
if (missingGroups < 0)
|
|
359
|
+
return null;
|
|
360
|
+
const allParts = [...leftParts, ...Array(missingGroups).fill('0'), ...rightParts];
|
|
361
|
+
fullIp = allParts.join(':');
|
|
362
|
+
}
|
|
363
|
+
const groups = fullIp.split(':');
|
|
364
|
+
if (groups.length !== 8)
|
|
365
|
+
return null;
|
|
366
|
+
let result = 0n;
|
|
367
|
+
for (const group of groups) {
|
|
368
|
+
if (group.length === 0 || group.length > 4)
|
|
369
|
+
return null;
|
|
370
|
+
const num = parseInt(group, 16);
|
|
371
|
+
if (isNaN(num) || num < 0 || num > 0xffff)
|
|
372
|
+
return null;
|
|
373
|
+
result = (result << 16n) | BigInt(num);
|
|
374
|
+
}
|
|
375
|
+
return result;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Parse an IP address (auto-detect IPv4 or IPv6)
|
|
379
|
+
* Returns { value: BigInt, isIPv6: boolean } or null if invalid
|
|
380
|
+
*/
|
|
381
|
+
parseIP(ip) {
|
|
382
|
+
if (!ip || typeof ip !== 'string')
|
|
383
|
+
return null;
|
|
384
|
+
const trimmed = ip.trim();
|
|
385
|
+
// Try IPv4 first (contains dots, no colons)
|
|
386
|
+
if (trimmed.includes('.') && !trimmed.includes(':')) {
|
|
387
|
+
const value = this.parseIPv4(trimmed);
|
|
388
|
+
if (value !== null)
|
|
389
|
+
return { value, isIPv6: false };
|
|
390
|
+
}
|
|
391
|
+
// Try IPv6 (contains colons)
|
|
392
|
+
if (trimmed.includes(':')) {
|
|
393
|
+
const value = this.parseIPv6(trimmed);
|
|
394
|
+
if (value !== null)
|
|
395
|
+
return { value, isIPv6: true };
|
|
396
|
+
}
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
|
|
401
|
+
* Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
|
|
402
|
+
*/
|
|
403
|
+
parseCIDR(cidr) {
|
|
404
|
+
if (!cidr || typeof cidr !== 'string')
|
|
405
|
+
return null;
|
|
406
|
+
const parts = cidr.trim().split('/');
|
|
407
|
+
if (parts.length !== 2)
|
|
408
|
+
return null;
|
|
409
|
+
const ip = this.parseIP(parts[0]);
|
|
410
|
+
if (!ip)
|
|
411
|
+
return null;
|
|
412
|
+
const prefixLength = parseInt(parts[1], 10);
|
|
413
|
+
const maxPrefix = ip.isIPv6 ? 128 : 32;
|
|
414
|
+
if (isNaN(prefixLength) || prefixLength < 0 || prefixLength > maxPrefix)
|
|
415
|
+
return null;
|
|
416
|
+
// Calculate network address by masking
|
|
417
|
+
const totalBits = ip.isIPv6 ? 128 : 32;
|
|
418
|
+
const hostBits = totalBits - prefixLength;
|
|
419
|
+
const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
|
|
420
|
+
const network = ip.value & mask;
|
|
421
|
+
return { network, prefixLength, isIPv6: ip.isIPv6 };
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Check if an IP address is within a CIDR range
|
|
425
|
+
*/
|
|
426
|
+
isIpInCidr(ip, cidr) {
|
|
427
|
+
const parsedIp = this.parseIP(ip);
|
|
428
|
+
const parsedCidr = this.parseCIDR(cidr);
|
|
429
|
+
if (!parsedIp || !parsedCidr)
|
|
430
|
+
return false;
|
|
431
|
+
// IP version must match CIDR version
|
|
432
|
+
if (parsedIp.isIPv6 !== parsedCidr.isIPv6)
|
|
433
|
+
return false;
|
|
434
|
+
const totalBits = parsedIp.isIPv6 ? 128 : 32;
|
|
435
|
+
const hostBits = totalBits - parsedCidr.prefixLength;
|
|
436
|
+
const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
|
|
437
|
+
return (parsedIp.value & mask) === parsedCidr.network;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Check if a user's IP matches any of the allowed CIDRs
|
|
441
|
+
* Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
|
|
442
|
+
*/
|
|
443
|
+
checkCidrMatch(userIp, allowedCidrs) {
|
|
444
|
+
// If no CIDR restrictions, assignment is open to all
|
|
445
|
+
if (!allowedCidrs || allowedCidrs.length === 0)
|
|
446
|
+
return true;
|
|
447
|
+
// If CIDRs are specified but user has no IP, deny match
|
|
448
|
+
if (!userIp)
|
|
449
|
+
return false;
|
|
450
|
+
// Check if user IP matches any allowed CIDR
|
|
451
|
+
for (const cidr of allowedCidrs) {
|
|
452
|
+
if (this.isIpInCidr(userIp, cidr))
|
|
453
|
+
return true;
|
|
454
|
+
}
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
// ==================== End CIDR/IP Matching Utilities ====================
|
|
111
458
|
async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
|
|
112
459
|
const aTags = assignmentTags ? assignmentTags.split(',') : [];
|
|
113
460
|
const matchesPattern = (pattern, tag) => {
|
|
@@ -172,7 +519,7 @@ class AssignmentMatcher {
|
|
|
172
519
|
}
|
|
173
520
|
async calculatePriority(...args) {
|
|
174
521
|
const [assignment] = args;
|
|
175
|
-
return new Date().getTime() -
|
|
522
|
+
return new Date().getTime() - assignment?.createdAt || 0;
|
|
176
523
|
}
|
|
177
524
|
get stats() {
|
|
178
525
|
return (async () => {
|
|
@@ -208,7 +555,7 @@ class AssignmentMatcher {
|
|
|
208
555
|
.hExists(this.assignmentsRefKey, id)
|
|
209
556
|
.hGet(assignmentTagsKey, 'tags')
|
|
210
557
|
.exec();
|
|
211
|
-
const tags = (
|
|
558
|
+
const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
212
559
|
const multi = this.redisClient.multi();
|
|
213
560
|
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
214
561
|
if (existsRef) {
|
|
@@ -285,11 +632,15 @@ class AssignmentMatcher {
|
|
|
285
632
|
const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
|
|
286
633
|
const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
|
|
287
634
|
const rejectedKey = this.redisPrefix + `user:${user.id}:rejected`;
|
|
288
|
-
const
|
|
289
|
-
|
|
635
|
+
const unionKeysWithWeights = expandedPositive.map((pw) => ({
|
|
636
|
+
key: this.redisPrefix + `tag:${pw.tag}:assignments`,
|
|
637
|
+
weight: pw.weight
|
|
638
|
+
}));
|
|
290
639
|
const multi = this.redisClient.multi();
|
|
291
640
|
// Weighted union of positive tag assignment zsets
|
|
292
|
-
|
|
641
|
+
if (unionKeysWithWeights.length > 0) {
|
|
642
|
+
multi.zUnionStore(tempKey, unionKeysWithWeights);
|
|
643
|
+
}
|
|
293
644
|
const excludeKeys = [];
|
|
294
645
|
// Optional exclude set for zero-weight tags
|
|
295
646
|
if (finalZeroTags.length > 0) {
|
|
@@ -318,14 +669,27 @@ class AssignmentMatcher {
|
|
|
318
669
|
const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
|
|
319
670
|
batched.hGet(assignmentPriorityKey, 'priority');
|
|
320
671
|
batched.hGet(assignmentTagsKey, 'tags');
|
|
672
|
+
// Also fetch assignment JSON to access allowedCidrs for network matching
|
|
673
|
+
batched.hGet(this.assignmentsRefKey, assignmentId);
|
|
321
674
|
}
|
|
322
675
|
const flat = await batched.exec();
|
|
323
676
|
const details = [];
|
|
324
677
|
for (let i = 0; i < top.length; i++) {
|
|
325
678
|
const assignmentId = top[i].value;
|
|
326
|
-
const priority = Number(flat[i *
|
|
327
|
-
const tags = String(flat[i *
|
|
328
|
-
|
|
679
|
+
const priority = Number(flat[i * 3]) || 0;
|
|
680
|
+
const tags = String(flat[i * 3 + 1] || '');
|
|
681
|
+
const assignmentJson = flat[i * 3 + 2];
|
|
682
|
+
let allowedCidrs;
|
|
683
|
+
if (assignmentJson) {
|
|
684
|
+
try {
|
|
685
|
+
const parsed = JSON.parse(assignmentJson);
|
|
686
|
+
allowedCidrs = parsed.allowedCidrs;
|
|
687
|
+
}
|
|
688
|
+
catch {
|
|
689
|
+
// Ignore JSON parse errors
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
details.push({ id: assignmentId, basePriority: priority, tags, allowedCidrs });
|
|
329
693
|
}
|
|
330
694
|
// Prefer higher base priority first to satisfy tests and practical expectations
|
|
331
695
|
details.sort((a, b) => b.basePriority - a.basePriority);
|
|
@@ -333,6 +697,10 @@ class AssignmentMatcher {
|
|
|
333
697
|
for (const d of details) {
|
|
334
698
|
if (userAssignments.length >= this.maxUserBacklogSize)
|
|
335
699
|
break;
|
|
700
|
+
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
701
|
+
if (!this.checkCidrMatch(user.ip, d.allowedCidrs)) {
|
|
702
|
+
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
703
|
+
}
|
|
336
704
|
// Use custom matchScore (supports weights) for a final check and tie-break
|
|
337
705
|
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
|
|
338
706
|
if (score && combinedPriority) {
|
|
@@ -395,13 +763,13 @@ class AssignmentMatcher {
|
|
|
395
763
|
}
|
|
396
764
|
// Otherwise, process all users in parallel as before.
|
|
397
765
|
let users = [];
|
|
398
|
-
let cursor = 0;
|
|
766
|
+
let cursor = '0';
|
|
399
767
|
// Fetch all users in a single loop
|
|
400
768
|
do {
|
|
401
|
-
const { cursor: nextCursor,
|
|
402
|
-
users.push(...
|
|
769
|
+
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor);
|
|
770
|
+
users.push(...entries.map((t) => JSON.parse(t.value)));
|
|
403
771
|
cursor = nextCursor;
|
|
404
|
-
} while (cursor !== 0);
|
|
772
|
+
} while (cursor !== '0');
|
|
405
773
|
// Process users in parallel
|
|
406
774
|
await Promise.all(users.map(async (user) => {
|
|
407
775
|
const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
|
|
@@ -425,11 +793,17 @@ class AssignmentMatcher {
|
|
|
425
793
|
const isAssigned = await this.redisClient.sIsMember(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
426
794
|
if (!isAssigned)
|
|
427
795
|
throw new Error('Assignment not found for user');
|
|
796
|
+
// Get the assignment JSON before removing from pending
|
|
797
|
+
const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
|
|
428
798
|
const multi = this.redisClient.multi();
|
|
429
799
|
multi.sRem(this.redisPrefix + `user:${userId}:assignments`, `assignment:${assignmentId}`);
|
|
430
800
|
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
431
801
|
multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
|
|
432
802
|
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
803
|
+
// Store in accepted assignments
|
|
804
|
+
if (json) {
|
|
805
|
+
multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
|
|
806
|
+
}
|
|
433
807
|
await multi.exec();
|
|
434
808
|
return true;
|
|
435
809
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "assignment-user-matcher",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.6",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "https://github.com/ViljarVoidula/assignment-user-matcher"
|
|
7
|
+
},
|
|
4
8
|
"main": "dist/index.js",
|
|
5
9
|
"module": "dist/index.js",
|
|
6
10
|
"types": "dist/index.d.ts",
|
|
@@ -19,7 +23,7 @@
|
|
|
19
23
|
"license": "MIT",
|
|
20
24
|
"private": false,
|
|
21
25
|
"dependencies": {
|
|
22
|
-
"redis": "
|
|
26
|
+
"redis": "5.10.0"
|
|
23
27
|
},
|
|
24
28
|
"prettier": {
|
|
25
29
|
"semi": true,
|