assignment-user-matcher 1.0.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.
@@ -0,0 +1,84 @@
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 ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "extension": ["ts"],
3
+ "diff": true,
4
+ "recursive": true,
5
+ "exit": true,
6
+ "slow": 100,
7
+ "ui": "bdd",
8
+ "full-trace": true,
9
+ "spec": "tests/**/*.ts",
10
+ "require": ["ts-node/register"]
11
+ }
@@ -0,0 +1 @@
1
+ package.lock.json
@@ -0,0 +1,32 @@
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/README.md ADDED
@@ -0,0 +1,367 @@
1
+ # `match-assignment`: Lightning-Fast, Tag-Based User & Assignment Matching
2
+
3
+ [![npm version](https://badge.fury.io/js/match-assignment.svg)](https://badge.fury.io/js/match-assignment)
4
+ [![CI Pipeline](https://github.com/ViljarVoidula/assignment-user-matcher/actions/workflows/docker-build.yml/badge.svg)](https://github.com/ViljarVoidula/assignment-user-matcher/actions/workflows/docker-build.yml)
5
+ <!-- Add other badges if you have them, e.g., build status, test coverage -->
6
+
7
+ **Tired of inefficiently assigning tasks or struggling to connect the right users with the right work? `match-assignment` is a specialized Node.js library designed for high-performance, near real-time matching of a smaller pool of users to a large volume of assignments, primarily based on shared tags and priority.**
8
+
9
+ It leverages the speed and efficiency of Redis to deliver a robust solution perfect for scenarios like call centers, customer support queues, back-office operations, and more.
10
+
11
+ ## The Challenge: Efficiently Connecting Users to Work
12
+
13
+ In many applications, from customer service platforms to internal task management systems, the core challenge remains the same: how do you quickly and accurately assign incoming work (assignments) to the best available person (user)? This becomes particularly complex when dealing with:
14
+
15
+ * **Large volumes of incoming assignments:** Tasks can pile up quickly, demanding immediate attention.
16
+ * **Real-time requirements:** Users expect instant responses, and assignments need prompt handling.
17
+ * **Varying skill sets and priorities:** Not all users are equipped for all tasks, and some assignments are more critical than others.
18
+
19
+ Traditional matching systems can become bottlenecks, leading to delays, suboptimal pairings, and frustrated users or customers.
20
+
21
+ ## Introducing `match-assignment`: Your Solution for Smart Task Distribution
22
+
23
+ `match-assignment` tackles these challenges head-on by providing a specialized engine optimized for a common pattern: a relatively small, active set of users (like support agents or back-office staff) processing a continuous, large stream of assignments.
24
+
25
+ **Key Features:**
26
+
27
+ * **Tag-Based Matching:** Intelligently connect users and assignments based on an intersection of descriptive tags (e.g., skills, language, department).
28
+ * **Priority-Aware:** Ensure that high-priority assignments are surfaced and processed first.
29
+ * **Redis-Powered:** Utilizes Redis for its in-memory data structures, enabling blazing-fast lookups and operations.
30
+ * **Optimized for Specific Scenarios:** Excels where a smaller group of users handles a large number of assignments.
31
+ * **User Backlog Management:** Prevents users from being overwhelmed by limiting the number of assignments they can be tentatively matched with.
32
+
33
+ ## Why `match-assignment`?
34
+
35
+ * 🚀 **Speed:** Designed for near real-time performance, ensuring assignments are matched and delivered swiftly.
36
+ * 🎯 **Accuracy:** Improves the quality of matches by considering relevant tags and priorities.
37
+ * ⚙️ **Efficiency:** Optimizes resource allocation, ensuring users are working on the most appropriate and urgent tasks.
38
+ * 😌 **Improved Experience:** Leads to faster response times for customers and a more streamlined workflow for users.
39
+ * 💡 **Scalable (for its niche):** Handles a large throughput of assignments efficiently.
40
+
41
+ ## Core Concepts: How It Works
42
+
43
+ `match-assignment` operates on a few key principles:
44
+
45
+ 1. **Users and Assignments Have Tags:**
46
+ * **Users:** Each user is defined by an ID and a set of `tags` representing their skills, capabilities, or any other relevant attributes (e.g., `['english', 'billing_support', 'tier_1']`).
47
+ * **Assignments:** Each assignment has an ID, `tags` describing its requirements (e.g., `['english', 'billing_inquiry']`), and a `createdAt` timestamp (or a custom priority score) to determine its urgency.
48
+
49
+ 2. **Matching via Tag Intersection:**
50
+ The core matching logic finds users whose tags have a common intersection with an assignment's tags.
51
+
52
+ 3. **Prioritization Engine:**
53
+ Assignments are typically processed in the order they are received or by a custom prioritization function you can provide. This ensures that older or more critical assignments get attention first. The library aims to match the highest priority assignments to available, suitable users.
54
+
55
+ 4. **Redis as the Backbone:**
56
+ Redis is used to store user availability, assignment details, and manage the matching process. Its speed is crucial for the near real-time performance of the library. Users are maintained in sorted sets based on their backlog size and last activity, ensuring fair and efficient distribution.
57
+
58
+ 5. **User Backlog (`maxUserBacklogSize`):**
59
+ To prevent any single user from being assigned too many tasks at once (even if they are a match), `match-assignment` maintains a backlog for each user. New assignments are only matched if a user's backlog is below this threshold.
60
+
61
+ ## Real-World Use Cases
62
+
63
+ `match-assignment` is particularly well-suited for:
64
+
65
+ * **📞 Call Centers:** Routing incoming calls (assignments) to the agent (user) with the right language skills, product knowledge, and availability.
66
+ * **🎫 Customer Support Ticketing:** Assigning new support tickets to support agents based on their expertise (e.g., "technical_issue," "api_support") and the ticket's urgency.
67
+ * **🗄️ Back-Office Operations:** Distributing tasks like data entry, document verification, or claims processing to available staff members based on task type and employee skills.
68
+ * **🚗 Gig Economy Platforms (Niche):** Matching available service providers to incoming customer requests where the provider pool is managed and assignments are plentiful (e.g., a dispatch system for a fleet of delivery drivers).
69
+ * ** Leads Distribution:** Assigning sales leads to representatives based on territory, product specialization, or lead score.
70
+
71
+ ## Getting Started
72
+
73
+ ### 1. Installation
74
+
75
+ ```bash
76
+ npm install match-assignment redis
77
+ # or
78
+ yarn add match-assignment redis
79
+ # or
80
+ pnpm add match-assignment redis
81
+ ```
82
+
83
+ ### 2. Basic Usage
84
+
85
+ Here's a simple example to get you up and running:
86
+
87
+ ```javascript
88
+ import AssignmentMatcher from 'match-assignment'; // or `import { AssignmentMatcher } from 'match-assignment';`
89
+ import { createClient } from 'redis';
90
+
91
+ async function runExample() {
92
+ // Connect to your Redis instance
93
+ const redisClient = createClient({
94
+ // url: 'redis://your-redis-host:6379' // Optional: specify Redis URL if not default
95
+ });
96
+ await redisClient.connect();
97
+ console.log('Connected to Redis.');
98
+
99
+ const assignmentMatcher = new AssignmentMatcher(redisClient, {
100
+ redisPrefix: 'exampleApp:', // Good practice to namespace your Redis keys
101
+ maxUserBacklogSize: 5, // Max 5 assignments per user backlog
102
+ enableDefaultMatching: true
103
+ });
104
+
105
+ // Add a user
106
+ await assignmentMatcher.addUser({
107
+ id: 'agent_007',
108
+ tags: ['english', 'technical_support', 'vip_clients'],
109
+ });
110
+ console.log("User 'agent_007' added.");
111
+
112
+ // Add an assignment
113
+ await assignmentMatcher.addAssignment({
114
+ id: 'ticket_12345',
115
+ tags: ['english', 'technical_support'],
116
+ createdAt: new Date().getTime(), // Use current time for priority
117
+ });
118
+ console.log("Assignment 'ticket_12345' added.");
119
+
120
+ // Run the matching process
121
+ // This will attempt to match pending assignments to available users
122
+ console.log('Running matching process...');
123
+ await assignmentMatcher.matchUsersAssignments();
124
+
125
+ // Check current assignments for the user
126
+ const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser('agent_007');
127
+ console.log(`Assignments for 'agent_007':`, userAssignments);
128
+
129
+ if (userAssignments && userAssignments.length > 0) {
130
+ console.log(`User 'agent_007' is matched with assignment '${userAssignments[0].id}'.`);
131
+ } else {
132
+ console.log(`User 'agent_007' has no assignments currently.`);
133
+ }
134
+
135
+ // Clean up (optional, depending on your Redis setup)
136
+ // await redisClient.flushDb(); // Be careful with this in production!
137
+ await redisClient.quit();
138
+ console.log('Disconnected from Redis.');
139
+ }
140
+
141
+ runExample().catch(console.error);
142
+ ```
143
+
144
+ ## API Reference
145
+
146
+ The main class provided is `AssignmentMatcher`.
147
+
148
+ ### `new AssignmentMatcher(redisClient, options?)`
149
+
150
+ Creates a new `AssignmentMatcher` instance.
151
+
152
+ * `redisClient`: An initialized and connected `redis` client instance (version 4+).
153
+ * `options` (Optional): Configuration options for the matcher. See [Options](#options) below.
154
+
155
+ ### `addUser(user: User): Promise<void>`
156
+
157
+ Adds or updates a user in the system.
158
+
159
+ * `user`: An object representing the user.
160
+ * `id: string`: Unique identifier for the user.
161
+ * `tags: string[]`: Array of tags associated with the user.
162
+
163
+ ### `addAssignment(assignment: Assignment): Promise<void>`
164
+
165
+ Adds a new assignment to be matched.
166
+
167
+ * `assignment`: An object representing the assignment.
168
+ * `id: string`: Unique identifier for the assignment.
169
+ * `tags: string[]`: Array of tags required for the assignment.
170
+ * `createdAt: number`: Timestamp (e.g., `new Date().getTime()`) indicating when the assignment was created. Used for default prioritization (older assignments get higher priority). Can be influenced by `prioritizationFunction`.
171
+ * `priority?: number | string`: Optional explicit priority. If `prioritizationFunction` is used, this might be an input to it.
172
+
173
+ ### `matchUsersAssignments(): Promise<void>`
174
+
175
+ Triggers the matching process. This method iterates through pending assignments and tries to match them with suitable, available users based on tags and user backlog capacity.
176
+
177
+ ### `getCurrentAssignmentsForUser(userId: string): Promise<Assignment[]>`
178
+
179
+ Retrieves the current list of assignments that a user is tentatively matched with (i.e., in their backlog).
180
+
181
+ * `userId: string`: The ID of the user.
182
+
183
+ ### `removeUser(userId: string): Promise<void>`
184
+
185
+ Removes a user from the system and clears their assignment backlog.
186
+
187
+ ### `removeAssignment(assignmentId: string, tags: string[]): Promise<void>`
188
+
189
+ Removes a specific assignment from the system. Requires tags to efficiently locate the assignment in Redis.
190
+
191
+ ### `completeAssignmentForUser(userId: string, assignmentId: string): Promise<void>`
192
+
193
+ Marks an assignment as completed by a user, removing it from their backlog and potentially making them available for new assignments.
194
+
195
+ ## Options
196
+
197
+ You can pass an options object to the `AssignmentMatcher` constructor:
198
+
199
+ ```typescript
200
+ type Options = {
201
+ // How many of the highest-priority assignments to consider in one matching batch.
202
+ // A larger batch might find more matches but could be slower.
203
+ relevantBatchSize?: number; // Default: 50
204
+
205
+ // Prefix for all Redis keys used by this library. Useful for namespacing
206
+ // if you use the same Redis instance for multiple applications or purposes.
207
+ redisPrefix?: string; // Default: '' (empty string)
208
+
209
+ // The maximum number of assignments a user can have in their "tentative" backlog.
210
+ // Once a user reaches this limit, they won't be matched with new assignments
211
+ // until some are completed or removed.
212
+ maxUserBacklogSize?: number; // Default: 9
213
+
214
+ // Whether to enable the default tag-based matching logic.
215
+ // If set to false, you MUST provide a custom `matchingFunction`.
216
+ enableDefaultMatching?: boolean; // Default: true
217
+
218
+ // A custom function to determine the priority of an assignment.
219
+ // The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
220
+ // and should return a numerical priority score. Higher scores mean higher priority.
221
+ // Useful if `createdAt` is not sufficient for your prioritization needs.
222
+ prioritizationFunction?: (
223
+ ...args: (Assignment | undefined)[]
224
+ ) => Promise<number>;
225
+
226
+ // A custom function to determine if a user can be matched with an assignment
227
+ // and the "cost" or "rank" of that match.
228
+ // If `enableDefaultMatching` is true, this function can augment or override the default logic.
229
+ // If `enableDefaultMatching` is false, this function is solely responsible for matching.
230
+ // It should return a tuple: `[matchRank, userCost]`.
231
+ // - `matchRank`: A score indicating the quality of the match (higher is better).
232
+ // A rank of 0 or less means no match.
233
+ // - `userCost`: A score indicating the "cost" of assigning this task to this user
234
+ // (lower is better, used for tie-breaking among users).
235
+ matchingFunction?: (
236
+ user: User,
237
+ assignmentTags: string[],
238
+ assignmentPriority: number | string, // This is the score from prioritizationFunction or createdAt
239
+ assignmentId?: string
240
+ ) => Promise<[number, number]>;
241
+ };
242
+ ```
243
+
244
+ ## Detailed Example & Performance Insights
245
+
246
+ The following example demonstrates adding multiple users and assignments and then measures the performance of the matching process.
247
+
248
+ ```javascript
249
+ #!/usr/bin/env ./node_modules/.bin/ts-node-script
250
+ // Save this as example.ts and ensure you have ts-node and typescript installed
251
+ // npm install -D ts-node typescript
252
+ // Then run: ./example.ts
253
+
254
+ import AssignmentMatcher, { User, Assignment } from 'match-assignment';
255
+ import { createClient } from 'redis';
256
+
257
+ async function bootstrap(userCount: number, assignmentCount: number) {
258
+ const redisClient = await createClient({});
259
+ await redisClient.connect();
260
+ // It's good practice to clear keys for a fresh test run,
261
+ // but be VERY careful with flushDb in production.
262
+ // await redisClient.flushDb();
263
+
264
+
265
+ const assignmentMatcher = new AssignmentMatcher(redisClient, {
266
+ relevantBatchSize: 100, // Larger batch for testing
267
+ maxUserBacklogSize: 10,
268
+ redisPrefix: 'perfTest:',
269
+ });
270
+
271
+ console.log(`Setting up ${userCount} users and ${assignmentCount} assignments...`);
272
+
273
+ // Add Users
274
+ for (let i = 0; i < userCount; i++) {
275
+ await assignmentMatcher.addUser({
276
+ id: `user_${i}`,
277
+ tags: ['tag1', 'tag2', `unique_skill_${i % 10}`], // Varied tags
278
+ });
279
+ }
280
+
281
+ // Add Assignments
282
+ for (let i = 0; i < assignmentCount; i++) {
283
+ await assignmentMatcher.addAssignment({
284
+ id: `assignment_${i}`,
285
+ tags: ['tag1', `unique_skill_${i % 10}`], // Ensure some matches
286
+ createdAt: new Date().getTime() + i, // Stagger creation time slightly
287
+ });
288
+ }
289
+ console.log('Setup complete.');
290
+
291
+ // --- Performance Measurement for Matching ---
292
+ performance.mark('match-start');
293
+ await assignmentMatcher.matchUsersAssignments();
294
+ performance.mark('match-end');
295
+ const matchMeasure = performance.measure('Matching Process', 'match-start', 'match-end');
296
+ console.log(`Matching execution time: ${matchMeasure.duration.toFixed(2)}ms`);
297
+
298
+ // --- Performance Measurement for Retrieving Assignments ---
299
+ performance.mark('current-assignment-start');
300
+ // Let's check assignments for a few users
301
+ for (let j = 0; j < Math.min(userCount, 5); j++) {
302
+ await assignmentMatcher.getCurrentAssignmentsForUser(`user_${j}`);
303
+ }
304
+ performance.mark('current-assignment-end');
305
+ const currentTaskMeasure = performance.measure(
306
+ 'Retrieving User Assignments (for 5 users)',
307
+ 'current-assignment-start',
308
+ 'current-assignment-end'
309
+ );
310
+ console.log(`Current assignment retrieval time: ${currentTaskMeasure.duration.toFixed(2)}ms`);
311
+
312
+ // Example: Log assignments for the first user
313
+ if (userCount > 0) {
314
+ const firstUserAssignments = await assignmentMatcher.getCurrentAssignmentsForUser('user_0');
315
+ console.log(`User 'user_0' has ${firstUserAssignments.length} assignments.`);
316
+ // firstUserAssignments.forEach(asgn => console.log(` - Assignment ID: ${asgn.id}, Tags: ${asgn.tags.join(', ')}`));
317
+ }
318
+
319
+ console.log(
320
+ `
321
+ Summary:
322
+ Users: ${userCount}
323
+ Assignments: ${assignmentCount}
324
+ Matching Duration: ${matchMeasure.duration.toFixed(2)}ms
325
+ Retrieval Duration (5 users): ${currentTaskMeasure.duration.toFixed(2)}ms`
326
+ );
327
+
328
+ await redisClient.quit();
329
+ }
330
+
331
+ // Adjust these numbers to test different scales
332
+ const USER_COUNT = 100;
333
+ const ASSIGNMENT_COUNT = 10000;
334
+
335
+ bootstrap(USER_COUNT, ASSIGNMENT_COUNT)
336
+ .then(() => {
337
+ console.log('Performance test finished.');
338
+ // process.exit(0); // Exit cleanly
339
+ })
340
+ .catch((err) => {
341
+ console.error('Error during bootstrap:', err);
342
+ // process.exit(1);
343
+ });
344
+ ```
345
+
346
+ ## Important Considerations (Disclaimer)
347
+
348
+ * **Optimized for a Specific Use Case:** `match-assignment` is primarily designed and optimized for scenarios with a **relatively small set of active users processing a large volume of incoming assignments** (e.g., call centers, customer support teams, back-office operations). While it might work for other scenarios, its performance characteristics are best suited for this model.
349
+ * **Redis Dependency:** This library requires a running Redis instance. Ensure your Redis server is adequately provisioned for your workload.
350
+ * **Near Real-Time, Not Instantaneous:** While fast, the matching process involves Redis operations and logic execution. "Near real-time" means it's quick, but not strictly instantaneous with nanosecond precision. The `matchUsersAssignments()` method needs to be called periodically or triggered by events (e.g., new assignment, user becomes available) to perform matching.
351
+
352
+ ## Contributing
353
+
354
+ Contributions are welcome! If you have ideas for improvements, new features, or bug fixes, please feel free to:
355
+
356
+ 1. Fork the repository.
357
+ 2. Create a new branch for your feature or fix.
358
+ 3. Make your changes.
359
+ 4. Add tests for your changes.
360
+ 5. Ensure all tests pass.
361
+ 6. Submit a pull request.
362
+
363
+ Please open an issue first to discuss significant changes.
364
+
365
+ ## License
366
+
367
+ This library is licensed under the MIT License. (Assuming MIT - please update if incorrect)
package/docs/README.md ADDED
@@ -0,0 +1,109 @@
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
+ ```