taskpace 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of taskpace might be problematic. Click here for more details.
- package/.babelrc.es5 +5 -0
- package/.babelrc.lib +9 -0
- package/.env +2 -0
- package/.travis.yml +25 -0
- package/LICENSE +20 -0
- package/README.md +474 -2
- package/bower.json +30 -0
- package/es5.js +5064 -0
- package/lib/Batcher.js +1 -0
- package/lib/DLList.js +1 -0
- package/lib/Events.js +1 -0
- package/lib/Group.js +1 -0
- package/lib/IORedisConnection.js +1 -0
- package/lib/Job.js +1 -0
- package/lib/LocalDatastore.js +1 -0
- package/lib/Queues.js +1 -0
- package/lib/RedisConnection.js +1 -0
- package/lib/RedisDatastore.js +1 -0
- package/lib/Scripts.js +1 -0
- package/lib/States.js +1 -0
- package/lib/Sync.js +1 -0
- package/lib/Taskpace.js +1 -0
- package/lib/TaskpaceError.js +1 -0
- package/lib/common.js +1 -0
- package/lib/es5.js +1 -0
- package/lib/index.js +1 -0
- package/lib/limit.js +1 -0
- package/lib/lua.json +24 -0
- package/lib/parser.js +1 -0
- package/lib/redis.js +1 -0
- package/lib/validate.js +1 -0
- package/lib/version.json +1 -0
- package/light.js +1524 -0
- package/package.json +53 -4
- package/rollup.config.es5.js +34 -0
- package/rollup.config.light.js +44 -0
- package/scripts/assemble_lua.js +25 -0
- package/scripts/build.sh +81 -0
- package/scripts/test_all.sh +20 -0
- package/scripts/version.js +3 -0
- package/src/Batcher.coffee +39 -0
- package/src/DLList.coffee +38 -0
- package/src/Events.coffee +38 -0
- package/src/Group.coffee +80 -0
- package/src/IORedisConnection.coffee +84 -0
- package/src/Job.coffee +98 -0
- package/src/LocalDatastore.coffee +140 -0
- package/src/Queues.coffee +28 -0
- package/src/RedisConnection.coffee +91 -0
- package/src/RedisDatastore.coffee +158 -0
- package/src/Scripts.coffee +151 -0
- package/src/States.coffee +43 -0
- package/src/Sync.coffee +28 -0
- package/src/Taskpace.coffee +298 -0
- package/src/TaskpaceError.coffee +3 -0
- package/src/es5.coffee +3 -0
- package/src/index.coffee +1 -0
- package/src/parser.coffee +10 -0
- package/src/redis/blacklist_client.lua +8 -0
- package/src/redis/check.lua +6 -0
- package/src/redis/conditions_check.lua +3 -0
- package/src/redis/current_reservoir.lua +1 -0
- package/src/redis/done.lua +3 -0
- package/src/redis/free.lua +5 -0
- package/src/redis/get_time.lua +7 -0
- package/src/redis/group_check.lua +1 -0
- package/src/redis/heartbeat.lua +1 -0
- package/src/redis/increment_reservoir.lua +10 -0
- package/src/redis/init.lua +105 -0
- package/src/redis/process_tick.lua +214 -0
- package/src/redis/queued.lua +10 -0
- package/src/redis/refresh_expiration.lua +11 -0
- package/src/redis/refs.lua +13 -0
- package/src/redis/register.lua +51 -0
- package/src/redis/register_client.lua +12 -0
- package/src/redis/running.lua +1 -0
- package/src/redis/submit.lua +74 -0
- package/src/redis/update_settings.lua +14 -0
- package/src/redis/validate_client.lua +5 -0
- package/src/redis/validate_keys.lua +3 -0
- package/taskpace.d.ts +629 -0
- package/taskpace.d.ts.ejs +588 -0
- package/test/DLList.js +148 -0
- package/test/batcher.js +209 -0
- package/test/cluster.js +1549 -0
- package/test/context.js +142 -0
- package/test/general.js +867 -0
- package/test/group.js +255 -0
- package/test/ioredis.js +135 -0
- package/test/node_redis.js +100 -0
- package/test/priority.js +184 -0
- package/test/promises.js +202 -0
- package/test/retries.js +237 -0
- package/test/spawn/increaseKeepAlive.js +17 -0
- package/test/spawn/refreshKeepAlive.js +17 -0
- package/test/states.js +103 -0
- package/test/stop.js +208 -0
- package/test/taskpace.js +7 -0
- package/test.ts +335 -0
package/.babelrc.es5
ADDED
package/.babelrc.lib
ADDED
package/.env
ADDED
package/.travis.yml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
language: node_js
|
|
2
|
+
node_js:
|
|
3
|
+
- 8
|
|
4
|
+
branches:
|
|
5
|
+
only:
|
|
6
|
+
- master
|
|
7
|
+
- next
|
|
8
|
+
services:
|
|
9
|
+
- redis-server
|
|
10
|
+
env:
|
|
11
|
+
global:
|
|
12
|
+
- "REDIS_HOST=127.0.0.1"
|
|
13
|
+
- "REDIS_PORT=6379"
|
|
14
|
+
cache:
|
|
15
|
+
directories:
|
|
16
|
+
- $HOME/.npm
|
|
17
|
+
install:
|
|
18
|
+
- npm i
|
|
19
|
+
sudo: required
|
|
20
|
+
after_success: npx codecov --file=./coverage/lcov.info
|
|
21
|
+
script: npm run test-all
|
|
22
|
+
|
|
23
|
+
before_install:
|
|
24
|
+
- npm i -g npm@5.10
|
|
25
|
+
- npm --version
|
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tom Hundley
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
the Software without restriction, including without limitation the rights to
|
|
8
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,475 @@
|
|
|
1
|
-
#
|
|
1
|
+
# taskpace
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Taskpace is a task scheduler and rate limiter for Node.js and the browser. It queues work and runs it under limits you set: how many jobs may run at once, how long to wait between starts, and how large the waiting line may grow.
|
|
4
|
+
|
|
5
|
+
It has no runtime dependencies. The same limiter can also share its counters across processes through Redis.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install taskpace
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
const Taskpace = require("taskpace");
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import Taskpace from "taskpace";
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Browsers and Node versions older than 6 should load the ES5 build:
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
const Taskpace = require("taskpace/es5");
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Create a limiter
|
|
28
|
+
|
|
29
|
+
```js
|
|
30
|
+
const limiter = new Taskpace({
|
|
31
|
+
maxConcurrent: 2,
|
|
32
|
+
minTime: 200
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`minTime` is the pause after one job starts before another may start. `maxConcurrent` is how many jobs may be in progress together. Either option can be used alone. Together they keep a steady pace instead of a burst followed by a long gap.
|
|
37
|
+
|
|
38
|
+
Pass `null` for `maxConcurrent` when you do not want a concurrency cap.
|
|
39
|
+
|
|
40
|
+
### Run a promise
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
const page = await limiter.schedule(() => fetch(url).then((res) => res.text()));
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`schedule` accepts the function and any arguments that function should receive:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
const body = await limiter.schedule(fetchText, url, { timeout: 5000 });
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Wrap an existing function
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
const fetchText = limiter.wrap(loadPage);
|
|
56
|
+
|
|
57
|
+
const body = await fetchText("/reports");
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The wrapped function has the same arguments as the original. It returns a promise that settles when the job finishes, or when Taskpace itself rejects the job.
|
|
61
|
+
|
|
62
|
+
### Callbacks
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
limiter.submit(readFile, path, (err, data) => {
|
|
66
|
+
if (err) return console.error(err);
|
|
67
|
+
console.log(data);
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
If you do not need the callback, pass `null`. The function you submit still has to call its own callback so the limiter knows the job is finished. A job that never calls back occupies a slot until you set an `expiration`.
|
|
72
|
+
|
|
73
|
+
## Limiter options
|
|
74
|
+
|
|
75
|
+
| Option | Default | What it does |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| `maxConcurrent` | `null` | Maximum number of jobs in progress. `null` means no cap. |
|
|
78
|
+
| `minTime` | `0` | Milliseconds to wait after a job starts before the next one can start. |
|
|
79
|
+
| `highWater` | `null` | Maximum queue length. Past this point, the chosen `strategy` drops work. Ignored when `null`. |
|
|
80
|
+
| `strategy` | `Taskpace.strategy.LEAK` | What to do when the queue would pass `highWater`. |
|
|
81
|
+
| `penalty` | `15 * minTime`, or `5000` when `minTime` is `0` | How long `BLOCK` stays closed after the queue overflows. |
|
|
82
|
+
| `reservoir` | `null` | How many jobs may start before the limiter pauses. `0` stops new starts until the value rises again. Jobs can still be queued. |
|
|
83
|
+
| `reservoirRefreshInterval` | `null` | How often, in milliseconds, to set `reservoir` back to `reservoirRefreshAmount`. |
|
|
84
|
+
| `reservoirRefreshAmount` | `null` | Value assigned to `reservoir` on each refresh. |
|
|
85
|
+
| `reservoirIncreaseInterval` | `null` | How often, in milliseconds, to add `reservoirIncreaseAmount` to `reservoir`. |
|
|
86
|
+
| `reservoirIncreaseAmount` | `null` | Amount added on each increase. |
|
|
87
|
+
| `reservoirIncreaseMaximum` | `null` | Ceiling for `reservoir` while increases are enabled. |
|
|
88
|
+
| `trackDoneStatus` | `false` | Keep finished jobs visible to `counts()` and `jobStatus()`. Uses more memory. |
|
|
89
|
+
| `Promise` | the built-in `Promise` | Promise implementation Taskpace should use. |
|
|
90
|
+
|
|
91
|
+
Refresh and increase intervals must be a multiple of 250. When the limiter stores state in Redis, use a multiple of 5000.
|
|
92
|
+
|
|
93
|
+
The interval clock starts when the limiter is created. A refresh can land immediately after you enqueue a burst, so the limiter may start two allotments back to back. Keep `minTime` or `maxConcurrent` set if that burst would be a problem.
|
|
94
|
+
|
|
95
|
+
A reservoir interval holds a timer, so the limiter will not be garbage-collected until you call `disconnect()`. The process can still exit without that call.
|
|
96
|
+
|
|
97
|
+
## Allowances that refill
|
|
98
|
+
|
|
99
|
+
Use a reservoir when a quota resets on a clock, rather than when you only need a smooth gap between calls.
|
|
100
|
+
|
|
101
|
+
This allows 30 starts, then restores that allowance every minute:
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
const limiter = new Taskpace({
|
|
105
|
+
reservoir: 30,
|
|
106
|
+
reservoirRefreshAmount: 30,
|
|
107
|
+
reservoirRefreshInterval: 60 * 1000,
|
|
108
|
+
maxConcurrent: 3,
|
|
109
|
+
minTime: 100
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
This starts with 20 starts and adds 1 every second, never going above 20:
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
const limiter = new Taskpace({
|
|
117
|
+
reservoir: 20,
|
|
118
|
+
reservoirIncreaseAmount: 1,
|
|
119
|
+
reservoirIncreaseInterval: 1000,
|
|
120
|
+
reservoirIncreaseMaximum: 20,
|
|
121
|
+
maxConcurrent: 4,
|
|
122
|
+
minTime: 50
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
When a refresh fires, every newly allowed job becomes eligible at once. `minTime` and `maxConcurrent` are what spread those starts out.
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
const left = await limiter.currentReservoir();
|
|
130
|
+
const updated = await limiter.incrementReservoir(5);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Options on a single job
|
|
134
|
+
|
|
135
|
+
Pass an options object as the first argument to `schedule` or `submit`. On a wrapped function, call `withOptions`.
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
await limiter.schedule({ priority: 1, id: "invoice-9" }, sendInvoice, invoice);
|
|
139
|
+
|
|
140
|
+
limiter.submit({ weight: 2 }, writeRows, rows, done);
|
|
141
|
+
|
|
142
|
+
const send = limiter.wrap(postJson);
|
|
143
|
+
await send.withOptions({ expiration: 8000 }, "/charges", payload);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
| Option | Default | What it does |
|
|
147
|
+
| --- | --- | --- |
|
|
148
|
+
| `priority` | `5` | Integer from `0` (runs sooner) to `9` (runs later). Priorities only order work that is actually waiting, so set `maxConcurrent`. |
|
|
149
|
+
| `weight` | `1` | How much this job counts against `maxConcurrent` and `reservoir`. Integer `0` or greater. |
|
|
150
|
+
| `expiration` | `null` | Milliseconds the job may run. After that, it fails with a `TaskpaceError`. |
|
|
151
|
+
| `id` | `"<no-id>"` | Label used in debug output and by `jobStatus()`. |
|
|
152
|
+
|
|
153
|
+
## When the queue is too long
|
|
154
|
+
|
|
155
|
+
If adding a job would make the queue longer than `highWater`, Taskpace applies `strategy`. Nothing in this section runs while `highWater` is `null`.
|
|
156
|
+
|
|
157
|
+
| Strategy | Behavior |
|
|
158
|
+
| --- | --- |
|
|
159
|
+
| `Taskpace.strategy.LEAK` | Drop the oldest waiting job that has the lowest priority. If every waiting job outranks the new one, the new job is the one dropped. |
|
|
160
|
+
| `Taskpace.strategy.OVERFLOW_PRIORITY` | Drop a waiting job only when it is less important than the new one. Otherwise reject the new job. |
|
|
161
|
+
| `Taskpace.strategy.OVERFLOW` | Reject the new job. Priority is ignored. |
|
|
162
|
+
| `Taskpace.strategy.BLOCK` | Drop the queue and refuse new jobs until `penalty` milliseconds pass with no new arrival. Priority is ignored. One limiter entering this state blocks every limiter that shares its Redis datastore. |
|
|
163
|
+
|
|
164
|
+
Listen for drops:
|
|
165
|
+
|
|
166
|
+
```js
|
|
167
|
+
limiter.on("dropped", (job) => {
|
|
168
|
+
console.log("dropped", job.options.id);
|
|
169
|
+
});
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## What the function you pass must do
|
|
173
|
+
|
|
174
|
+
`schedule` and `wrap` consider the job finished when the returned promise settles. Return only after the work is done:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
await limiter.schedule(() => {
|
|
178
|
+
return Promise.all(items.map((item) => save(item)));
|
|
179
|
+
});
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
If you pass an object method, keep its `this` binding:
|
|
183
|
+
|
|
184
|
+
```js
|
|
185
|
+
limiter.schedule(() => client.query(sql));
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Listen for `"error"`. Those events are how listener exceptions and Redis failures surface. They are not delivered through the job promise.
|
|
189
|
+
|
|
190
|
+
`submit` always needs a callback argument, even if that argument is `null`. The task itself must still invoke its callback.
|
|
191
|
+
|
|
192
|
+
## Job stages
|
|
193
|
+
|
|
194
|
+
1. **Received.** The job has entered the limiter and has not yet been accepted into the queue.
|
|
195
|
+
2. **Queued.** It is accepted, and its start time still depends on earlier jobs.
|
|
196
|
+
3. **Running.** It has left the queue and is waiting out the computed `minTime` delay.
|
|
197
|
+
4. **Executing.** Its function is running.
|
|
198
|
+
5. **Done.** It has finished.
|
|
199
|
+
|
|
200
|
+
Finished jobs are not retained unless the limiter was created with `trackDoneStatus: true`.
|
|
201
|
+
|
|
202
|
+
```js
|
|
203
|
+
limiter.counts();
|
|
204
|
+
// { RECEIVED, QUEUED, RUNNING, EXECUTING, DONE }
|
|
205
|
+
|
|
206
|
+
limiter.jobStatus("invoice-9"); // "QUEUED", or null if that id is unknown
|
|
207
|
+
limiter.jobs("EXECUTING"); // ["invoice-9"]
|
|
208
|
+
limiter.jobs(); // every known id
|
|
209
|
+
|
|
210
|
+
limiter.queued(); // waiting jobs in this limiter
|
|
211
|
+
limiter.queued(1); // waiting jobs at priority 1
|
|
212
|
+
limiter.empty(); // true when nothing is RECEIVED or QUEUED here
|
|
213
|
+
|
|
214
|
+
await limiter.clusterQueued(); // waiting jobs across limiters that share state
|
|
215
|
+
await limiter.running(); // total weight of RUNNING and EXECUTING work in the shared state
|
|
216
|
+
await limiter.done(); // total weight of DONE work in the shared state
|
|
217
|
+
await limiter.check(); // true if a new job would start immediately
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`running()` and `done()` report weight, not a plain job count. `done()` does not require `trackDoneStatus`.
|
|
221
|
+
|
|
222
|
+
## Events
|
|
223
|
+
|
|
224
|
+
```js
|
|
225
|
+
limiter.on("error", (err) => {});
|
|
226
|
+
limiter.on("failed", (err, info) => {});
|
|
227
|
+
limiter.on("retry", (message, info) => {});
|
|
228
|
+
limiter.on("empty", () => {});
|
|
229
|
+
limiter.on("idle", () => {});
|
|
230
|
+
limiter.on("dropped", (dropped) => {});
|
|
231
|
+
limiter.on("depleted", (isEmpty) => {});
|
|
232
|
+
limiter.on("debug", (message, data) => {});
|
|
233
|
+
limiter.on("received", (info) => {});
|
|
234
|
+
limiter.on("queued", (info) => {});
|
|
235
|
+
limiter.on("scheduled", (info) => {});
|
|
236
|
+
limiter.on("executing", (info) => {});
|
|
237
|
+
limiter.on("done", (info) => {});
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`"empty"` fires when this limiter has nothing received or queued. `"idle"` fires when that is true and `running()` is `0`. `"depleted"` fires when `reservoir` hits `0`; the argument is the current result of `empty()`. `"dropped"` fires when a strategy discards a job.
|
|
241
|
+
|
|
242
|
+
Stage events (`received`, `queued`, `scheduled`, `executing`, `done`) describe jobs on this limiter only.
|
|
243
|
+
|
|
244
|
+
`once` listens a single time. `removeAllListeners` clears listeners, optionally for one event name.
|
|
245
|
+
|
|
246
|
+
## Retry a failed job
|
|
247
|
+
|
|
248
|
+
Return a delay in milliseconds from the `"failed"` handler. Return `0` to retry immediately. Return nothing to let the failure stand.
|
|
249
|
+
|
|
250
|
+
```js
|
|
251
|
+
limiter.on("failed", (err, info) => {
|
|
252
|
+
if (info.retryCount < 2) return 100;
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
limiter.on("retry", (message, info) => {
|
|
256
|
+
console.log("retrying", info.options.id);
|
|
257
|
+
});
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
A job that is waiting to retry stays in `EXECUTING`. It still counts toward `maxConcurrent`, and the delay does not consult `minTime`.
|
|
261
|
+
|
|
262
|
+
## Update, stop, and chain
|
|
263
|
+
|
|
264
|
+
```js
|
|
265
|
+
await limiter.updateSettings({ minTime: 400, maxConcurrent: 1 });
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
The object matches the constructor options. Jobs that are already scheduled keep the previous timing.
|
|
269
|
+
|
|
270
|
+
```js
|
|
271
|
+
await limiter.stop({
|
|
272
|
+
dropWaitingJobs: true,
|
|
273
|
+
dropErrorMessage: "This limiter has been stopped.",
|
|
274
|
+
enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs."
|
|
275
|
+
});
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
`stop` rejects further arrivals. With `dropWaitingJobs: true` (the default), jobs that are received, queued, or running are failed with `dropErrorMessage`. Jobs already executing are allowed to finish. Set `dropWaitingJobs` to `false` to wait for the rest of the queue as well.
|
|
279
|
+
|
|
280
|
+
`chain` sends a job to another limiter once this one is ready to run it. Both limits apply:
|
|
281
|
+
|
|
282
|
+
```js
|
|
283
|
+
const reports = new Taskpace({ minTime: 50 });
|
|
284
|
+
const uploads = new Taskpace({ maxConcurrent: 1 });
|
|
285
|
+
const globalCap = new Taskpace({ maxConcurrent: 4 });
|
|
286
|
+
|
|
287
|
+
reports.chain(globalCap);
|
|
288
|
+
uploads.chain(globalCap);
|
|
289
|
+
|
|
290
|
+
reports.chain(null); // remove the link
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## One limiter per key
|
|
294
|
+
|
|
295
|
+
`Taskpace.Group` builds a limiter the first time you ask for a key, and reuses it after that.
|
|
296
|
+
|
|
297
|
+
```js
|
|
298
|
+
const group = new Taskpace.Group({ maxConcurrent: 1, minTime: 100 });
|
|
299
|
+
|
|
300
|
+
group.on("created", (limiter, key) => {
|
|
301
|
+
limiter.on("error", (err) => console.error(key, err));
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
await group.key(userId).schedule(() => charge(userId));
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
The handler for `"created"` runs before `key` returns the new limiter. Options passed to the group are copied onto each limiter it creates.
|
|
308
|
+
|
|
309
|
+
Limiters that stay idle are removed after 5 minutes. Pass `timeout` in milliseconds to change that.
|
|
310
|
+
|
|
311
|
+
```js
|
|
312
|
+
group.updateSettings({ minTime: 250 }); // applies to limiters created afterward
|
|
313
|
+
group.keys();
|
|
314
|
+
group.limiters(); // [{ key, limiter }, ...]
|
|
315
|
+
await group.deleteKey(userId);
|
|
316
|
+
await group.clusterKeys(); // keys for this group id across Redis
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
In Redis mode, a generated limiter id looks like `${group.id}-${key}`.
|
|
320
|
+
|
|
321
|
+
## Group calls into batches
|
|
322
|
+
|
|
323
|
+
`Taskpace.Batcher` collects values and flushes them together. It does not apply a rate limit.
|
|
324
|
+
|
|
325
|
+
```js
|
|
326
|
+
const batcher = new Taskpace.Batcher({
|
|
327
|
+
maxTime: 200,
|
|
328
|
+
maxSize: 25
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
batcher.on("batch", async (rows) => {
|
|
332
|
+
await insertMany(rows);
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
await batcher.add(row);
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
| Option | Default | What it does |
|
|
339
|
+
| --- | --- | --- |
|
|
340
|
+
| `maxTime` | `null` | Longest a value may wait before a flush. |
|
|
341
|
+
| `maxSize` | `null` | Largest batch. A flush also happens when this size is reached. |
|
|
342
|
+
|
|
343
|
+
`add` resolves when that value has been handed to a `"batch"` listener.
|
|
344
|
+
|
|
345
|
+
## Share state with Redis
|
|
346
|
+
|
|
347
|
+
Set `datastore` to `"redis"` or `"ioredis"` so every limiter with the same `id` shares counters. Install the client yourself (`redis` or `ioredis`). It is not bundled.
|
|
348
|
+
|
|
349
|
+
```js
|
|
350
|
+
const limiter = new Taskpace({
|
|
351
|
+
id: "checkout",
|
|
352
|
+
maxConcurrent: 5,
|
|
353
|
+
minTime: 100,
|
|
354
|
+
datastore: "ioredis",
|
|
355
|
+
clearDatastore: false,
|
|
356
|
+
clientOptions: {
|
|
357
|
+
host: "127.0.0.1",
|
|
358
|
+
port: 6379
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
| Option | Default | What it does |
|
|
364
|
+
| --- | --- | --- |
|
|
365
|
+
| `datastore` | `"local"` | `"local"`, `"redis"`, or `"ioredis"`. |
|
|
366
|
+
| `clearDatastore` | `false` | On startup, delete stored state for this `id`, including saved settings. |
|
|
367
|
+
| `clientOptions` | `{}` | Passed through to the Redis client. |
|
|
368
|
+
| `clusterNodes` | `null` | ioredis only. When set, the client is `new Redis.Cluster(clusterNodes, clientOptions)`. |
|
|
369
|
+
| `timeout` | `null` | Remove this limiter's Redis keys after this many milliseconds without activity. Groups default this to `300000`. |
|
|
370
|
+
| `Redis` | `null` | The `redis` or `ioredis` module, if Taskpace should not load it itself. |
|
|
371
|
+
| `connection` | `null` | An existing `Taskpace.RedisConnection` or `Taskpace.IORedisConnection`. When set, `datastore`, `clientOptions`, and `clusterNodes` are ignored. |
|
|
372
|
+
|
|
373
|
+
The first limiter to connect stores its constructor options. Later limiters with that `id` use the stored options. Call `updateSettings` to change them for everyone. `clearDatastore: true` wipes that record first.
|
|
374
|
+
|
|
375
|
+
Give every limiter and group an `id`. It is part of the Redis key names. Also set `expiration` on jobs. If a process dies mid-job, the shared running count is released when the expiration elapses.
|
|
376
|
+
|
|
377
|
+
Queues stay in the process that called `schedule` or `submit`. They are not written to Redis, and they disappear if that process exits. Because of that:
|
|
378
|
+
|
|
379
|
+
- Priority and arrival order are guaranteed only among jobs on the same limiter.
|
|
380
|
+
- `highWater` is local, except that `BLOCK` freezes the whole shared limiter.
|
|
381
|
+
- `"empty"` refers to the local queue. `"idle"` also requires that nothing is running anywhere in the shared state.
|
|
382
|
+
|
|
383
|
+
`minTime` does not subtract network delay. Taskpace makes one Redis round trip per stage change. Keep the server close, and keep clocks aligned across hosts.
|
|
384
|
+
|
|
385
|
+
Redis Cluster needs `datastore: "ioredis"` and `clusterNodes`. Redis Sentinel also needs `ioredis`.
|
|
386
|
+
|
|
387
|
+
If a bundler cannot see the optional client import, pass the module in:
|
|
388
|
+
|
|
389
|
+
```js
|
|
390
|
+
import Redis from "ioredis";
|
|
391
|
+
|
|
392
|
+
const limiter = new Taskpace({
|
|
393
|
+
id: "checkout",
|
|
394
|
+
datastore: "ioredis",
|
|
395
|
+
clientOptions: { host: "127.0.0.1", port: 6379 },
|
|
396
|
+
Redis
|
|
397
|
+
});
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
### Connection helpers
|
|
401
|
+
|
|
402
|
+
You can call these with `datastore: "local"` as well, so calling code does not have to branch.
|
|
403
|
+
|
|
404
|
+
```js
|
|
405
|
+
limiter.on("error", (err) => console.error(err));
|
|
406
|
+
|
|
407
|
+
await limiter.ready();
|
|
408
|
+
|
|
409
|
+
limiter.on("message", (msg) => console.log(msg));
|
|
410
|
+
await limiter.publish("reload");
|
|
411
|
+
|
|
412
|
+
const { client, subscriber } = limiter.clients();
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
`ready` resolves after Redis is connected. Calls made earlier are held until then. Connection failures arrive on `"error"`.
|
|
416
|
+
|
|
417
|
+
`publish` sends a string to every limiter on that shared state. Stringify objects yourself.
|
|
418
|
+
|
|
419
|
+
### One connection for many limiters
|
|
420
|
+
|
|
421
|
+
Taskpace opens two clients: one for commands and one for subscriptions. Build a connection once and pass it in to share them.
|
|
422
|
+
|
|
423
|
+
```js
|
|
424
|
+
const connection = new Taskpace.IORedisConnection({
|
|
425
|
+
clientOptions: { host: "127.0.0.1", port: 6379 }
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
connection.on("error", (err) => console.error(err));
|
|
429
|
+
|
|
430
|
+
const limiter = new Taskpace({ id: "checkout", connection });
|
|
431
|
+
const group = new Taskpace.Group({ connection });
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
`Taskpace.RedisConnection` is the matching helper for the `redis` package. You can also hand over a client you already opened. Taskpace still creates the subscriber client.
|
|
435
|
+
|
|
436
|
+
```js
|
|
437
|
+
const connection = new Taskpace.RedisConnection({ client });
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
`disconnect()` closes clients that Taskpace opened. If you created the connection yourself, call `connection.disconnect()` instead.
|
|
441
|
+
|
|
442
|
+
Taskpace stores its Redis data under its own keys and channels, separate from other application data. It loads a few Lua scripts with `SCRIPT LOAD`. `SCRIPT FLUSH` removes those scripts and breaks connected limiters until another one loads them again.
|
|
443
|
+
|
|
444
|
+
## Failures from Taskpace
|
|
445
|
+
|
|
446
|
+
When Taskpace rejects a job, the error is a `Taskpace.TaskpaceError`. That includes dropped jobs, expirations, and jobs refused after `stop()`.
|
|
447
|
+
|
|
448
|
+
```js
|
|
449
|
+
try {
|
|
450
|
+
await limiter.schedule(() => callApi());
|
|
451
|
+
} catch (err) {
|
|
452
|
+
if (err instanceof Taskpace.TaskpaceError) {
|
|
453
|
+
console.error(err.message);
|
|
454
|
+
} else {
|
|
455
|
+
throw err;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
`"debug"` prints the decisions the limiter is making. Job `id` values make that log easier to follow.
|
|
461
|
+
|
|
462
|
+
## Development
|
|
463
|
+
|
|
464
|
+
Source lives in `src/`. Build it, then run the tests:
|
|
465
|
+
|
|
466
|
+
```bash
|
|
467
|
+
./scripts/build.sh
|
|
468
|
+
npm test
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
`./scripts/build.sh dev` is a faster local compile. Run a full build before you rely on the ES5 bundle or the type declarations. Clustering tests need a local Redis server. Host and port overrides go in `.env`, and `npm run test-all` runs that suite.
|
|
472
|
+
|
|
473
|
+
## License
|
|
474
|
+
|
|
475
|
+
MIT. See [LICENSE](LICENSE).
|
package/bower.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "taskpace",
|
|
3
|
+
"main": "taskpace.js",
|
|
4
|
+
"version": "2.19.5",
|
|
5
|
+
"homepage": "https://github.com/PaceJS/taskpace",
|
|
6
|
+
"authors": [
|
|
7
|
+
"SGrondin <github@simongrondin.name>"
|
|
8
|
+
],
|
|
9
|
+
"description": "Distributed task scheduler and rate limiter",
|
|
10
|
+
"moduleType": [
|
|
11
|
+
"globals",
|
|
12
|
+
"node"
|
|
13
|
+
],
|
|
14
|
+
"keywords": [
|
|
15
|
+
"async",
|
|
16
|
+
"rate",
|
|
17
|
+
"limiter",
|
|
18
|
+
"limiting",
|
|
19
|
+
"throttle",
|
|
20
|
+
"throttling",
|
|
21
|
+
"load",
|
|
22
|
+
"ddos"
|
|
23
|
+
],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"ignore": [
|
|
26
|
+
"**/.*",
|
|
27
|
+
"node_modules",
|
|
28
|
+
"bower_components"
|
|
29
|
+
]
|
|
30
|
+
}
|