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
package/LICENCE
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
This Strict Commercial License ("License") is a legal agreement between the Owner identified below ("Owner") and any natural person or legal entity that receives, accesses, or uses the Software ("Recipient"). By receiving, accessing, or using the Software, Recipient acknowledges and agrees to the terms below. All capitalized terms not otherwise defined herein have the meanings given in Section 1.
|
|
2
|
+
|
|
3
|
+
1. Definitions
|
|
4
|
+
- "Software" means the source code, binaries, documentation, designs, examples, data, configuration, and any other materials provided by Owner.
|
|
5
|
+
- "Use" means to copy, execute, run, display, distribute, host, provide as a service, sublicense, or otherwise employ the Software.
|
|
6
|
+
- "Modify" means to alter, adapt, translate, create derivative works of, reverse engineer, decompile, disassemble, or otherwise change the Software.
|
|
7
|
+
|
|
8
|
+
2. No Grant
|
|
9
|
+
- Except for a specific, express, written license signed by Owner, no rights, licenses, or permissions are granted to Recipient, whether by implication, estoppel, or otherwise. Owner expressly reserves all rights in the Software.
|
|
10
|
+
|
|
11
|
+
3. Prohibited Acts
|
|
12
|
+
- Without Owner's prior written permission, Recipient shall not, directly or indirectly, Use, copy, publish, distribute, sublicense, make available, or Modify the Software in whole or in part.
|
|
13
|
+
- Recipient shall not remove, alter, or obscure any proprietary, copyright, or other notices in or on the Software, nor attempt to bypass technological restrictions or authentication controls.
|
|
14
|
+
|
|
15
|
+
4. Remedies; Liquidated Damages; Fees
|
|
16
|
+
- Each unauthorized Use or Modification of the Software (each an "Infringing Act") shall constitute a material breach and an actionable wrong.
|
|
17
|
+
- For each Infringing Act, Recipient agrees that Owner shall be entitled to recover liquidated damages in the amount of USD 250,000 (Two Hundred Fifty Thousand United States Dollars) per Infringing Act, which the parties agree is a reasonable pre-estimate of damages and not a penalty. In addition, Owner may recover:
|
|
18
|
+
- disgorgement of all profits and revenues derived from the Infringing Act;
|
|
19
|
+
- statutory damages available under applicable law (if greater than the liquidated damages amount);
|
|
20
|
+
- pre-judgment and post-judgment interest at the highest lawful rate;
|
|
21
|
+
- Owner's reasonable attorneys' fees, costs, and expenses incurred to investigate or enforce this License; and
|
|
22
|
+
- any other equitable or legal relief available, including injunctive and declaratory relief.
|
|
23
|
+
- The remedies in this Section are cumulative, not exclusive, and shall not limit other remedies at law or in equity. Owner need not post a bond to obtain injunctive relief.
|
|
24
|
+
|
|
25
|
+
5. Indemnity
|
|
26
|
+
- Recipient shall indemnify, defend, and hold Owner harmless from and against any and all claims, liabilities, losses, damages, costs and expenses (including reasonable attorneys' fees) arising from any unauthorized Use, Modification, distribution, or other breach of this License.
|
|
27
|
+
|
|
28
|
+
6. Termination and Return
|
|
29
|
+
- Owner may terminate this License immediately upon written notice if Recipient commits any breach, including any Infringing Act. Upon termination, Recipient shall immediately cease all Use of the Software and destroy or return all copies of the Software and related materials and certify such destruction or return in writing to Owner.
|
|
30
|
+
|
|
31
|
+
7. Preservation of Notices
|
|
32
|
+
- Recipient shall not remove, alter, or obscure any copyright, trademark, patent, or other proprietary notices, legends, or labels contained in or on the Software.
|
|
33
|
+
|
|
34
|
+
8. Warranty Disclaimer
|
|
35
|
+
- THE SOFTWARE IS PROVIDED "AS IS" AND OWNER DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NONINFRINGEMENT. THIS DISCLAIMER DOES NOT AFFECT OWNER'S RIGHT TO SEEK EQUITABLE RELIEF OR DAMAGES FOR UNAUTHORIZED USE.
|
|
36
|
+
|
|
37
|
+
9. Limitation of Liability
|
|
38
|
+
- EXCEPT FOR OWNER'S RIGHTS AND REMEDIES FOR UNAUTHORIZED USE (WHICH ARE PRESERVED), IN NO EVENT SHALL OWNER BE LIABLE TO RECIPIENT FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL, PUNITIVE, OR EXEMPLARY DAMAGES ARISING OUT OF OR RELATED TO THIS LICENSE OR THE SOFTWARE, WHETHER IN CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR OTHERWISE.
|
|
39
|
+
|
|
40
|
+
10. Governing Law and Venue
|
|
41
|
+
- This License shall be governed by and construed in accordance with the laws of [INSERT STATE/PROVINCE/COUNTRY], without regard to its conflicts of laws rules. The exclusive venue and jurisdiction for any dispute arising out of or related to this License shall be the state and federal courts located in [INSERT CITY, STATE/PROVINCE/COUNTRY]. Recipient consents to personal jurisdiction in those courts.
|
|
42
|
+
|
|
43
|
+
11. Severability; Waiver; Entire Agreement
|
|
44
|
+
- If any provision of this License is held to be invalid or unenforceable, the remainder of this License shall remain in full force and effect. No waiver by Owner of any breach shall be deemed a waiver of any other or subsequent breach. This License constitutes the entire agreement between the parties regarding the subject matter hereof.
|
|
45
|
+
|
|
46
|
+
12. Effective Date 21/05/2025 or since intiial commit of this repository
|
|
47
|
+
- Effective Date: the date Recipient first receives, accesses, or uses the Software.
|
|
48
|
+
- Owner: Viljar Võidula
|
|
49
|
+
- Contact: viljar@forgemaster.ai
|
|
50
|
+
|
|
51
|
+
Footnote — Non-Commercial Fair Use
|
|
52
|
+
- As a limited exception to Sections 2 and 3, non-commercial fair use (e.g., academic evaluation, internal demonstrations, code review excerpts) is permitted provided that, prior to any such use, Recipient contacts the Owner at viljar@forgemaster.ai and receives written confirmation authorizing the specific use.
|
|
53
|
+
- Any such authorization is non-exclusive, non-transferable, revocable at any time, and may be conditioned on additional terms. All other provisions of this License remain in full force and effect unless explicitly modified in the written confirmation.
|
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://badge.fury.io/js/assignment-user-matcher)
|
|
4
4
|
[](https://github.com/ViljarVoidula/assignment-user-matcher/actions/workflows/npm-publish.yml)
|
|
5
|
+
|
|
5
6
|
<!-- Add other badges if you have them, e.g., build status, test coverage -->
|
|
6
7
|
|
|
7
8
|
**Tired of inefficiently assigning tasks or struggling to connect the right users with the right work? `assignment-user-matcher` 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.**
|
|
@@ -12,9 +13,9 @@ It leverages the speed and efficiency of Redis to deliver a robust solution perf
|
|
|
12
13
|
|
|
13
14
|
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
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
- **Large volumes of incoming assignments:** Tasks can pile up quickly, demanding immediate attention.
|
|
17
|
+
- **Real-time requirements:** Users expect instant responses, and assignments need prompt handling.
|
|
18
|
+
- **Varying skill sets and priorities:** Not all users are equipped for all tasks, and some assignments are more critical than others.
|
|
18
19
|
|
|
19
20
|
Traditional matching systems can become bottlenecks, leading to delays, suboptimal pairings, and frustrated users or customers.
|
|
20
21
|
|
|
@@ -24,27 +25,28 @@ Traditional matching systems can become bottlenecks, leading to delays, suboptim
|
|
|
24
25
|
|
|
25
26
|
**Key Features:**
|
|
26
27
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
28
|
+
- **Tag-Based Matching:** Intelligently connect users and assignments based on an intersection of descriptive tags (e.g., skills, language, department).
|
|
29
|
+
- **Priority-Aware:** Ensure that high-priority assignments are surfaced and processed first.
|
|
30
|
+
- **Redis-Powered:** Utilizes Redis for its in-memory data structures, enabling blazing-fast lookups and operations.
|
|
31
|
+
- **Optimized for Specific Scenarios:** Excels where a smaller group of users handles a large number of assignments.
|
|
32
|
+
- **User Backlog Management:** Prevents users from being overwhelmed by limiting the number of assignments they can be tentatively matched with.
|
|
32
33
|
|
|
33
34
|
## Why `assignment-user-matcher`?
|
|
34
35
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
- 🚀 **Speed:** Designed for near real-time performance, ensuring assignments are matched and delivered swiftly.
|
|
37
|
+
- 🎯 **Accuracy:** Improves the quality of matches by considering relevant tags and priorities.
|
|
38
|
+
- ⚙️ **Efficiency:** Optimizes resource allocation, ensuring users are working on the most appropriate and urgent tasks.
|
|
39
|
+
- 😌 **Improved Experience:** Leads to faster response times for customers and a more streamlined workflow for users.
|
|
40
|
+
- 💡 **Scalable (for its niche):** Handles a large throughput of assignments efficiently.
|
|
40
41
|
|
|
41
42
|
## Core Concepts: How It Works
|
|
42
43
|
|
|
43
44
|
`assignment-user-matcher` operates on a few key principles:
|
|
44
45
|
|
|
45
46
|
1. **Users and Assignments Have Tags:**
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
|
|
48
|
+
- **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']`).
|
|
49
|
+
- **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
50
|
|
|
49
51
|
2. **Matching via Tag Intersection:**
|
|
50
52
|
The core matching logic finds users whose tags have a common intersection with an assignment's tags.
|
|
@@ -62,11 +64,11 @@ Traditional matching systems can become bottlenecks, leading to delays, suboptim
|
|
|
62
64
|
|
|
63
65
|
`assignment-user-matcher` is particularly well-suited for:
|
|
64
66
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
- **📞 Call Centers:** Routing incoming calls (assignments) to the agent (user) with the right language skills, product knowledge, and availability.
|
|
68
|
+
- **🎫 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.
|
|
69
|
+
- **🗄️ Back-Office Operations:** Distributing tasks like data entry, document verification, or claims processing to available staff members based on task type and employee skills.
|
|
70
|
+
- **🚗 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).
|
|
71
|
+
- ** Leads Distribution:** Assigning sales leads to representatives based on territory, product specialization, or lead score.
|
|
70
72
|
|
|
71
73
|
## Getting Started
|
|
72
74
|
|
|
@@ -89,53 +91,53 @@ import AssignmentMatcher from 'assignment-user-matcher'; // or `import { Assignm
|
|
|
89
91
|
import { createClient } from 'redis';
|
|
90
92
|
|
|
91
93
|
async function runExample() {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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();
|
|
94
|
+
// Connect to your Redis instance
|
|
95
|
+
const redisClient = createClient({
|
|
96
|
+
// url: 'redis://your-redis-host:6379' // Optional: specify Redis URL if not default
|
|
97
|
+
});
|
|
98
|
+
await redisClient.connect();
|
|
99
|
+
console.log('Connected to Redis.');
|
|
124
100
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
101
|
+
const assignmentMatcher = new AssignmentMatcher(redisClient, {
|
|
102
|
+
redisPrefix: 'exampleApp:', // Good practice to namespace your Redis keys
|
|
103
|
+
maxUserBacklogSize: 5, // Max 5 assignments per user backlog
|
|
104
|
+
enableDefaultMatching: true,
|
|
105
|
+
});
|
|
128
106
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
107
|
+
// Add a user
|
|
108
|
+
await assignmentMatcher.addUser({
|
|
109
|
+
id: 'agent_007',
|
|
110
|
+
tags: ['english', 'technical_support', 'vip_clients'],
|
|
111
|
+
});
|
|
112
|
+
console.log("User 'agent_007' added.");
|
|
134
113
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
114
|
+
// Add an assignment
|
|
115
|
+
await assignmentMatcher.addAssignment({
|
|
116
|
+
id: 'ticket_12345',
|
|
117
|
+
tags: ['english', 'technical_support'],
|
|
118
|
+
createdAt: new Date().getTime(), // Use current time for priority
|
|
119
|
+
});
|
|
120
|
+
console.log("Assignment 'ticket_12345' added.");
|
|
121
|
+
|
|
122
|
+
// Run the matching process
|
|
123
|
+
// This will attempt to match pending assignments to available users
|
|
124
|
+
console.log('Running matching process...');
|
|
125
|
+
await assignmentMatcher.matchUsersAssignments();
|
|
126
|
+
|
|
127
|
+
// Check current assignments for the user
|
|
128
|
+
const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser('agent_007');
|
|
129
|
+
console.log(`Assignments for 'agent_007':`, userAssignments);
|
|
130
|
+
|
|
131
|
+
if (userAssignments && userAssignments.length > 0) {
|
|
132
|
+
console.log(`User 'agent_007' is matched with assignment '${userAssignments[0].id}'.`);
|
|
133
|
+
} else {
|
|
134
|
+
console.log(`User 'agent_007' has no assignments currently.`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Clean up (optional, depending on your Redis setup)
|
|
138
|
+
// await redisClient.flushDb(); // Be careful with this in production!
|
|
139
|
+
await redisClient.quit();
|
|
140
|
+
console.log('Disconnected from Redis.');
|
|
139
141
|
}
|
|
140
142
|
|
|
141
143
|
runExample().catch(console.error);
|
|
@@ -149,26 +151,26 @@ The main class provided is `AssignmentMatcher`.
|
|
|
149
151
|
|
|
150
152
|
Creates a new `AssignmentMatcher` instance.
|
|
151
153
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
+
- `redisClient`: An initialized and connected `redis` client instance (version 4+).
|
|
155
|
+
- `options` (Optional): Configuration options for the matcher. See [Options](#options) below.
|
|
154
156
|
|
|
155
157
|
### `addUser(user: User): Promise<void>`
|
|
156
158
|
|
|
157
159
|
Adds or updates a user in the system.
|
|
158
160
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
161
|
+
- `user`: An object representing the user.
|
|
162
|
+
- `id: string`: Unique identifier for the user.
|
|
163
|
+
- `tags: string[]`: Array of tags associated with the user.
|
|
162
164
|
|
|
163
165
|
### `addAssignment(assignment: Assignment): Promise<void>`
|
|
164
166
|
|
|
165
167
|
Adds a new assignment to be matched.
|
|
166
168
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
169
|
+
- `assignment`: An object representing the assignment.
|
|
170
|
+
- `id: string`: Unique identifier for the assignment.
|
|
171
|
+
- `tags: string[]`: Array of tags required for the assignment.
|
|
172
|
+
- `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`.
|
|
173
|
+
- `priority?: number | string`: Optional explicit priority. If `prioritizationFunction` is used, this might be an input to it.
|
|
172
174
|
|
|
173
175
|
### `matchUsersAssignments(): Promise<void>`
|
|
174
176
|
|
|
@@ -178,7 +180,7 @@ Triggers the matching process. This method iterates through pending assignments
|
|
|
178
180
|
|
|
179
181
|
Retrieves the current list of assignments that a user is tentatively matched with (i.e., in their backlog).
|
|
180
182
|
|
|
181
|
-
|
|
183
|
+
- `userId: string`: The ID of the user.
|
|
182
184
|
|
|
183
185
|
### `removeUser(userId: string): Promise<void>`
|
|
184
186
|
|
|
@@ -198,46 +200,44 @@ You can pass an options object to the `AssignmentMatcher` constructor:
|
|
|
198
200
|
|
|
199
201
|
```typescript
|
|
200
202
|
type Options = {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
assignmentId?: string
|
|
240
|
-
) => Promise<[number, number]>;
|
|
203
|
+
// How many of the highest-priority assignments to consider in one matching batch.
|
|
204
|
+
// A larger batch might find more matches but could be slower.
|
|
205
|
+
relevantBatchSize?: number; // Default: 50
|
|
206
|
+
|
|
207
|
+
// Prefix for all Redis keys used by this library. Useful for namespacing
|
|
208
|
+
// if you use the same Redis instance for multiple applications or purposes.
|
|
209
|
+
redisPrefix?: string; // Default: '' (empty string)
|
|
210
|
+
|
|
211
|
+
// The maximum number of assignments a user can have in their "tentative" backlog.
|
|
212
|
+
// Once a user reaches this limit, they won't be matched with new assignments
|
|
213
|
+
// until some are completed or removed.
|
|
214
|
+
maxUserBacklogSize?: number; // Default: 9
|
|
215
|
+
|
|
216
|
+
// Whether to enable the default tag-based matching logic.
|
|
217
|
+
// If set to false, you MUST provide a custom `matchingFunction`.
|
|
218
|
+
enableDefaultMatching?: boolean; // Default: true
|
|
219
|
+
|
|
220
|
+
// A custom function to determine the priority of an assignment.
|
|
221
|
+
// The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
|
|
222
|
+
// and should return a numerical priority score. Higher scores mean higher priority.
|
|
223
|
+
// Useful if `createdAt` is not sufficient for your prioritization needs.
|
|
224
|
+
prioritizationFunction?: (...args: (Assignment | undefined)[]) => 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
241
|
};
|
|
242
242
|
```
|
|
243
243
|
|
|
@@ -246,7 +246,6 @@ type Options = {
|
|
|
246
246
|
The following example demonstrates adding multiple users and assignments and then measures the performance of the matching process.
|
|
247
247
|
|
|
248
248
|
```javascript
|
|
249
|
-
#!/usr/bin/env ./node_modules/.bin/ts-node-script
|
|
250
249
|
// Save this as example.ts and ensure you have ts-node and typescript installed
|
|
251
250
|
// npm install -D ts-node typescript
|
|
252
251
|
// Then run: ./example.ts
|
|
@@ -259,7 +258,7 @@ async function bootstrap(userCount: number, assignmentCount: number) {
|
|
|
259
258
|
await redisClient.connect();
|
|
260
259
|
// It's good practice to clear keys for a fresh test run,
|
|
261
260
|
// but be VERY careful with flushDb in production.
|
|
262
|
-
|
|
261
|
+
await redisClient.flushDb();
|
|
263
262
|
|
|
264
263
|
|
|
265
264
|
const assignmentMatcher = new AssignmentMatcher(redisClient, {
|
|
@@ -274,7 +273,7 @@ async function bootstrap(userCount: number, assignmentCount: number) {
|
|
|
274
273
|
for (let i = 0; i < userCount; i++) {
|
|
275
274
|
await assignmentMatcher.addUser({
|
|
276
275
|
id: `user_${i}`,
|
|
277
|
-
tags: ['tag1', 'tag2', `unique_skill_${i %
|
|
276
|
+
tags: ['tag1', 'tag2', `unique_skill_${i % 5}`], // Varied tags with smaller modulo for more matches
|
|
278
277
|
});
|
|
279
278
|
}
|
|
280
279
|
|
|
@@ -282,55 +281,79 @@ async function bootstrap(userCount: number, assignmentCount: number) {
|
|
|
282
281
|
for (let i = 0; i < assignmentCount; i++) {
|
|
283
282
|
await assignmentMatcher.addAssignment({
|
|
284
283
|
id: `assignment_${i}`,
|
|
285
|
-
tags: ['tag1', `unique_skill_${i %
|
|
284
|
+
tags: ['tag1', `unique_skill_${i % 5}`], // Ensure more matches
|
|
286
285
|
createdAt: new Date().getTime() + i, // Stagger creation time slightly
|
|
287
286
|
});
|
|
288
287
|
}
|
|
289
288
|
console.log('Setup complete.');
|
|
290
289
|
|
|
291
|
-
// --- Performance Measurement for Matching ---
|
|
290
|
+
// --- Performance Measurement for Initial Matching ---
|
|
291
|
+
console.log('Performing initial matching...');
|
|
292
292
|
performance.mark('match-start');
|
|
293
293
|
await assignmentMatcher.matchUsersAssignments();
|
|
294
294
|
performance.mark('match-end');
|
|
295
|
-
const matchMeasure = performance.measure('Matching Process', 'match-start', 'match-end');
|
|
296
|
-
console.log(`
|
|
297
|
-
|
|
298
|
-
// ---
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
295
|
+
const matchMeasure = performance.measure('Initial Matching Process', 'match-start', 'match-end');
|
|
296
|
+
console.log(`Initial matching execution time: ${matchMeasure.duration.toFixed(2)}ms`);
|
|
297
|
+
|
|
298
|
+
// --- Log initial assignments for all users ---
|
|
299
|
+
console.log('\nInitial assignments for users:');
|
|
300
|
+
for (let i = 0; i < userCount; i++) {
|
|
301
|
+
const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser(`user_${i}`);
|
|
302
|
+
console.log(`User 'user_${i}' has ${userAssignments.length} assignments.`);
|
|
303
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
304
|
|
|
312
|
-
//
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
305
|
+
// --- Simulate completing assignments ---
|
|
306
|
+
console.log('\nSimulating users completing assignments...');
|
|
307
|
+
for (let i = 0; i < userCount; i++) {
|
|
308
|
+
// Only process for the first 15 users
|
|
309
|
+
if (i >= 15) break;
|
|
310
|
+
|
|
311
|
+
// Get the current assignments for this user
|
|
312
|
+
const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser(`user_${i}`);
|
|
313
|
+
|
|
314
|
+
if (userAssignments.length > 0) {
|
|
315
|
+
// Simulate completing half of the assignments
|
|
316
|
+
const assignmentsToComplete = userAssignments.slice(0, Math.ceil(userAssignments.length / 2));
|
|
317
|
+
console.log(`User 'user_${i}' completing ${assignmentsToComplete.length} assignments...`);
|
|
318
|
+
|
|
319
|
+
// Remove these assignments from the user's queue
|
|
320
|
+
for (const assignmentId of assignmentsToComplete) {
|
|
321
|
+
await redisClient.sRem(assignmentMatcher.redisPrefix + `user:user_${i}:assignments`, `assignment:${assignmentId}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// --- Perform another matching after completion ---
|
|
327
|
+
console.log('\nPerforming second matching after assignment completion...');
|
|
328
|
+
performance.mark('rematch-start');
|
|
329
|
+
await assignmentMatcher.matchUsersAssignments();
|
|
330
|
+
performance.mark('rematch-end');
|
|
331
|
+
const rematchMeasure = performance.measure('Second Matching Process', 'rematch-start', 'rematch-end');
|
|
332
|
+
console.log(`Second matching execution time: ${rematchMeasure.duration.toFixed(2)}ms`);
|
|
333
|
+
|
|
334
|
+
// --- Final check of assignments for all users ---
|
|
335
|
+
console.log('\nFinal assignments for users:');
|
|
336
|
+
for (let i = 0; i < userCount; i++) {
|
|
337
|
+
if (i >= 15) break; // Only show for the first 15 users
|
|
338
|
+
const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser(`user_${i}`);
|
|
339
|
+
console.log(`User 'user_${i}' now has ${userAssignments.length} assignments.`);
|
|
317
340
|
}
|
|
318
341
|
|
|
319
342
|
console.log(
|
|
320
343
|
`
|
|
321
344
|
Summary:
|
|
322
|
-
Users: ${userCount}
|
|
345
|
+
Users: ${userCount} (simulated 15 users completing assignments)
|
|
323
346
|
Assignments: ${assignmentCount}
|
|
324
|
-
Matching Duration: ${matchMeasure.duration.toFixed(2)}ms
|
|
325
|
-
|
|
347
|
+
Initial Matching Duration: ${matchMeasure.duration.toFixed(2)}ms
|
|
348
|
+
Second Matching Duration: ${rematchMeasure.duration.toFixed(2)}ms`
|
|
326
349
|
);
|
|
327
350
|
|
|
328
351
|
await redisClient.quit();
|
|
329
352
|
}
|
|
330
353
|
|
|
331
354
|
// Adjust these numbers to test different scales
|
|
332
|
-
const USER_COUNT =
|
|
333
|
-
const ASSIGNMENT_COUNT =
|
|
355
|
+
const USER_COUNT = 30;
|
|
356
|
+
const ASSIGNMENT_COUNT = 150000;
|
|
334
357
|
|
|
335
358
|
bootstrap(USER_COUNT, ASSIGNMENT_COUNT)
|
|
336
359
|
.then(() => {
|
|
@@ -343,11 +366,26 @@ bootstrap(USER_COUNT, ASSIGNMENT_COUNT)
|
|
|
343
366
|
});
|
|
344
367
|
```
|
|
345
368
|
|
|
369
|
+
### Example Performance Results
|
|
370
|
+
|
|
371
|
+
When running the above example with 30 users and 150,000 assignments, you might see results similar to this:
|
|
372
|
+
|
|
373
|
+
```
|
|
374
|
+
Summary:
|
|
375
|
+
Users: 30 (simulated 15 users completing assignments)
|
|
376
|
+
Assignments: 150000
|
|
377
|
+
Initial Matching Duration: 3.83ms
|
|
378
|
+
Second Matching Duration: 0.83ms
|
|
379
|
+
Performance test finished.
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
This demonstrates the library's impressive performance even with large numbers of assignments and shows how subsequent matching operations can be even faster after initial assignment distribution.
|
|
383
|
+
|
|
346
384
|
## Important Considerations (Disclaimer)
|
|
347
385
|
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
386
|
+
- **Optimized for a Specific Use Case:** `assignment-user-matcher` 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.
|
|
387
|
+
- **Redis Dependency:** This library requires a running Redis instance. Ensure your Redis server is adequately provisioned for your workload.
|
|
388
|
+
- **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
389
|
|
|
352
390
|
## Contributing
|
|
353
391
|
|
|
@@ -362,6 +400,16 @@ Contributions are welcome! If you have ideas for improvements, new features, or
|
|
|
362
400
|
|
|
363
401
|
Please open an issue first to discuss significant changes.
|
|
364
402
|
|
|
403
|
+
## Packaging & Publishing
|
|
404
|
+
|
|
405
|
+
The npm package only ships the compiled artifacts in `dist/`. Before publishing:
|
|
406
|
+
|
|
407
|
+
1. Install dependencies: `pnpm install`
|
|
408
|
+
2. Build the library: `pnpm run build`
|
|
409
|
+
3. (Optional) Inspect the publish payload: `pnpm pack --dry-run`
|
|
410
|
+
|
|
411
|
+
Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `const { AssignmentMatcher } = require('assignment-user-matcher')` without running TypeScript themselves.
|
|
412
|
+
|
|
365
413
|
## License
|
|
366
414
|
|
|
367
415
|
This library is licensed under the MIT License. (Assuming MIT - please update if incorrect)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.AssignmentMatcher = void 0;
|
|
7
|
+
const matcher_class_1 = __importDefault(require("./matcher.class"));
|
|
8
|
+
exports.AssignmentMatcher = matcher_class_1.default;
|
|
9
|
+
exports.default = matcher_class_1.default;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createClient } from 'redis';
|
|
2
|
+
export type RedisClientType = ReturnType<typeof createClient>;
|
|
3
|
+
export interface User {
|
|
4
|
+
id: string;
|
|
5
|
+
tags: string[];
|
|
6
|
+
routingWeights?: Record<string, number>;
|
|
7
|
+
[key: string]: any;
|
|
8
|
+
}
|
|
9
|
+
export type Assignment = {
|
|
10
|
+
id: string;
|
|
11
|
+
tags: string[];
|
|
12
|
+
priority?: number;
|
|
13
|
+
[key: string]: any;
|
|
14
|
+
};
|
|
15
|
+
export type Stats = {
|
|
16
|
+
users?: number;
|
|
17
|
+
usersWithoutAssignment?: string[];
|
|
18
|
+
remainingAssignments?: number;
|
|
19
|
+
};
|
|
20
|
+
export type options = {
|
|
21
|
+
relevantBatchSize?: number;
|
|
22
|
+
redisPrefix?: string;
|
|
23
|
+
maxUserBacklogSize?: number;
|
|
24
|
+
enableDefaultMatching?: boolean;
|
|
25
|
+
prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
|
|
26
|
+
matchingFunction?: (user: User, assignmentTags: string, assignmentPriority: number | string, assignmentId?: string) => Promise<[number, number]>;
|
|
27
|
+
};
|
|
28
|
+
export default class AssignmentMatcher {
|
|
29
|
+
redisClient: RedisClientType;
|
|
30
|
+
relevantBatchSize: number;
|
|
31
|
+
redisPrefix: string;
|
|
32
|
+
assignmentsKey: string;
|
|
33
|
+
assignmentsRefKey: string;
|
|
34
|
+
usersKey: string;
|
|
35
|
+
maxUserBacklogSize: number;
|
|
36
|
+
enableDefaultMatching: boolean;
|
|
37
|
+
constructor(redisClient: RedisClientType, options?: options);
|
|
38
|
+
private initRedis;
|
|
39
|
+
addUser(user: User): Promise<User>;
|
|
40
|
+
addAssignment(assignment: Assignment): Promise<Assignment>;
|
|
41
|
+
removeAssignment(id: string): Promise<string>;
|
|
42
|
+
removeUser(userId: string): Promise<string>;
|
|
43
|
+
getAllAssignments(): Promise<Assignment[]>;
|
|
44
|
+
private matchScore;
|
|
45
|
+
private calculatePriority;
|
|
46
|
+
get stats(): Promise<Stats>;
|
|
47
|
+
get usersWithoutAssignment(): Promise<string[]>;
|
|
48
|
+
setAssignmentPriority(id: string, priority: number): Promise<{
|
|
49
|
+
id: string;
|
|
50
|
+
priority: number;
|
|
51
|
+
}>;
|
|
52
|
+
setAssignmentPriorityByTags(tags: string[], priority: number): Promise<{
|
|
53
|
+
id: string;
|
|
54
|
+
priority: number;
|
|
55
|
+
}[]>;
|
|
56
|
+
private getUserRelatedAssignments;
|
|
57
|
+
matchUsersAssignments(userId?: string): Promise<void>;
|
|
58
|
+
getCurrentAssignmentsForUser(userId: string): Promise<string[]>;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=matcher.class.d.ts.map
|
|
@@ -0,0 +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;IACxC,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,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,KAAK,GAAG;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sBAAsB,CAAC,EAAE,MAAM,EAAE,CAAC;IAClC,oBAAoB,CAAC,EAAE,MAAM,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAClB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,sBAAsB,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAClF,gBAAgB,CAAC,EAAE,CACf,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,YAAY,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAClC,CAAC;AAEF,MAAM,CAAC,OAAO,OAAO,iBAAiB;IAUvB,WAAW,EAAE,eAAe;IATvC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,qBAAqB,EAAE,OAAO,CAAC;gBAGpB,WAAW,EAAE,eAAe,EACnC,OAAO,CAAC,EAAE,OAAO;YAcP,SAAS;IAQjB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAalC,aAAa,CAAC,UAAU,EAAE,UAAU;IA0CpC,gBAAgB,CAAC,EAAE,EAAE,MAAM;IAyB3B,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU3C,iBAAiB,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YAKlC,UAAU;YAkCV,iBAAiB;IAK/B,IAAI,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,CAY1B;IAED,IAAI,sBAAsB,sBAWzB;IAEK,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;IAyBlD,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM;;;;YA6BpD,yBAAyB;IAoHjC,qBAAqB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmDrD,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAKxE"}
|