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.

Files changed (99) hide show
  1. package/.babelrc.es5 +5 -0
  2. package/.babelrc.lib +9 -0
  3. package/.env +2 -0
  4. package/.travis.yml +25 -0
  5. package/LICENSE +20 -0
  6. package/README.md +474 -2
  7. package/bower.json +30 -0
  8. package/es5.js +5064 -0
  9. package/lib/Batcher.js +1 -0
  10. package/lib/DLList.js +1 -0
  11. package/lib/Events.js +1 -0
  12. package/lib/Group.js +1 -0
  13. package/lib/IORedisConnection.js +1 -0
  14. package/lib/Job.js +1 -0
  15. package/lib/LocalDatastore.js +1 -0
  16. package/lib/Queues.js +1 -0
  17. package/lib/RedisConnection.js +1 -0
  18. package/lib/RedisDatastore.js +1 -0
  19. package/lib/Scripts.js +1 -0
  20. package/lib/States.js +1 -0
  21. package/lib/Sync.js +1 -0
  22. package/lib/Taskpace.js +1 -0
  23. package/lib/TaskpaceError.js +1 -0
  24. package/lib/common.js +1 -0
  25. package/lib/es5.js +1 -0
  26. package/lib/index.js +1 -0
  27. package/lib/limit.js +1 -0
  28. package/lib/lua.json +24 -0
  29. package/lib/parser.js +1 -0
  30. package/lib/redis.js +1 -0
  31. package/lib/validate.js +1 -0
  32. package/lib/version.json +1 -0
  33. package/light.js +1524 -0
  34. package/package.json +53 -4
  35. package/rollup.config.es5.js +34 -0
  36. package/rollup.config.light.js +44 -0
  37. package/scripts/assemble_lua.js +25 -0
  38. package/scripts/build.sh +81 -0
  39. package/scripts/test_all.sh +20 -0
  40. package/scripts/version.js +3 -0
  41. package/src/Batcher.coffee +39 -0
  42. package/src/DLList.coffee +38 -0
  43. package/src/Events.coffee +38 -0
  44. package/src/Group.coffee +80 -0
  45. package/src/IORedisConnection.coffee +84 -0
  46. package/src/Job.coffee +98 -0
  47. package/src/LocalDatastore.coffee +140 -0
  48. package/src/Queues.coffee +28 -0
  49. package/src/RedisConnection.coffee +91 -0
  50. package/src/RedisDatastore.coffee +158 -0
  51. package/src/Scripts.coffee +151 -0
  52. package/src/States.coffee +43 -0
  53. package/src/Sync.coffee +28 -0
  54. package/src/Taskpace.coffee +298 -0
  55. package/src/TaskpaceError.coffee +3 -0
  56. package/src/es5.coffee +3 -0
  57. package/src/index.coffee +1 -0
  58. package/src/parser.coffee +10 -0
  59. package/src/redis/blacklist_client.lua +8 -0
  60. package/src/redis/check.lua +6 -0
  61. package/src/redis/conditions_check.lua +3 -0
  62. package/src/redis/current_reservoir.lua +1 -0
  63. package/src/redis/done.lua +3 -0
  64. package/src/redis/free.lua +5 -0
  65. package/src/redis/get_time.lua +7 -0
  66. package/src/redis/group_check.lua +1 -0
  67. package/src/redis/heartbeat.lua +1 -0
  68. package/src/redis/increment_reservoir.lua +10 -0
  69. package/src/redis/init.lua +105 -0
  70. package/src/redis/process_tick.lua +214 -0
  71. package/src/redis/queued.lua +10 -0
  72. package/src/redis/refresh_expiration.lua +11 -0
  73. package/src/redis/refs.lua +13 -0
  74. package/src/redis/register.lua +51 -0
  75. package/src/redis/register_client.lua +12 -0
  76. package/src/redis/running.lua +1 -0
  77. package/src/redis/submit.lua +74 -0
  78. package/src/redis/update_settings.lua +14 -0
  79. package/src/redis/validate_client.lua +5 -0
  80. package/src/redis/validate_keys.lua +3 -0
  81. package/taskpace.d.ts +629 -0
  82. package/taskpace.d.ts.ejs +588 -0
  83. package/test/DLList.js +148 -0
  84. package/test/batcher.js +209 -0
  85. package/test/cluster.js +1549 -0
  86. package/test/context.js +142 -0
  87. package/test/general.js +867 -0
  88. package/test/group.js +255 -0
  89. package/test/ioredis.js +135 -0
  90. package/test/node_redis.js +100 -0
  91. package/test/priority.js +184 -0
  92. package/test/promises.js +202 -0
  93. package/test/retries.js +237 -0
  94. package/test/spawn/increaseKeepAlive.js +17 -0
  95. package/test/spawn/refreshKeepAlive.js +17 -0
  96. package/test/states.js +103 -0
  97. package/test/stop.js +208 -0
  98. package/test/taskpace.js +7 -0
  99. package/test.ts +335 -0
package/light.js ADDED
@@ -0,0 +1,1524 @@
1
+ /**
2
+ * This file contains the Taskpace library (MIT), compiled to ES2017, and without Clustering support.
3
+ * https://github.com/PaceJS/taskpace
4
+ */
5
+ (function (global, factory) {
6
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
7
+ typeof define === 'function' && define.amd ? define(factory) :
8
+ (global.Taskpace = factory());
9
+ }(this, (function () { 'use strict';
10
+
11
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
12
+
13
+ function getCjsExportFromNamespace (n) {
14
+ return n && n['default'] || n;
15
+ }
16
+
17
+ var load = function(received, defaults, onto = {}) {
18
+ var k, ref, v;
19
+ for (k in defaults) {
20
+ v = defaults[k];
21
+ onto[k] = (ref = received[k]) != null ? ref : v;
22
+ }
23
+ return onto;
24
+ };
25
+
26
+ var overwrite = function(received, defaults, onto = {}) {
27
+ var k, v;
28
+ for (k in received) {
29
+ v = received[k];
30
+ if (defaults[k] !== void 0) {
31
+ onto[k] = v;
32
+ }
33
+ }
34
+ return onto;
35
+ };
36
+
37
+ var parser = {
38
+ load: load,
39
+ overwrite: overwrite
40
+ };
41
+
42
+ var DLList;
43
+
44
+ DLList = class DLList {
45
+ constructor(incr, decr) {
46
+ this.incr = incr;
47
+ this.decr = decr;
48
+ this._first = null;
49
+ this._last = null;
50
+ this.length = 0;
51
+ }
52
+
53
+ push(value) {
54
+ var node;
55
+ this.length++;
56
+ if (typeof this.incr === "function") {
57
+ this.incr();
58
+ }
59
+ node = {
60
+ value,
61
+ prev: this._last,
62
+ next: null
63
+ };
64
+ if (this._last != null) {
65
+ this._last.next = node;
66
+ this._last = node;
67
+ } else {
68
+ this._first = this._last = node;
69
+ }
70
+ return void 0;
71
+ }
72
+
73
+ shift() {
74
+ var value;
75
+ if (this._first == null) {
76
+ return;
77
+ } else {
78
+ this.length--;
79
+ if (typeof this.decr === "function") {
80
+ this.decr();
81
+ }
82
+ }
83
+ value = this._first.value;
84
+ if ((this._first = this._first.next) != null) {
85
+ this._first.prev = null;
86
+ } else {
87
+ this._last = null;
88
+ }
89
+ return value;
90
+ }
91
+
92
+ first() {
93
+ if (this._first != null) {
94
+ return this._first.value;
95
+ }
96
+ }
97
+
98
+ getArray() {
99
+ var node, ref, results;
100
+ node = this._first;
101
+ results = [];
102
+ while (node != null) {
103
+ results.push((ref = node, node = node.next, ref.value));
104
+ }
105
+ return results;
106
+ }
107
+
108
+ forEachShift(cb) {
109
+ var node;
110
+ node = this.shift();
111
+ while (node != null) {
112
+ (cb(node), node = this.shift());
113
+ }
114
+ return void 0;
115
+ }
116
+
117
+ debug() {
118
+ var node, ref, ref1, ref2, results;
119
+ node = this._first;
120
+ results = [];
121
+ while (node != null) {
122
+ results.push((ref = node, node = node.next, {
123
+ value: ref.value,
124
+ prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
125
+ next: (ref2 = ref.next) != null ? ref2.value : void 0
126
+ }));
127
+ }
128
+ return results;
129
+ }
130
+
131
+ };
132
+
133
+ var DLList_1 = DLList;
134
+
135
+ var Events;
136
+
137
+ Events = class Events {
138
+ constructor(instance) {
139
+ this.instance = instance;
140
+ this._events = {};
141
+ if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) {
142
+ throw new Error("An Emitter already exists for this object");
143
+ }
144
+ this.instance.on = (name, cb) => {
145
+ return this._addListener(name, "many", cb);
146
+ };
147
+ this.instance.once = (name, cb) => {
148
+ return this._addListener(name, "once", cb);
149
+ };
150
+ this.instance.removeAllListeners = (name = null) => {
151
+ if (name != null) {
152
+ return delete this._events[name];
153
+ } else {
154
+ return this._events = {};
155
+ }
156
+ };
157
+ }
158
+
159
+ _addListener(name, status, cb) {
160
+ var base;
161
+ if ((base = this._events)[name] == null) {
162
+ base[name] = [];
163
+ }
164
+ this._events[name].push({cb, status});
165
+ return this.instance;
166
+ }
167
+
168
+ listenerCount(name) {
169
+ if (this._events[name] != null) {
170
+ return this._events[name].length;
171
+ } else {
172
+ return 0;
173
+ }
174
+ }
175
+
176
+ async trigger(name, ...args) {
177
+ var e, promises;
178
+ try {
179
+ if (name !== "debug") {
180
+ this.trigger("debug", `Event triggered: ${name}`, args);
181
+ }
182
+ if (this._events[name] == null) {
183
+ return;
184
+ }
185
+ this._events[name] = this._events[name].filter(function(listener) {
186
+ return listener.status !== "none";
187
+ });
188
+ promises = this._events[name].map(async(listener) => {
189
+ var e, returned;
190
+ if (listener.status === "none") {
191
+ return;
192
+ }
193
+ if (listener.status === "once") {
194
+ listener.status = "none";
195
+ }
196
+ try {
197
+ returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0;
198
+ if (typeof (returned != null ? returned.then : void 0) === "function") {
199
+ return (await returned);
200
+ } else {
201
+ return returned;
202
+ }
203
+ } catch (error) {
204
+ e = error;
205
+ {
206
+ this.trigger("error", e);
207
+ }
208
+ return null;
209
+ }
210
+ });
211
+ return ((await Promise.all(promises))).find(function(x) {
212
+ return x != null;
213
+ });
214
+ } catch (error) {
215
+ e = error;
216
+ {
217
+ this.trigger("error", e);
218
+ }
219
+ return null;
220
+ }
221
+ }
222
+
223
+ };
224
+
225
+ var Events_1 = Events;
226
+
227
+ var DLList$1, Events$1, Queues;
228
+
229
+ DLList$1 = DLList_1;
230
+
231
+ Events$1 = Events_1;
232
+
233
+ Queues = class Queues {
234
+ constructor(num_priorities) {
235
+ var i;
236
+ this.Events = new Events$1(this);
237
+ this._length = 0;
238
+ this._lists = (function() {
239
+ var j, ref, results;
240
+ results = [];
241
+ for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {
242
+ results.push(new DLList$1((() => {
243
+ return this.incr();
244
+ }), (() => {
245
+ return this.decr();
246
+ })));
247
+ }
248
+ return results;
249
+ }).call(this);
250
+ }
251
+
252
+ incr() {
253
+ if (this._length++ === 0) {
254
+ return this.Events.trigger("leftzero");
255
+ }
256
+ }
257
+
258
+ decr() {
259
+ if (--this._length === 0) {
260
+ return this.Events.trigger("zero");
261
+ }
262
+ }
263
+
264
+ push(job) {
265
+ return this._lists[job.options.priority].push(job);
266
+ }
267
+
268
+ queued(priority) {
269
+ if (priority != null) {
270
+ return this._lists[priority].length;
271
+ } else {
272
+ return this._length;
273
+ }
274
+ }
275
+
276
+ shiftAll(fn) {
277
+ return this._lists.forEach(function(list) {
278
+ return list.forEachShift(fn);
279
+ });
280
+ }
281
+
282
+ getFirst(arr = this._lists) {
283
+ var j, len, list;
284
+ for (j = 0, len = arr.length; j < len; j++) {
285
+ list = arr[j];
286
+ if (list.length > 0) {
287
+ return list;
288
+ }
289
+ }
290
+ return [];
291
+ }
292
+
293
+ shiftLastFrom(priority) {
294
+ return this.getFirst(this._lists.slice(priority).reverse()).shift();
295
+ }
296
+
297
+ };
298
+
299
+ var Queues_1 = Queues;
300
+
301
+ var TaskpaceError;
302
+
303
+ TaskpaceError = class TaskpaceError extends Error {};
304
+
305
+ var TaskpaceError_1 = TaskpaceError;
306
+
307
+ var TaskpaceError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1;
308
+
309
+ NUM_PRIORITIES = 10;
310
+
311
+ DEFAULT_PRIORITY = 5;
312
+
313
+ parser$1 = parser;
314
+
315
+ TaskpaceError$1 = TaskpaceError_1;
316
+
317
+ Job = class Job {
318
+ constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {
319
+ this.task = task;
320
+ this.args = args;
321
+ this.rejectOnDrop = rejectOnDrop;
322
+ this.Events = Events;
323
+ this._states = _states;
324
+ this.Promise = Promise;
325
+ this.options = parser$1.load(options, jobDefaults);
326
+ this.options.priority = this._sanitizePriority(this.options.priority);
327
+ if (this.options.id === jobDefaults.id) {
328
+ this.options.id = `${this.options.id}-${this._randomIndex()}`;
329
+ }
330
+ this.promise = new this.Promise((_resolve, _reject) => {
331
+ this._resolve = _resolve;
332
+ this._reject = _reject;
333
+ });
334
+ this.retryCount = 0;
335
+ }
336
+
337
+ _sanitizePriority(priority) {
338
+ var sProperty;
339
+ sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
340
+ if (sProperty < 0) {
341
+ return 0;
342
+ } else if (sProperty > NUM_PRIORITIES - 1) {
343
+ return NUM_PRIORITIES - 1;
344
+ } else {
345
+ return sProperty;
346
+ }
347
+ }
348
+
349
+ _randomIndex() {
350
+ return Math.random().toString(36).slice(2);
351
+ }
352
+
353
+ doDrop({error, message = "This job has been dropped by Taskpace"} = {}) {
354
+ if (this._states.remove(this.options.id)) {
355
+ if (this.rejectOnDrop) {
356
+ this._reject(error != null ? error : new TaskpaceError$1(message));
357
+ }
358
+ this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise});
359
+ return true;
360
+ } else {
361
+ return false;
362
+ }
363
+ }
364
+
365
+ _assertStatus(expected) {
366
+ var status;
367
+ status = this._states.jobStatus(this.options.id);
368
+ if (!(status === expected || (expected === "DONE" && status === null))) {
369
+ throw new TaskpaceError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/PaceJS/taskpace/issues`);
370
+ }
371
+ }
372
+
373
+ doReceive() {
374
+ this._states.start(this.options.id);
375
+ return this.Events.trigger("received", {args: this.args, options: this.options});
376
+ }
377
+
378
+ doQueue(reachedHWM, blocked) {
379
+ this._assertStatus("RECEIVED");
380
+ this._states.next(this.options.id);
381
+ return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked});
382
+ }
383
+
384
+ doRun() {
385
+ if (this.retryCount === 0) {
386
+ this._assertStatus("QUEUED");
387
+ this._states.next(this.options.id);
388
+ } else {
389
+ this._assertStatus("EXECUTING");
390
+ }
391
+ return this.Events.trigger("scheduled", {args: this.args, options: this.options});
392
+ }
393
+
394
+ async doExecute(chained, clearGlobalState, run, free) {
395
+ var error, eventInfo, passed;
396
+ if (this.retryCount === 0) {
397
+ this._assertStatus("RUNNING");
398
+ this._states.next(this.options.id);
399
+ } else {
400
+ this._assertStatus("EXECUTING");
401
+ }
402
+ eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
403
+ this.Events.trigger("executing", eventInfo);
404
+ try {
405
+ passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)));
406
+ if (clearGlobalState()) {
407
+ this.doDone(eventInfo);
408
+ await free(this.options, eventInfo);
409
+ this._assertStatus("DONE");
410
+ return this._resolve(passed);
411
+ }
412
+ } catch (error1) {
413
+ error = error1;
414
+ return this._onFailure(error, eventInfo, clearGlobalState, run, free);
415
+ }
416
+ }
417
+
418
+ doExpire(clearGlobalState, run, free) {
419
+ var error, eventInfo;
420
+ if (this._states.jobStatus(this.options.id === "RUNNING")) {
421
+ this._states.next(this.options.id);
422
+ }
423
+ this._assertStatus("EXECUTING");
424
+ eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
425
+ error = new TaskpaceError$1(`This job timed out after ${this.options.expiration} ms.`);
426
+ return this._onFailure(error, eventInfo, clearGlobalState, run, free);
427
+ }
428
+
429
+ async _onFailure(error, eventInfo, clearGlobalState, run, free) {
430
+ var retry, retryAfter;
431
+ if (clearGlobalState()) {
432
+ retry = (await this.Events.trigger("failed", error, eventInfo));
433
+ if (retry != null) {
434
+ retryAfter = ~~retry;
435
+ this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo);
436
+ this.retryCount++;
437
+ return run(retryAfter);
438
+ } else {
439
+ this.doDone(eventInfo);
440
+ await free(this.options, eventInfo);
441
+ this._assertStatus("DONE");
442
+ return this._reject(error);
443
+ }
444
+ }
445
+ }
446
+
447
+ doDone(eventInfo) {
448
+ this._assertStatus("EXECUTING");
449
+ this._states.next(this.options.id);
450
+ return this.Events.trigger("done", eventInfo);
451
+ }
452
+
453
+ };
454
+
455
+ var Job_1 = Job;
456
+
457
+ var TaskpaceError$2, LocalDatastore, parser$2;
458
+
459
+ parser$2 = parser;
460
+
461
+ TaskpaceError$2 = TaskpaceError_1;
462
+
463
+ LocalDatastore = class LocalDatastore {
464
+ constructor(instance, storeOptions, storeInstanceOptions) {
465
+ this.instance = instance;
466
+ this.storeOptions = storeOptions;
467
+ this.clientId = this.instance._randomIndex();
468
+ parser$2.load(storeInstanceOptions, storeInstanceOptions, this);
469
+ this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();
470
+ this._running = 0;
471
+ this._done = 0;
472
+ this._unblockTime = 0;
473
+ this.ready = this.Promise.resolve();
474
+ this.clients = {};
475
+ this._startHeartbeat();
476
+ }
477
+
478
+ _startHeartbeat() {
479
+ var base;
480
+ if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) {
481
+ return typeof (base = (this.heartbeat = setInterval(() => {
482
+ var amount, incr, maximum, now, reservoir;
483
+ now = Date.now();
484
+ if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {
485
+ this._lastReservoirRefresh = now;
486
+ this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;
487
+ this.instance._drainAll(this.computeCapacity());
488
+ }
489
+ if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {
490
+ ({
491
+ reservoirIncreaseAmount: amount,
492
+ reservoirIncreaseMaximum: maximum,
493
+ reservoir
494
+ } = this.storeOptions);
495
+ this._lastReservoirIncrease = now;
496
+ incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;
497
+ if (incr > 0) {
498
+ this.storeOptions.reservoir += incr;
499
+ return this.instance._drainAll(this.computeCapacity());
500
+ }
501
+ }
502
+ }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0;
503
+ } else {
504
+ return clearInterval(this.heartbeat);
505
+ }
506
+ }
507
+
508
+ async __publish__(message) {
509
+ await this.yieldLoop();
510
+ return this.instance.Events.trigger("message", message.toString());
511
+ }
512
+
513
+ async __disconnect__(flush) {
514
+ await this.yieldLoop();
515
+ clearInterval(this.heartbeat);
516
+ return this.Promise.resolve();
517
+ }
518
+
519
+ yieldLoop(t = 0) {
520
+ return new this.Promise(function(resolve, reject) {
521
+ return setTimeout(resolve, t);
522
+ });
523
+ }
524
+
525
+ computePenalty() {
526
+ var ref;
527
+ return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000;
528
+ }
529
+
530
+ async __updateSettings__(options) {
531
+ await this.yieldLoop();
532
+ parser$2.overwrite(options, options, this.storeOptions);
533
+ this._startHeartbeat();
534
+ this.instance._drainAll(this.computeCapacity());
535
+ return true;
536
+ }
537
+
538
+ async __running__() {
539
+ await this.yieldLoop();
540
+ return this._running;
541
+ }
542
+
543
+ async __queued__() {
544
+ await this.yieldLoop();
545
+ return this.instance.queued();
546
+ }
547
+
548
+ async __done__() {
549
+ await this.yieldLoop();
550
+ return this._done;
551
+ }
552
+
553
+ async __groupCheck__(time) {
554
+ await this.yieldLoop();
555
+ return (this._nextRequest + this.timeout) < time;
556
+ }
557
+
558
+ computeCapacity() {
559
+ var maxConcurrent, reservoir;
560
+ ({maxConcurrent, reservoir} = this.storeOptions);
561
+ if ((maxConcurrent != null) && (reservoir != null)) {
562
+ return Math.min(maxConcurrent - this._running, reservoir);
563
+ } else if (maxConcurrent != null) {
564
+ return maxConcurrent - this._running;
565
+ } else if (reservoir != null) {
566
+ return reservoir;
567
+ } else {
568
+ return null;
569
+ }
570
+ }
571
+
572
+ conditionsCheck(weight) {
573
+ var capacity;
574
+ capacity = this.computeCapacity();
575
+ return (capacity == null) || weight <= capacity;
576
+ }
577
+
578
+ async __incrementReservoir__(incr) {
579
+ var reservoir;
580
+ await this.yieldLoop();
581
+ reservoir = this.storeOptions.reservoir += incr;
582
+ this.instance._drainAll(this.computeCapacity());
583
+ return reservoir;
584
+ }
585
+
586
+ async __currentReservoir__() {
587
+ await this.yieldLoop();
588
+ return this.storeOptions.reservoir;
589
+ }
590
+
591
+ isBlocked(now) {
592
+ return this._unblockTime >= now;
593
+ }
594
+
595
+ check(weight, now) {
596
+ return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0;
597
+ }
598
+
599
+ async __check__(weight) {
600
+ var now;
601
+ await this.yieldLoop();
602
+ now = Date.now();
603
+ return this.check(weight, now);
604
+ }
605
+
606
+ async __register__(index, weight, expiration) {
607
+ var now, wait;
608
+ await this.yieldLoop();
609
+ now = Date.now();
610
+ if (this.conditionsCheck(weight)) {
611
+ this._running += weight;
612
+ if (this.storeOptions.reservoir != null) {
613
+ this.storeOptions.reservoir -= weight;
614
+ }
615
+ wait = Math.max(this._nextRequest - now, 0);
616
+ this._nextRequest = now + wait + this.storeOptions.minTime;
617
+ return {
618
+ success: true,
619
+ wait,
620
+ reservoir: this.storeOptions.reservoir
621
+ };
622
+ } else {
623
+ return {
624
+ success: false
625
+ };
626
+ }
627
+ }
628
+
629
+ strategyIsBlock() {
630
+ return this.storeOptions.strategy === 3;
631
+ }
632
+
633
+ async __submit__(queueLength, weight) {
634
+ var blocked, now, reachedHWM;
635
+ await this.yieldLoop();
636
+ if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) {
637
+ throw new TaskpaceError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);
638
+ }
639
+ now = Date.now();
640
+ reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now);
641
+ blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));
642
+ if (blocked) {
643
+ this._unblockTime = now + this.computePenalty();
644
+ this._nextRequest = this._unblockTime + this.storeOptions.minTime;
645
+ this.instance._dropAllQueued();
646
+ }
647
+ return {
648
+ reachedHWM,
649
+ blocked,
650
+ strategy: this.storeOptions.strategy
651
+ };
652
+ }
653
+
654
+ async __free__(index, weight) {
655
+ await this.yieldLoop();
656
+ this._running -= weight;
657
+ this._done += weight;
658
+ this.instance._drainAll(this.computeCapacity());
659
+ return {
660
+ running: this._running
661
+ };
662
+ }
663
+
664
+ };
665
+
666
+ var LocalDatastore_1 = LocalDatastore;
667
+
668
+ var TaskpaceError$3, States;
669
+
670
+ TaskpaceError$3 = TaskpaceError_1;
671
+
672
+ States = class States {
673
+ constructor(status1) {
674
+ this.status = status1;
675
+ this._jobs = {};
676
+ this.counts = this.status.map(function() {
677
+ return 0;
678
+ });
679
+ }
680
+
681
+ next(id) {
682
+ var current, next;
683
+ current = this._jobs[id];
684
+ next = current + 1;
685
+ if ((current != null) && next < this.status.length) {
686
+ this.counts[current]--;
687
+ this.counts[next]++;
688
+ return this._jobs[id]++;
689
+ } else if (current != null) {
690
+ this.counts[current]--;
691
+ return delete this._jobs[id];
692
+ }
693
+ }
694
+
695
+ start(id) {
696
+ var initial;
697
+ initial = 0;
698
+ this._jobs[id] = initial;
699
+ return this.counts[initial]++;
700
+ }
701
+
702
+ remove(id) {
703
+ var current;
704
+ current = this._jobs[id];
705
+ if (current != null) {
706
+ this.counts[current]--;
707
+ delete this._jobs[id];
708
+ }
709
+ return current != null;
710
+ }
711
+
712
+ jobStatus(id) {
713
+ var ref;
714
+ return (ref = this.status[this._jobs[id]]) != null ? ref : null;
715
+ }
716
+
717
+ statusJobs(status) {
718
+ var k, pos, ref, results, v;
719
+ if (status != null) {
720
+ pos = this.status.indexOf(status);
721
+ if (pos < 0) {
722
+ throw new TaskpaceError$3(`status must be one of ${this.status.join(', ')}`);
723
+ }
724
+ ref = this._jobs;
725
+ results = [];
726
+ for (k in ref) {
727
+ v = ref[k];
728
+ if (v === pos) {
729
+ results.push(k);
730
+ }
731
+ }
732
+ return results;
733
+ } else {
734
+ return Object.keys(this._jobs);
735
+ }
736
+ }
737
+
738
+ statusCounts() {
739
+ return this.counts.reduce(((acc, v, i) => {
740
+ acc[this.status[i]] = v;
741
+ return acc;
742
+ }), {});
743
+ }
744
+
745
+ };
746
+
747
+ var States_1 = States;
748
+
749
+ var DLList$2, Sync;
750
+
751
+ DLList$2 = DLList_1;
752
+
753
+ Sync = class Sync {
754
+ constructor(name, Promise) {
755
+ this.schedule = this.schedule.bind(this);
756
+ this.name = name;
757
+ this.Promise = Promise;
758
+ this._running = 0;
759
+ this._queue = new DLList$2();
760
+ }
761
+
762
+ isEmpty() {
763
+ return this._queue.length === 0;
764
+ }
765
+
766
+ async _tryToRun() {
767
+ var args, cb, error, reject, resolve, returned, task;
768
+ if ((this._running < 1) && this._queue.length > 0) {
769
+ this._running++;
770
+ ({task, args, resolve, reject} = this._queue.shift());
771
+ cb = (await (async function() {
772
+ try {
773
+ returned = (await task(...args));
774
+ return function() {
775
+ return resolve(returned);
776
+ };
777
+ } catch (error1) {
778
+ error = error1;
779
+ return function() {
780
+ return reject(error);
781
+ };
782
+ }
783
+ })());
784
+ this._running--;
785
+ this._tryToRun();
786
+ return cb();
787
+ }
788
+ }
789
+
790
+ schedule(task, ...args) {
791
+ var promise, reject, resolve;
792
+ resolve = reject = null;
793
+ promise = new this.Promise(function(_resolve, _reject) {
794
+ resolve = _resolve;
795
+ return reject = _reject;
796
+ });
797
+ this._queue.push({task, args, resolve, reject});
798
+ this._tryToRun();
799
+ return promise;
800
+ }
801
+
802
+ };
803
+
804
+ var Sync_1 = Sync;
805
+
806
+ var version = "2.19.5";
807
+ var version$1 = {
808
+ version: version
809
+ };
810
+
811
+ var version$2 = /*#__PURE__*/Object.freeze({
812
+ version: version,
813
+ default: version$1
814
+ });
815
+
816
+ var require$$2 = () => console.log('You must import the full version of Taskpace in order to use this feature.');
817
+
818
+ var require$$3 = () => console.log('You must import the full version of Taskpace in order to use this feature.');
819
+
820
+ var require$$4 = () => console.log('You must import the full version of Taskpace in order to use this feature.');
821
+
822
+ var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3;
823
+
824
+ parser$3 = parser;
825
+
826
+ Events$2 = Events_1;
827
+
828
+ RedisConnection$1 = require$$2;
829
+
830
+ IORedisConnection$1 = require$$3;
831
+
832
+ Scripts$1 = require$$4;
833
+
834
+ Group = (function() {
835
+ class Group {
836
+ constructor(limiterOptions = {}) {
837
+ this.deleteKey = this.deleteKey.bind(this);
838
+ this.limiterOptions = limiterOptions;
839
+ parser$3.load(this.limiterOptions, this.defaults, this);
840
+ this.Events = new Events$2(this);
841
+ this.instances = {};
842
+ this.Taskpace = Taskpace_1;
843
+ this._startAutoCleanup();
844
+ this.sharedConnection = this.connection != null;
845
+ if (this.connection == null) {
846
+ if (this.limiterOptions.datastore === "redis") {
847
+ this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
848
+ } else if (this.limiterOptions.datastore === "ioredis") {
849
+ this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
850
+ }
851
+ }
852
+ }
853
+
854
+ key(key = "") {
855
+ var ref;
856
+ return (ref = this.instances[key]) != null ? ref : (() => {
857
+ var limiter;
858
+ limiter = this.instances[key] = new this.Taskpace(Object.assign(this.limiterOptions, {
859
+ id: `${this.id}-${key}`,
860
+ timeout: this.timeout,
861
+ connection: this.connection
862
+ }));
863
+ this.Events.trigger("created", limiter, key);
864
+ return limiter;
865
+ })();
866
+ }
867
+
868
+ async deleteKey(key = "") {
869
+ var deleted, instance;
870
+ instance = this.instances[key];
871
+ if (this.connection) {
872
+ deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)]));
873
+ }
874
+ if (instance != null) {
875
+ delete this.instances[key];
876
+ await instance.disconnect();
877
+ }
878
+ return (instance != null) || deleted > 0;
879
+ }
880
+
881
+ limiters() {
882
+ var k, ref, results, v;
883
+ ref = this.instances;
884
+ results = [];
885
+ for (k in ref) {
886
+ v = ref[k];
887
+ results.push({
888
+ key: k,
889
+ limiter: v
890
+ });
891
+ }
892
+ return results;
893
+ }
894
+
895
+ keys() {
896
+ return Object.keys(this.instances);
897
+ }
898
+
899
+ async clusterKeys() {
900
+ var cursor, end, found, i, k, keys, len, next, start;
901
+ if (this.connection == null) {
902
+ return this.Promise.resolve(this.keys());
903
+ }
904
+ keys = [];
905
+ cursor = null;
906
+ start = `b_${this.id}-`.length;
907
+ end = "_settings".length;
908
+ while (cursor !== 0) {
909
+ [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000]));
910
+ cursor = ~~next;
911
+ for (i = 0, len = found.length; i < len; i++) {
912
+ k = found[i];
913
+ keys.push(k.slice(start, -end));
914
+ }
915
+ }
916
+ return keys;
917
+ }
918
+
919
+ _startAutoCleanup() {
920
+ var base;
921
+ clearInterval(this.interval);
922
+ return typeof (base = (this.interval = setInterval(async() => {
923
+ var e, k, ref, results, time, v;
924
+ time = Date.now();
925
+ ref = this.instances;
926
+ results = [];
927
+ for (k in ref) {
928
+ v = ref[k];
929
+ try {
930
+ if ((await v._store.__groupCheck__(time))) {
931
+ results.push(this.deleteKey(k));
932
+ } else {
933
+ results.push(void 0);
934
+ }
935
+ } catch (error) {
936
+ e = error;
937
+ results.push(v.Events.trigger("error", e));
938
+ }
939
+ }
940
+ return results;
941
+ }, this.timeout / 2))).unref === "function" ? base.unref() : void 0;
942
+ }
943
+
944
+ updateSettings(options = {}) {
945
+ parser$3.overwrite(options, this.defaults, this);
946
+ parser$3.overwrite(options, options, this.limiterOptions);
947
+ if (options.timeout != null) {
948
+ return this._startAutoCleanup();
949
+ }
950
+ }
951
+
952
+ disconnect(flush = true) {
953
+ var ref;
954
+ if (!this.sharedConnection) {
955
+ return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
956
+ }
957
+ }
958
+
959
+ }
960
+ Group.prototype.defaults = {
961
+ timeout: 1000 * 60 * 5,
962
+ connection: null,
963
+ Promise: Promise,
964
+ id: "group-key"
965
+ };
966
+
967
+ return Group;
968
+
969
+ }).call(commonjsGlobal);
970
+
971
+ var Group_1 = Group;
972
+
973
+ var Batcher, Events$3, parser$4;
974
+
975
+ parser$4 = parser;
976
+
977
+ Events$3 = Events_1;
978
+
979
+ Batcher = (function() {
980
+ class Batcher {
981
+ constructor(options = {}) {
982
+ this.options = options;
983
+ parser$4.load(this.options, this.defaults, this);
984
+ this.Events = new Events$3(this);
985
+ this._arr = [];
986
+ this._resetPromise();
987
+ this._lastFlush = Date.now();
988
+ }
989
+
990
+ _resetPromise() {
991
+ return this._promise = new this.Promise((res, rej) => {
992
+ return this._resolve = res;
993
+ });
994
+ }
995
+
996
+ _flush() {
997
+ clearTimeout(this._timeout);
998
+ this._lastFlush = Date.now();
999
+ this._resolve();
1000
+ this.Events.trigger("batch", this._arr);
1001
+ this._arr = [];
1002
+ return this._resetPromise();
1003
+ }
1004
+
1005
+ add(data) {
1006
+ var ret;
1007
+ this._arr.push(data);
1008
+ ret = this._promise;
1009
+ if (this._arr.length === this.maxSize) {
1010
+ this._flush();
1011
+ } else if ((this.maxTime != null) && this._arr.length === 1) {
1012
+ this._timeout = setTimeout(() => {
1013
+ return this._flush();
1014
+ }, this.maxTime);
1015
+ }
1016
+ return ret;
1017
+ }
1018
+
1019
+ }
1020
+ Batcher.prototype.defaults = {
1021
+ maxTime: null,
1022
+ maxSize: null,
1023
+ Promise: Promise
1024
+ };
1025
+
1026
+ return Batcher;
1027
+
1028
+ }).call(commonjsGlobal);
1029
+
1030
+ var Batcher_1 = Batcher;
1031
+
1032
+ var require$$4$1 = () => console.log('You must import the full version of Taskpace in order to use this feature.');
1033
+
1034
+ var require$$8 = getCjsExportFromNamespace(version$2);
1035
+
1036
+ var Taskpace, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5,
1037
+ splice = [].splice;
1038
+
1039
+ NUM_PRIORITIES$1 = 10;
1040
+
1041
+ DEFAULT_PRIORITY$1 = 5;
1042
+
1043
+ parser$5 = parser;
1044
+
1045
+ Queues$1 = Queues_1;
1046
+
1047
+ Job$1 = Job_1;
1048
+
1049
+ LocalDatastore$1 = LocalDatastore_1;
1050
+
1051
+ RedisDatastore$1 = require$$4$1;
1052
+
1053
+ Events$4 = Events_1;
1054
+
1055
+ States$1 = States_1;
1056
+
1057
+ Sync$1 = Sync_1;
1058
+
1059
+ Taskpace = (function() {
1060
+ class Taskpace {
1061
+ constructor(options = {}, ...invalid) {
1062
+ var storeInstanceOptions, storeOptions;
1063
+ this._addToQueue = this._addToQueue.bind(this);
1064
+ this._validateOptions(options, invalid);
1065
+ parser$5.load(options, this.instanceDefaults, this);
1066
+ this._queues = new Queues$1(NUM_PRIORITIES$1);
1067
+ this._scheduled = {};
1068
+ this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
1069
+ this._limiter = null;
1070
+ this.Events = new Events$4(this);
1071
+ this._submitLock = new Sync$1("submit", this.Promise);
1072
+ this._registerLock = new Sync$1("register", this.Promise);
1073
+ storeOptions = parser$5.load(options, this.storeDefaults, {});
1074
+ this._store = (function() {
1075
+ if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) {
1076
+ storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {});
1077
+ return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
1078
+ } else if (this.datastore === "local") {
1079
+ storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {});
1080
+ return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
1081
+ } else {
1082
+ throw new Taskpace.prototype.TaskpaceError(`Invalid datastore type: ${this.datastore}`);
1083
+ }
1084
+ }).call(this);
1085
+ this._queues.on("leftzero", () => {
1086
+ var ref;
1087
+ return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0;
1088
+ });
1089
+ this._queues.on("zero", () => {
1090
+ var ref;
1091
+ return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0;
1092
+ });
1093
+ }
1094
+
1095
+ _validateOptions(options, invalid) {
1096
+ if (!((options != null) && typeof options === "object" && invalid.length === 0)) {
1097
+ throw new Taskpace.prototype.TaskpaceError("Taskpace v2 takes a single object argument. Refer to https://github.com/PaceJS/taskpace#upgrading-to-v2 if you're upgrading from Taskpace v1.");
1098
+ }
1099
+ }
1100
+
1101
+ ready() {
1102
+ return this._store.ready;
1103
+ }
1104
+
1105
+ clients() {
1106
+ return this._store.clients;
1107
+ }
1108
+
1109
+ channel() {
1110
+ return `b_${this.id}`;
1111
+ }
1112
+
1113
+ channel_client() {
1114
+ return `b_${this.id}_${this._store.clientId}`;
1115
+ }
1116
+
1117
+ publish(message) {
1118
+ return this._store.__publish__(message);
1119
+ }
1120
+
1121
+ disconnect(flush = true) {
1122
+ return this._store.__disconnect__(flush);
1123
+ }
1124
+
1125
+ chain(_limiter) {
1126
+ this._limiter = _limiter;
1127
+ return this;
1128
+ }
1129
+
1130
+ queued(priority) {
1131
+ return this._queues.queued(priority);
1132
+ }
1133
+
1134
+ clusterQueued() {
1135
+ return this._store.__queued__();
1136
+ }
1137
+
1138
+ empty() {
1139
+ return this.queued() === 0 && this._submitLock.isEmpty();
1140
+ }
1141
+
1142
+ running() {
1143
+ return this._store.__running__();
1144
+ }
1145
+
1146
+ done() {
1147
+ return this._store.__done__();
1148
+ }
1149
+
1150
+ jobStatus(id) {
1151
+ return this._states.jobStatus(id);
1152
+ }
1153
+
1154
+ jobs(status) {
1155
+ return this._states.statusJobs(status);
1156
+ }
1157
+
1158
+ counts() {
1159
+ return this._states.statusCounts();
1160
+ }
1161
+
1162
+ _randomIndex() {
1163
+ return Math.random().toString(36).slice(2);
1164
+ }
1165
+
1166
+ check(weight = 1) {
1167
+ return this._store.__check__(weight);
1168
+ }
1169
+
1170
+ _clearGlobalState(index) {
1171
+ if (this._scheduled[index] != null) {
1172
+ clearTimeout(this._scheduled[index].expiration);
1173
+ delete this._scheduled[index];
1174
+ return true;
1175
+ } else {
1176
+ return false;
1177
+ }
1178
+ }
1179
+
1180
+ async _free(index, job, options, eventInfo) {
1181
+ var e, running;
1182
+ try {
1183
+ ({running} = (await this._store.__free__(index, options.weight)));
1184
+ this.Events.trigger("debug", `Freed ${options.id}`, eventInfo);
1185
+ if (running === 0 && this.empty()) {
1186
+ return this.Events.trigger("idle");
1187
+ }
1188
+ } catch (error1) {
1189
+ e = error1;
1190
+ return this.Events.trigger("error", e);
1191
+ }
1192
+ }
1193
+
1194
+ _run(index, job, wait) {
1195
+ var clearGlobalState, free, run;
1196
+ job.doRun();
1197
+ clearGlobalState = this._clearGlobalState.bind(this, index);
1198
+ run = this._run.bind(this, index, job);
1199
+ free = this._free.bind(this, index, job);
1200
+ return this._scheduled[index] = {
1201
+ timeout: setTimeout(() => {
1202
+ return job.doExecute(this._limiter, clearGlobalState, run, free);
1203
+ }, wait),
1204
+ expiration: job.options.expiration != null ? setTimeout(function() {
1205
+ return job.doExpire(clearGlobalState, run, free);
1206
+ }, wait + job.options.expiration) : void 0,
1207
+ job: job
1208
+ };
1209
+ }
1210
+
1211
+ _drainOne(capacity) {
1212
+ return this._registerLock.schedule(() => {
1213
+ var args, index, next, options, queue;
1214
+ if (this.queued() === 0) {
1215
+ return this.Promise.resolve(null);
1216
+ }
1217
+ queue = this._queues.getFirst();
1218
+ ({options, args} = next = queue.first());
1219
+ if ((capacity != null) && options.weight > capacity) {
1220
+ return this.Promise.resolve(null);
1221
+ }
1222
+ this.Events.trigger("debug", `Draining ${options.id}`, {args, options});
1223
+ index = this._randomIndex();
1224
+ return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => {
1225
+ var empty;
1226
+ this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options});
1227
+ if (success) {
1228
+ queue.shift();
1229
+ empty = this.empty();
1230
+ if (empty) {
1231
+ this.Events.trigger("empty");
1232
+ }
1233
+ if (reservoir === 0) {
1234
+ this.Events.trigger("depleted", empty);
1235
+ }
1236
+ this._run(index, next, wait);
1237
+ return this.Promise.resolve(options.weight);
1238
+ } else {
1239
+ return this.Promise.resolve(null);
1240
+ }
1241
+ });
1242
+ });
1243
+ }
1244
+
1245
+ _drainAll(capacity, total = 0) {
1246
+ return this._drainOne(capacity).then((drained) => {
1247
+ var newCapacity;
1248
+ if (drained != null) {
1249
+ newCapacity = capacity != null ? capacity - drained : capacity;
1250
+ return this._drainAll(newCapacity, total + drained);
1251
+ } else {
1252
+ return this.Promise.resolve(total);
1253
+ }
1254
+ }).catch((e) => {
1255
+ return this.Events.trigger("error", e);
1256
+ });
1257
+ }
1258
+
1259
+ _dropAllQueued(message) {
1260
+ return this._queues.shiftAll(function(job) {
1261
+ return job.doDrop({message});
1262
+ });
1263
+ }
1264
+
1265
+ stop(options = {}) {
1266
+ var done, waitForExecuting;
1267
+ options = parser$5.load(options, this.stopDefaults);
1268
+ waitForExecuting = (at) => {
1269
+ var finished;
1270
+ finished = () => {
1271
+ var counts;
1272
+ counts = this._states.counts;
1273
+ return (counts[0] + counts[1] + counts[2] + counts[3]) === at;
1274
+ };
1275
+ return new this.Promise((resolve, reject) => {
1276
+ if (finished()) {
1277
+ return resolve();
1278
+ } else {
1279
+ return this.on("done", () => {
1280
+ if (finished()) {
1281
+ this.removeAllListeners("done");
1282
+ return resolve();
1283
+ }
1284
+ });
1285
+ }
1286
+ });
1287
+ };
1288
+ done = options.dropWaitingJobs ? (this._run = function(index, next) {
1289
+ return next.doDrop({
1290
+ message: options.dropErrorMessage
1291
+ });
1292
+ }, this._drainOne = () => {
1293
+ return this.Promise.resolve(null);
1294
+ }, this._registerLock.schedule(() => {
1295
+ return this._submitLock.schedule(() => {
1296
+ var k, ref, v;
1297
+ ref = this._scheduled;
1298
+ for (k in ref) {
1299
+ v = ref[k];
1300
+ if (this.jobStatus(v.job.options.id) === "RUNNING") {
1301
+ clearTimeout(v.timeout);
1302
+ clearTimeout(v.expiration);
1303
+ v.job.doDrop({
1304
+ message: options.dropErrorMessage
1305
+ });
1306
+ }
1307
+ }
1308
+ this._dropAllQueued(options.dropErrorMessage);
1309
+ return waitForExecuting(0);
1310
+ });
1311
+ })) : this.schedule({
1312
+ priority: NUM_PRIORITIES$1 - 1,
1313
+ weight: 0
1314
+ }, () => {
1315
+ return waitForExecuting(1);
1316
+ });
1317
+ this._receive = function(job) {
1318
+ return job._reject(new Taskpace.prototype.TaskpaceError(options.enqueueErrorMessage));
1319
+ };
1320
+ this.stop = () => {
1321
+ return this.Promise.reject(new Taskpace.prototype.TaskpaceError("stop() has already been called"));
1322
+ };
1323
+ return done;
1324
+ }
1325
+
1326
+ async _addToQueue(job) {
1327
+ var args, blocked, error, options, reachedHWM, shifted, strategy;
1328
+ ({args, options} = job);
1329
+ try {
1330
+ ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight)));
1331
+ } catch (error1) {
1332
+ error = error1;
1333
+ this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error});
1334
+ job.doDrop({error});
1335
+ return false;
1336
+ }
1337
+ if (blocked) {
1338
+ job.doDrop();
1339
+ return true;
1340
+ } else if (reachedHWM) {
1341
+ shifted = strategy === Taskpace.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Taskpace.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Taskpace.prototype.strategy.OVERFLOW ? job : void 0;
1342
+ if (shifted != null) {
1343
+ shifted.doDrop();
1344
+ }
1345
+ if ((shifted == null) || strategy === Taskpace.prototype.strategy.OVERFLOW) {
1346
+ if (shifted == null) {
1347
+ job.doDrop();
1348
+ }
1349
+ return reachedHWM;
1350
+ }
1351
+ }
1352
+ job.doQueue(reachedHWM, blocked);
1353
+ this._queues.push(job);
1354
+ await this._drainAll();
1355
+ return reachedHWM;
1356
+ }
1357
+
1358
+ _receive(job) {
1359
+ if (this._states.jobStatus(job.options.id) != null) {
1360
+ job._reject(new Taskpace.prototype.TaskpaceError(`A job with the same id already exists (id=${job.options.id})`));
1361
+ return false;
1362
+ } else {
1363
+ job.doReceive();
1364
+ return this._submitLock.schedule(this._addToQueue, job);
1365
+ }
1366
+ }
1367
+
1368
+ submit(...args) {
1369
+ var cb, fn, job, options, ref, ref1, task;
1370
+ if (typeof args[0] === "function") {
1371
+ ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1);
1372
+ options = parser$5.load({}, this.jobDefaults);
1373
+ } else {
1374
+ ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1);
1375
+ options = parser$5.load(options, this.jobDefaults);
1376
+ }
1377
+ task = (...args) => {
1378
+ return new this.Promise(function(resolve, reject) {
1379
+ return fn(...args, function(...args) {
1380
+ return (args[0] != null ? reject : resolve)(args);
1381
+ });
1382
+ });
1383
+ };
1384
+ job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
1385
+ job.promise.then(function(args) {
1386
+ return typeof cb === "function" ? cb(...args) : void 0;
1387
+ }).catch(function(args) {
1388
+ if (Array.isArray(args)) {
1389
+ return typeof cb === "function" ? cb(...args) : void 0;
1390
+ } else {
1391
+ return typeof cb === "function" ? cb(args) : void 0;
1392
+ }
1393
+ });
1394
+ return this._receive(job);
1395
+ }
1396
+
1397
+ schedule(...args) {
1398
+ var job, options, task;
1399
+ if (typeof args[0] === "function") {
1400
+ [task, ...args] = args;
1401
+ options = {};
1402
+ } else {
1403
+ [options, task, ...args] = args;
1404
+ }
1405
+ job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
1406
+ this._receive(job);
1407
+ return job.promise;
1408
+ }
1409
+
1410
+ wrap(fn) {
1411
+ var schedule, wrapped;
1412
+ schedule = this.schedule.bind(this);
1413
+ wrapped = function(...args) {
1414
+ return schedule(fn.bind(this), ...args);
1415
+ };
1416
+ wrapped.withOptions = function(options, ...args) {
1417
+ return schedule(options, fn, ...args);
1418
+ };
1419
+ return wrapped;
1420
+ }
1421
+
1422
+ async updateSettings(options = {}) {
1423
+ await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults));
1424
+ parser$5.overwrite(options, this.instanceDefaults, this);
1425
+ return this;
1426
+ }
1427
+
1428
+ currentReservoir() {
1429
+ return this._store.__currentReservoir__();
1430
+ }
1431
+
1432
+ incrementReservoir(incr = 0) {
1433
+ return this._store.__incrementReservoir__(incr);
1434
+ }
1435
+
1436
+ }
1437
+ Taskpace.default = Taskpace;
1438
+
1439
+ Taskpace.Events = Events$4;
1440
+
1441
+ Taskpace.version = Taskpace.prototype.version = require$$8.version;
1442
+
1443
+ Taskpace.strategy = Taskpace.prototype.strategy = {
1444
+ LEAK: 1,
1445
+ OVERFLOW: 2,
1446
+ OVERFLOW_PRIORITY: 4,
1447
+ BLOCK: 3
1448
+ };
1449
+
1450
+ Taskpace.TaskpaceError = Taskpace.prototype.TaskpaceError = TaskpaceError_1;
1451
+
1452
+ Taskpace.Group = Taskpace.prototype.Group = Group_1;
1453
+
1454
+ Taskpace.RedisConnection = Taskpace.prototype.RedisConnection = require$$2;
1455
+
1456
+ Taskpace.IORedisConnection = Taskpace.prototype.IORedisConnection = require$$3;
1457
+
1458
+ Taskpace.Batcher = Taskpace.prototype.Batcher = Batcher_1;
1459
+
1460
+ Taskpace.prototype.jobDefaults = {
1461
+ priority: DEFAULT_PRIORITY$1,
1462
+ weight: 1,
1463
+ expiration: null,
1464
+ id: "<no-id>"
1465
+ };
1466
+
1467
+ Taskpace.prototype.storeDefaults = {
1468
+ maxConcurrent: null,
1469
+ minTime: 0,
1470
+ highWater: null,
1471
+ strategy: Taskpace.prototype.strategy.LEAK,
1472
+ penalty: null,
1473
+ reservoir: null,
1474
+ reservoirRefreshInterval: null,
1475
+ reservoirRefreshAmount: null,
1476
+ reservoirIncreaseInterval: null,
1477
+ reservoirIncreaseAmount: null,
1478
+ reservoirIncreaseMaximum: null
1479
+ };
1480
+
1481
+ Taskpace.prototype.localStoreDefaults = {
1482
+ Promise: Promise,
1483
+ timeout: null,
1484
+ heartbeatInterval: 250
1485
+ };
1486
+
1487
+ Taskpace.prototype.redisStoreDefaults = {
1488
+ Promise: Promise,
1489
+ timeout: null,
1490
+ heartbeatInterval: 5000,
1491
+ clientTimeout: 10000,
1492
+ Redis: null,
1493
+ clientOptions: {},
1494
+ clusterNodes: null,
1495
+ clearDatastore: false,
1496
+ connection: null
1497
+ };
1498
+
1499
+ Taskpace.prototype.instanceDefaults = {
1500
+ datastore: "local",
1501
+ connection: null,
1502
+ id: "<no-id>",
1503
+ rejectOnDrop: true,
1504
+ trackDoneStatus: false,
1505
+ Promise: Promise
1506
+ };
1507
+
1508
+ Taskpace.prototype.stopDefaults = {
1509
+ enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
1510
+ dropWaitingJobs: true,
1511
+ dropErrorMessage: "This limiter has been stopped."
1512
+ };
1513
+
1514
+ return Taskpace;
1515
+
1516
+ }).call(commonjsGlobal);
1517
+
1518
+ var Taskpace_1 = Taskpace;
1519
+
1520
+ var lib = Taskpace_1;
1521
+
1522
+ return lib;
1523
+
1524
+ })));