@rango-dev/queue-manager-core 0.1.15-next.5 → 0.1.15-next.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1500 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var idb = require('idb');
6
- var uuid = require('uuid');
7
-
8
- function _regeneratorRuntime() {
9
- _regeneratorRuntime = function () {
10
- return exports;
11
- };
12
- var exports = {},
13
- Op = Object.prototype,
14
- hasOwn = Op.hasOwnProperty,
15
- defineProperty = Object.defineProperty || function (obj, key, desc) {
16
- obj[key] = desc.value;
17
- },
18
- $Symbol = "function" == typeof Symbol ? Symbol : {},
19
- iteratorSymbol = $Symbol.iterator || "@@iterator",
20
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
21
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
22
- function define(obj, key, value) {
23
- return Object.defineProperty(obj, key, {
24
- value: value,
25
- enumerable: !0,
26
- configurable: !0,
27
- writable: !0
28
- }), obj[key];
29
- }
30
- try {
31
- define({}, "");
32
- } catch (err) {
33
- define = function (obj, key, value) {
34
- return obj[key] = value;
35
- };
36
- }
37
- function wrap(innerFn, outerFn, self, tryLocsList) {
38
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
39
- generator = Object.create(protoGenerator.prototype),
40
- context = new Context(tryLocsList || []);
41
- return defineProperty(generator, "_invoke", {
42
- value: makeInvokeMethod(innerFn, self, context)
43
- }), generator;
44
- }
45
- function tryCatch(fn, obj, arg) {
46
- try {
47
- return {
48
- type: "normal",
49
- arg: fn.call(obj, arg)
50
- };
51
- } catch (err) {
52
- return {
53
- type: "throw",
54
- arg: err
55
- };
56
- }
57
- }
58
- exports.wrap = wrap;
59
- var ContinueSentinel = {};
60
- function Generator() {}
61
- function GeneratorFunction() {}
62
- function GeneratorFunctionPrototype() {}
63
- var IteratorPrototype = {};
64
- define(IteratorPrototype, iteratorSymbol, function () {
65
- return this;
66
- });
67
- var getProto = Object.getPrototypeOf,
68
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
69
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
70
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
71
- function defineIteratorMethods(prototype) {
72
- ["next", "throw", "return"].forEach(function (method) {
73
- define(prototype, method, function (arg) {
74
- return this._invoke(method, arg);
75
- });
76
- });
77
- }
78
- function AsyncIterator(generator, PromiseImpl) {
79
- function invoke(method, arg, resolve, reject) {
80
- var record = tryCatch(generator[method], generator, arg);
81
- if ("throw" !== record.type) {
82
- var result = record.arg,
83
- value = result.value;
84
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
85
- invoke("next", value, resolve, reject);
86
- }, function (err) {
87
- invoke("throw", err, resolve, reject);
88
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
89
- result.value = unwrapped, resolve(result);
90
- }, function (error) {
91
- return invoke("throw", error, resolve, reject);
92
- });
93
- }
94
- reject(record.arg);
95
- }
96
- var previousPromise;
97
- defineProperty(this, "_invoke", {
98
- value: function (method, arg) {
99
- function callInvokeWithMethodAndArg() {
100
- return new PromiseImpl(function (resolve, reject) {
101
- invoke(method, arg, resolve, reject);
102
- });
103
- }
104
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
105
- }
106
- });
107
- }
108
- function makeInvokeMethod(innerFn, self, context) {
109
- var state = "suspendedStart";
110
- return function (method, arg) {
111
- if ("executing" === state) throw new Error("Generator is already running");
112
- if ("completed" === state) {
113
- if ("throw" === method) throw arg;
114
- return doneResult();
115
- }
116
- for (context.method = method, context.arg = arg;;) {
117
- var delegate = context.delegate;
118
- if (delegate) {
119
- var delegateResult = maybeInvokeDelegate(delegate, context);
120
- if (delegateResult) {
121
- if (delegateResult === ContinueSentinel) continue;
122
- return delegateResult;
123
- }
124
- }
125
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
126
- if ("suspendedStart" === state) throw state = "completed", context.arg;
127
- context.dispatchException(context.arg);
128
- } else "return" === context.method && context.abrupt("return", context.arg);
129
- state = "executing";
130
- var record = tryCatch(innerFn, self, context);
131
- if ("normal" === record.type) {
132
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
133
- return {
134
- value: record.arg,
135
- done: context.done
136
- };
137
- }
138
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
139
- }
140
- };
141
- }
142
- function maybeInvokeDelegate(delegate, context) {
143
- var methodName = context.method,
144
- method = delegate.iterator[methodName];
145
- if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
146
- var record = tryCatch(method, delegate.iterator, context.arg);
147
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
148
- var info = record.arg;
149
- return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
150
- }
151
- function pushTryEntry(locs) {
152
- var entry = {
153
- tryLoc: locs[0]
154
- };
155
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
156
- }
157
- function resetTryEntry(entry) {
158
- var record = entry.completion || {};
159
- record.type = "normal", delete record.arg, entry.completion = record;
160
- }
161
- function Context(tryLocsList) {
162
- this.tryEntries = [{
163
- tryLoc: "root"
164
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
165
- }
166
- function values(iterable) {
167
- if (iterable) {
168
- var iteratorMethod = iterable[iteratorSymbol];
169
- if (iteratorMethod) return iteratorMethod.call(iterable);
170
- if ("function" == typeof iterable.next) return iterable;
171
- if (!isNaN(iterable.length)) {
172
- var i = -1,
173
- next = function next() {
174
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
175
- return next.value = undefined, next.done = !0, next;
176
- };
177
- return next.next = next;
178
- }
179
- }
180
- return {
181
- next: doneResult
182
- };
183
- }
184
- function doneResult() {
185
- return {
186
- value: undefined,
187
- done: !0
188
- };
189
- }
190
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
191
- value: GeneratorFunctionPrototype,
192
- configurable: !0
193
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
194
- value: GeneratorFunction,
195
- configurable: !0
196
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
197
- var ctor = "function" == typeof genFun && genFun.constructor;
198
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
199
- }, exports.mark = function (genFun) {
200
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
201
- }, exports.awrap = function (arg) {
202
- return {
203
- __await: arg
204
- };
205
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
206
- return this;
207
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
208
- void 0 === PromiseImpl && (PromiseImpl = Promise);
209
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
210
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
211
- return result.done ? result.value : iter.next();
212
- });
213
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
214
- return this;
215
- }), define(Gp, "toString", function () {
216
- return "[object Generator]";
217
- }), exports.keys = function (val) {
218
- var object = Object(val),
219
- keys = [];
220
- for (var key in object) keys.push(key);
221
- return keys.reverse(), function next() {
222
- for (; keys.length;) {
223
- var key = keys.pop();
224
- if (key in object) return next.value = key, next.done = !1, next;
225
- }
226
- return next.done = !0, next;
227
- };
228
- }, exports.values = values, Context.prototype = {
229
- constructor: Context,
230
- reset: function (skipTempReset) {
231
- if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
232
- },
233
- stop: function () {
234
- this.done = !0;
235
- var rootRecord = this.tryEntries[0].completion;
236
- if ("throw" === rootRecord.type) throw rootRecord.arg;
237
- return this.rval;
238
- },
239
- dispatchException: function (exception) {
240
- if (this.done) throw exception;
241
- var context = this;
242
- function handle(loc, caught) {
243
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
244
- }
245
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
246
- var entry = this.tryEntries[i],
247
- record = entry.completion;
248
- if ("root" === entry.tryLoc) return handle("end");
249
- if (entry.tryLoc <= this.prev) {
250
- var hasCatch = hasOwn.call(entry, "catchLoc"),
251
- hasFinally = hasOwn.call(entry, "finallyLoc");
252
- if (hasCatch && hasFinally) {
253
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
254
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
255
- } else if (hasCatch) {
256
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
257
- } else {
258
- if (!hasFinally) throw new Error("try statement without catch or finally");
259
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
260
- }
261
- }
262
- }
263
- },
264
- abrupt: function (type, arg) {
265
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
266
- var entry = this.tryEntries[i];
267
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
268
- var finallyEntry = entry;
269
- break;
270
- }
271
- }
272
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
273
- var record = finallyEntry ? finallyEntry.completion : {};
274
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
275
- },
276
- complete: function (record, afterLoc) {
277
- if ("throw" === record.type) throw record.arg;
278
- return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
279
- },
280
- finish: function (finallyLoc) {
281
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
282
- var entry = this.tryEntries[i];
283
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
284
- }
285
- },
286
- catch: function (tryLoc) {
287
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
288
- var entry = this.tryEntries[i];
289
- if (entry.tryLoc === tryLoc) {
290
- var record = entry.completion;
291
- if ("throw" === record.type) {
292
- var thrown = record.arg;
293
- resetTryEntry(entry);
294
- }
295
- return thrown;
296
- }
297
- }
298
- throw new Error("illegal catch attempt");
299
- },
300
- delegateYield: function (iterable, resultName, nextLoc) {
301
- return this.delegate = {
302
- iterator: values(iterable),
303
- resultName: resultName,
304
- nextLoc: nextLoc
305
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
306
- }
307
- }, exports;
308
- }
309
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
310
- try {
311
- var info = gen[key](arg);
312
- var value = info.value;
313
- } catch (error) {
314
- reject(error);
315
- return;
316
- }
317
- if (info.done) {
318
- resolve(value);
319
- } else {
320
- Promise.resolve(value).then(_next, _throw);
321
- }
322
- }
323
- function _asyncToGenerator(fn) {
324
- return function () {
325
- var self = this,
326
- args = arguments;
327
- return new Promise(function (resolve, reject) {
328
- var gen = fn.apply(self, args);
329
- function _next(value) {
330
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
331
- }
332
- function _throw(err) {
333
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
334
- }
335
- _next(undefined);
336
- });
337
- };
338
- }
339
- function _extends() {
340
- _extends = Object.assign ? Object.assign.bind() : function (target) {
341
- for (var i = 1; i < arguments.length; i++) {
342
- var source = arguments[i];
343
- for (var key in source) {
344
- if (Object.prototype.hasOwnProperty.call(source, key)) {
345
- target[key] = source[key];
346
- }
347
- }
348
- }
349
- return target;
350
- };
351
- return _extends.apply(this, arguments);
352
- }
353
- function _unsupportedIterableToArray(o, minLen) {
354
- if (!o) return;
355
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
356
- var n = Object.prototype.toString.call(o).slice(8, -1);
357
- if (n === "Object" && o.constructor) n = o.constructor.name;
358
- if (n === "Map" || n === "Set") return Array.from(o);
359
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
360
- }
361
- function _arrayLikeToArray(arr, len) {
362
- if (len == null || len > arr.length) len = arr.length;
363
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
364
- return arr2;
365
- }
366
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
367
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
368
- if (it) return (it = it.call(o)).next.bind(it);
369
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
370
- if (it) o = it;
371
- var i = 0;
372
- return function () {
373
- if (i >= o.length) return {
374
- done: true
375
- };
376
- return {
377
- done: false,
378
- value: o[i++]
379
- };
380
- };
381
- }
382
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
383
- }
384
-
385
- var DB_NAME = 'queues-manager';
386
- var OBJECT_STORE_NAME = 'queues';
387
- var VERSION = 1;
388
- var Persistor = /*#__PURE__*/function () {
389
- function Persistor() {
390
- this.db = idb.openDB(DB_NAME, VERSION, {
391
- upgrade: function upgrade(db) {
392
- db.createObjectStore(OBJECT_STORE_NAME, {
393
- keyPath: 'id'
394
- });
395
- }
396
- });
397
- }
398
- var _proto = Persistor.prototype;
399
- _proto.insertQueue = /*#__PURE__*/function () {
400
- var _insertQueue = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(queue) {
401
- var db, queueRecord;
402
- return _regeneratorRuntime().wrap(function _callee$(_context) {
403
- while (1) switch (_context.prev = _context.next) {
404
- case 0:
405
- _context.next = 2;
406
- return this.db;
407
- case 2:
408
- db = _context.sent;
409
- _context.next = 5;
410
- return db.get(OBJECT_STORE_NAME, queue.id);
411
- case 5:
412
- queueRecord = _context.sent;
413
- if (!queueRecord) {
414
- _context.next = 9;
415
- break;
416
- }
417
- _context.next = 11;
418
- break;
419
- case 9:
420
- _context.next = 11;
421
- return db.add(OBJECT_STORE_NAME, queue);
422
- case 11:
423
- case "end":
424
- return _context.stop();
425
- }
426
- }, _callee, this);
427
- }));
428
- function insertQueue(_x) {
429
- return _insertQueue.apply(this, arguments);
430
- }
431
- return insertQueue;
432
- }();
433
- _proto.updateQueue = /*#__PURE__*/function () {
434
- var _updateQueue = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(id, queue) {
435
- var db, currentRecord, updatedRecord;
436
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
437
- while (1) switch (_context2.prev = _context2.next) {
438
- case 0:
439
- _context2.next = 2;
440
- return this.db;
441
- case 2:
442
- db = _context2.sent;
443
- _context2.next = 5;
444
- return db.get(OBJECT_STORE_NAME, id);
445
- case 5:
446
- currentRecord = _context2.sent;
447
- if (currentRecord) {
448
- _context2.next = 8;
449
- break;
450
- }
451
- return _context2.abrupt("return");
452
- case 8:
453
- updatedRecord = _extends({}, currentRecord, queue);
454
- _context2.next = 11;
455
- return db.put(OBJECT_STORE_NAME, updatedRecord);
456
- case 11:
457
- case "end":
458
- return _context2.stop();
459
- }
460
- }, _callee2, this);
461
- }));
462
- function updateQueue(_x2, _x3) {
463
- return _updateQueue.apply(this, arguments);
464
- }
465
- return updateQueue;
466
- }();
467
- _proto.getAll = /*#__PURE__*/function () {
468
- var _getAll = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
469
- var db, results;
470
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
471
- while (1) switch (_context3.prev = _context3.next) {
472
- case 0:
473
- _context3.next = 2;
474
- return this.db;
475
- case 2:
476
- db = _context3.sent;
477
- _context3.next = 5;
478
- return db.getAll(OBJECT_STORE_NAME);
479
- case 5:
480
- results = _context3.sent;
481
- return _context3.abrupt("return", results);
482
- case 7:
483
- case "end":
484
- return _context3.stop();
485
- }
486
- }, _callee3, this);
487
- }));
488
- function getAll() {
489
- return _getAll.apply(this, arguments);
490
- }
491
- return getAll;
492
- }();
493
- return Persistor;
494
- }();
495
-
496
- (function (Status) {
497
- Status["PENDING"] = "PENDING";
498
- Status["RUNNING"] = "RUNNING";
499
- Status["FAILED"] = "FAILED";
500
- Status["SUCCESS"] = "SUCCESS";
501
- Status["CANCELED"] = "CANCELED";
502
- Status["BLOCKED"] = "BLOCKED";
503
- })(exports.Status || (exports.Status = {}));
504
- var SYNC_POLLING_INTERVAL = 5000;
505
-
506
- /**
507
- *
508
- * Notes on statuses:
509
- * - Success: last task has success status
510
- * - Failed: any of task has been failed
511
- * - Running: first task is not on pending
512
- * - Pending: default state. not started
513
- *
514
- */
515
- var Queue = /*#__PURE__*/function () {
516
- function Queue(options) {
517
- this.state = {
518
- status: exports.Status.PENDING,
519
- activeTaskIndex: 0,
520
- tasks: {}
521
- };
522
- this.tasks = [];
523
- this.storage = {};
524
- this.id = options.id;
525
- this.events = options.events;
526
- this.actions = options.actions;
527
- }
528
- /**
529
- * Update queue status and trigger an event
530
- *
531
- */
532
- var _proto = Queue.prototype;
533
- _proto.updateQueueStatus = function updateQueueStatus(status) {
534
- this.state.status = status;
535
- this.events.onUpdateListStatus(status);
536
- };
537
- _proto.updateActiveTaskIndex = function updateActiveTaskIndex(index) {
538
- this.state.activeTaskIndex = index;
539
- }
540
- /**
541
- *
542
- * Update task state (`status`, `blockedFor`) and trigger an event.
543
- * @param id
544
- * @param nextState
545
- */;
546
- _proto.updateTaskState = function updateTaskState(id, nextState) {
547
- if (nextState.status) {
548
- this.state.tasks[id].status = nextState.status;
549
- }
550
- if (nextState.blockedFor) {
551
- this.state.tasks[id].blockedFor = nextState.blockedFor;
552
- }
553
- var updatedTaskEvent = {
554
- id: id,
555
- task: this.get(id),
556
- action: this.tasks.find(function (task) {
557
- return task.id === id;
558
- }).action
559
- };
560
- this.events.onUpdate(updatedTaskEvent);
561
- }
562
- /**
563
- * Create a task by providing an `action` name.
564
- *
565
- * this method creating the task, push it to the queue's tasks and trigger an event.
566
- * @param action
567
- */;
568
- _proto.createTask = function createTask(action) {
569
- var id = uuid.v4();
570
- this.tasks.push({
571
- action: action,
572
- id: id
573
- });
574
- this.state.tasks[id] = {
575
- status: exports.Status.PENDING,
576
- blockedFor: null
577
- };
578
- var createdTask = this.get(id);
579
- this.events.onCreate({
580
- id: id,
581
- task: createdTask,
582
- action: action
583
- });
584
- }
585
- /**
586
- * Initilize a queue with some tasks, instead of an empty queue.
587
- *
588
- * Using it for recover the queue state from persistor.
589
- *
590
- */;
591
- _proto.initTasks = function initTasks(info) {
592
- var _this = this;
593
- this.state = info.state;
594
- this.storage = info.storage;
595
- info.tasks.forEach(function (task) {
596
- _this.tasks.push(task);
597
- var action = _this.tasks.find(function (t) {
598
- return t.id === task.id;
599
- }).action;
600
- _this.events.onCreate({
601
- id: task.id,
602
- task: _this.get(task.id),
603
- action: action
604
- });
605
- });
606
- };
607
- _proto.checkBlock = function checkBlock() {
608
- var currentActiveTask = this.getActiveTask();
609
- if (!currentActiveTask) {
610
- return;
611
- }
612
- var task = currentActiveTask.task,
613
- state = currentActiveTask.state;
614
- if (state.status === exports.Status.BLOCKED) {
615
- this.events.onBlock({
616
- action: task.action,
617
- id: task.id,
618
- reason: state.blockedFor
619
- });
620
- }
621
- }
622
- /**
623
- * Getting task state by ID
624
- */;
625
- _proto.get = function get(id) {
626
- var task = this.state.tasks[id];
627
- if (!task) return null;
628
- return task;
629
- }
630
- /**
631
- *
632
- * Checking if status of the last is `SUCCESS` or not
633
- *
634
- */;
635
- _proto.lastTaskIsSuccessful = function lastTaskIsSuccessful() {
636
- var lastTask = this.tasks[this.tasks.length - 1];
637
- // checking for empty lists.
638
- if (lastTask) {
639
- var lastTaskState = this.state.tasks[lastTask.id];
640
- // Maybe we didn't create the state yet. It should has success status as well.
641
- if (!!lastTaskState && lastTaskState.status === exports.Status.SUCCESS) {
642
- return true;
643
- }
644
- }
645
- return false;
646
- }
647
- /**
648
- * If the first task started (it's not PENDING),
649
- * it means the queue has been ran.
650
- *
651
- * @returns
652
- */;
653
- _proto.firstTaskIsStarted = function firstTaskIsStarted() {
654
- var firstTask = this.tasks[0];
655
- // checking for empty lists.
656
- if (firstTask) {
657
- var firstTaskState = this.state.tasks[firstTask.id];
658
- // Maybe we didn't create the state yet.
659
- if (!!firstTaskState) {
660
- if (firstTaskState.status !== exports.Status.PENDING) {
661
- return true;
662
- }
663
- }
664
- }
665
- return false;
666
- }
667
- /**
668
- * Getting active task index from state and
669
- * returns the task and its state.
670
- *
671
- */;
672
- _proto.getActiveTask = function getActiveTask() {
673
- // First try to get task with `activeTask`
674
- var index = this.state.activeTaskIndex;
675
- var task = this.tasks[index];
676
- // Consider all the tasks has been executed.
677
- if (!task) {
678
- return null;
679
- }
680
- var state = this.state.tasks[task.id];
681
- return {
682
- task: task,
683
- state: state,
684
- index: index
685
- };
686
- }
687
- /**
688
- * Update and find the queue status by checking state of each tasks in the queue.
689
- */;
690
- _proto.check = function check() {
691
- var currentListStatus = this.state.status;
692
- var nextListStatus = this.firstTaskIsStarted() ? exports.Status.RUNNING : exports.Status.PENDING;
693
- if (this.lastTaskIsSuccessful()) {
694
- nextListStatus = exports.Status.SUCCESS;
695
- } else {
696
- // Is there any failed task?
697
- for (var _iterator = _createForOfIteratorHelperLoose(this.tasks), _step; !(_step = _iterator()).done;) {
698
- var task = _step.value;
699
- var state = this.state.tasks[task.id];
700
- // If one item fails, we stop to work on the list.
701
- if (state.status === exports.Status.FAILED) {
702
- nextListStatus = exports.Status.FAILED;
703
- break;
704
- }
705
- }
706
- }
707
- // We only update and trigger an event when there is a new value
708
- if (nextListStatus !== currentListStatus) {
709
- this.updateQueueStatus(nextListStatus);
710
- }
711
- }
712
- /**
713
- * Execute active task.
714
- * Based on the state of active task, the behaviour is different. If status is:
715
- * - Success -> we need to go to next task by updating the active index and try `next` on more time.
716
- * - Failed, Running, or no active task -> doesn't do anything.
717
- * - Pending or Blocked -> update the task and queue status to running, and execute the provided `action` for the task.
718
- *
719
- * The queue is a linked list somehow, active task means the pointer to where we are in the queue right now.
720
- *
721
- */;
722
- _proto.next = function next(params) {
723
- var _this2 = this;
724
- this.check();
725
- var currentActiveTask = this.getActiveTask();
726
- if (!currentActiveTask) {
727
- return;
728
- }
729
- var activeTaskIndex = currentActiveTask.index,
730
- activeTask = currentActiveTask.task,
731
- activeTaskState = currentActiveTask.state;
732
- // if `activeTask` is already done, we will go for next one.
733
- if (activeTaskState.status === exports.Status.SUCCESS) {
734
- this.updateActiveTaskIndex(activeTaskIndex + 1);
735
- this.next(params);
736
- return;
737
- }
738
- if ([exports.Status.FAILED, exports.Status.CANCELED, exports.Status.RUNNING].includes(activeTaskState.status)) {
739
- return;
740
- }
741
- if (activeTaskState.status === exports.Status.PENDING || activeTaskState.status === exports.Status.BLOCKED) {
742
- // Update task status to `running`
743
- this.updateTaskState(activeTask.id, {
744
- status: exports.Status.RUNNING
745
- });
746
- this.updateQueueStatus(exports.Status.RUNNING);
747
- // Try to execute task.
748
- var execute = this.actions[activeTask.action];
749
- execute({
750
- context: this.getContext(params),
751
- next: function next() {
752
- _this2.markCurrentTaskAsFinished(params);
753
- },
754
- retry: function retry() {
755
- _this2.resume(params);
756
- },
757
- failed: function failed() {
758
- _this2.updateTaskState(activeTask.id, {
759
- status: exports.Status.FAILED
760
- });
761
- _this2.check();
762
- },
763
- schedule: function schedule(action) {
764
- _this2.createTask(action);
765
- _this2.check();
766
- },
767
- getStorage: this.getStorage.bind(this),
768
- setStorage: this.setStorage.bind(this),
769
- block: function block(reason) {
770
- _this2.block({
771
- reason: reason
772
- });
773
- },
774
- unblock: function unblock() {
775
- _this2.unblock();
776
- }
777
- });
778
- }
779
- }
780
- /**
781
- * Change the `status` of active task and queue to BLOCKED, then trigger an event.
782
- */;
783
- _proto.block = function block(_ref) {
784
- var reason = _ref.reason,
785
- _ref$silent = _ref.silent,
786
- silent = _ref$silent === void 0 ? false : _ref$silent;
787
- var currentActiveTask = this.getActiveTask();
788
- if (!currentActiveTask) {
789
- throw new Error("Task isn't exist.");
790
- }
791
- this.updateTaskState(currentActiveTask.task.id, {
792
- status: exports.Status.BLOCKED,
793
- blockedFor: reason
794
- });
795
- this.updateQueueStatus(exports.Status.BLOCKED);
796
- if (!silent) {
797
- this.events.onBlock({
798
- action: currentActiveTask.task.action,
799
- id: currentActiveTask.task.id,
800
- reason: reason
801
- });
802
- }
803
- }
804
- /**
805
- * If the active task is `BLOCKED`, update the task status to `PENDING`, queue status to `RUNNING`
806
- * then trigger an event.
807
- */;
808
- _proto.unblock = function unblock() {
809
- var currentActiveTask = this.getActiveTask();
810
- if (!currentActiveTask || currentActiveTask.state.status !== exports.Status.BLOCKED) {
811
- throw new Error('Task is not blocked.');
812
- }
813
- this.updateTaskState(currentActiveTask.task.id, {
814
- status: exports.Status.PENDING
815
- });
816
- this.updateQueueStatus(exports.Status.RUNNING);
817
- this.events.onUnblock({
818
- id: currentActiveTask.task.id
819
- });
820
- }
821
- /**
822
- * If the active task is `BLOCKED` then execute the `action` for the task.
823
- *
824
- * It is useful for when we need to run a blocked task without changing the status of task at the first place.
825
- * For scenarios like we have some conditions in `action` and needs to run the `action` again
826
- * to check the conditions are met or not, if yes, so we can proceed the `action`.
827
- *
828
- */;
829
- _proto.forceRun = function forceRun(params) {
830
- var _this3 = this;
831
- var currentTask = this.getActiveTask();
832
- if (!currentTask || currentTask.state.status !== exports.Status.BLOCKED) {
833
- throw new Error('Task is not blocked.');
834
- }
835
- // Try to execute task.
836
- var execute = this.actions[currentTask.task.action];
837
- execute({
838
- context: this.getContext(params),
839
- next: function next() {
840
- /*
841
- NOTE:
842
- When running `forceRun`, the status of task can be `BLOCKED`
843
- So we need to change to `Running` first.
844
- */
845
- // Update task status to `running`
846
- _this3.updateTaskState(currentTask.task.id, {
847
- status: exports.Status.RUNNING
848
- });
849
- _this3.updateQueueStatus(exports.Status.RUNNING);
850
- _this3.markCurrentTaskAsFinished(params);
851
- },
852
- retry: function retry() {
853
- _this3.resume(params);
854
- },
855
- failed: function failed() {
856
- _this3.updateTaskState(currentTask.task.id, {
857
- status: exports.Status.FAILED
858
- });
859
- _this3.check();
860
- },
861
- schedule: function schedule(action) {
862
- _this3.createTask(action);
863
- _this3.check();
864
- },
865
- getStorage: this.getStorage.bind(this),
866
- setStorage: this.setStorage.bind(this),
867
- block: function block(reason) {
868
- _this3.block({
869
- reason: reason
870
- });
871
- },
872
- unblock: function unblock() {
873
- _this3.unblock();
874
- }
875
- });
876
- };
877
- _proto.markCurrentTaskAsFinished = function markCurrentTaskAsFinished(params) {
878
- this.check();
879
- var activeTaskIndex = this.state.activeTaskIndex;
880
- var activeTask = this.tasks[activeTaskIndex];
881
- if (!activeTask) return;
882
- var activeTaskState = this.state.tasks[activeTask.id];
883
- if (activeTaskState.status === exports.Status.RUNNING) {
884
- this.updateTaskState(activeTask.id, {
885
- status: exports.Status.SUCCESS
886
- });
887
- this.updateActiveTaskIndex(activeTaskIndex + 1);
888
- var updatedTaskEvent = {
889
- id: activeTask.id,
890
- task: this.get(activeTask.id),
891
- action: this.tasks.find(function (task) {
892
- return task.id === activeTask.id;
893
- }).action
894
- };
895
- this.events.onUpdate(updatedTaskEvent);
896
- this.next(params);
897
- }
898
- }
899
- /**
900
- * If the active task is `RUNNING`, change it to `PENING` the try to run the task by calling `next`.
901
- * If it's other than `RUNNING` we reset the queue state and run the queue from the beggining.
902
- *
903
- * @param params
904
- * @returns
905
- */;
906
- _proto.resume = function resume(params) {
907
- var activeTaskIndex = this.state.activeTaskIndex;
908
- var activeTask = this.tasks[activeTaskIndex];
909
- if (!activeTask) return;
910
- var activeTaskState = this.state.tasks[activeTask.id];
911
- if (activeTaskState.status === exports.Status.RUNNING) {
912
- this.updateTaskState(activeTask.id, {
913
- status: exports.Status.PENDING
914
- });
915
- this.next(params);
916
- } else {
917
- this.resetState();
918
- this.next(params);
919
- }
920
- }
921
- /**
922
- *
923
- * Cancel the queue by changing active task and queue status to `CANCELED`.
924
- *
925
- */;
926
- _proto.cancel = function cancel() {
927
- var currentActiveTask = this.getActiveTask();
928
- if (!currentActiveTask || [exports.Status.FAILED, exports.Status.CANCELED, exports.Status.SUCCESS].includes(currentActiveTask.state.status)) {
929
- return;
930
- }
931
- var task = currentActiveTask.task;
932
- // Update task status to `canceled`
933
- this.updateTaskState(task.id, {
934
- status: exports.Status.CANCELED
935
- });
936
- var updatedTaskEvent = {
937
- id: task.id,
938
- task: this.get(task.id),
939
- action: this.tasks.find(function (t) {
940
- return t.id === task.id;
941
- }).action
942
- };
943
- this.events.onUpdate(updatedTaskEvent);
944
- // Update queue status to `canceled`
945
- this.updateQueueStatus(exports.Status.CANCELED);
946
- }
947
- /**
948
- * Update queue status, and all the tasks inside queue to `PENDING`.
949
- */;
950
- _proto.resetState = function resetState() {
951
- var _this4 = this;
952
- this.state.activeTaskIndex = 0;
953
- this.state.status = exports.Status.PENDING;
954
- Object.keys(this.state.tasks).forEach(function (id) {
955
- _this4.state.tasks[id].status = exports.Status.PENDING;
956
- });
957
- };
958
- _proto.getStorage = function getStorage() {
959
- return this.storage;
960
- };
961
- _proto.setStorage = function setStorage(data) {
962
- this.storage = data;
963
- this.events.onStorageUpdate(data);
964
- return this.storage;
965
- };
966
- _proto.getContext = function getContext(params) {
967
- return _extends({}, params.context, {
968
- _queue: {
969
- id: this.id
970
- }
971
- });
972
- };
973
- return Queue;
974
- }();
975
-
976
- var Manager = /*#__PURE__*/function () {
977
- /**
978
- *
979
- * Making an instance, initilize events, setup a persistor and try to recover the last state of the manager.
980
- *
981
- * */
982
- function Manager(options) {
983
- var _this = this;
984
- this.queuesDefs = new Map();
985
- this.queues = new Map();
986
- this.isPaused = false;
987
- // The client won't get any update on pause, We are using a polling mode to fix this issue for now.
988
- this.syncInterval = null;
989
- var defaultEventHandlers = {
990
- onCreateQueue: function onCreateQueue() {
991
- // ...
992
- },
993
- onCreateTask: function onCreateTask() {
994
- // ...
995
- },
996
- onUpdateQueue: function onUpdateQueue() {
997
- // ...
998
- },
999
- onUpdateTask: function onUpdateTask() {
1000
- // ...
1001
- },
1002
- onStorageUpdate: function onStorageUpdate() {
1003
- // ...
1004
- },
1005
- onTaskBlock: function onTaskBlock() {
1006
- // ...
1007
- },
1008
- onPersistedDataLoaded: function onPersistedDataLoaded() {
1009
- // ..
1010
- }
1011
- };
1012
- if (options.events) {
1013
- this.events = _extends({}, defaultEventHandlers, options.events);
1014
- } else {
1015
- this.events = defaultEventHandlers;
1016
- }
1017
- options.queuesDefs.map(function (qDef) {
1018
- _this.queuesDefs.set(qDef.name, qDef);
1019
- });
1020
- this.context = options.context || {};
1021
- this.persistor = new Persistor();
1022
- this.sync();
1023
- if (options.isPaused) {
1024
- this.pause();
1025
- }
1026
- }
1027
- /**
1028
- *
1029
- * Reading persisted data from storage then brings into memory.
1030
- *
1031
- * Notes:
1032
- * - Reset the memory, so we can call this method whenever we want and not only on the initialize process.
1033
- * - All the events will be tirggered (like onCreateQueue, onCreateTask, onBlock, ....)
1034
- * - Try to `resume` if the status is `running`.
1035
- * - Trigger `onPersistedDataLoaded` event when queues recovered from storage.
1036
- *
1037
- */
1038
- var _proto = Manager.prototype;
1039
- _proto.sync =
1040
- /*#__PURE__*/
1041
- function () {
1042
- var _sync = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1043
- var _this2 = this;
1044
- var queues;
1045
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1046
- while (1) switch (_context.prev = _context.next) {
1047
- case 0:
1048
- _context.prev = 0;
1049
- _context.next = 3;
1050
- return this.persistor.getAll();
1051
- case 3:
1052
- queues = _context.sent;
1053
- // Reset queues, if anything is exist in memory.
1054
- this.queues = new Map();
1055
- // Brings them into memory
1056
- queues.forEach(function (q) {
1057
- var list = _this2.createQueue({
1058
- queue_id: q.id,
1059
- queue_name: q.name
1060
- });
1061
- _this2.add(q.id, {
1062
- list: list,
1063
- createdAt: q.createdAt,
1064
- name: q.name,
1065
- status: q.status,
1066
- actions: {
1067
- run: function run() {
1068
- list.next({
1069
- context: _this2.getContext()
1070
- });
1071
- },
1072
- cancel: function cancel() {
1073
- list.cancel();
1074
- },
1075
- setStorage: function setStorage() {
1076
- list.setStorage.apply(list, arguments);
1077
- },
1078
- getStorage: function getStorage() {
1079
- return list.getStorage();
1080
- }
1081
- }
1082
- });
1083
- list.initTasks({
1084
- state: q.state,
1085
- tasks: q.tasks,
1086
- storage: q.storage || {}
1087
- });
1088
- if (q.status === exports.Status.RUNNING && _this2.shouldExecute()) {
1089
- list.resume({
1090
- context: _this2.getContext()
1091
- });
1092
- }
1093
- });
1094
- _context.next = 11;
1095
- break;
1096
- case 8:
1097
- _context.prev = 8;
1098
- _context.t0 = _context["catch"](0);
1099
- console.log("IndexDB Error: " + _context.t0);
1100
- case 11:
1101
- // Trigger an event to let the subscribers we are done here.
1102
- this.events.onPersistedDataLoaded(this);
1103
- case 12:
1104
- case "end":
1105
- return _context.stop();
1106
- }
1107
- }, _callee, this, [[0, 8]]);
1108
- }));
1109
- function sync() {
1110
- return _sync.apply(this, arguments);
1111
- }
1112
- return sync;
1113
- }()
1114
- /**
1115
- *
1116
- * Making a new instance from `Queue` and adds Manager's event handlers to it.
1117
- *
1118
- * @returns An instance of `Queue` with wrapped event handlers from Manager.
1119
- *
1120
- */
1121
- ;
1122
- _proto.createQueue = function createQueue(_ref) {
1123
- var _this3 = this;
1124
- var queue_id = _ref.queue_id,
1125
- queue_name = _ref.queue_name;
1126
- var manager = this;
1127
- var def = this.queuesDefs.get(queue_name);
1128
- var list = new Queue({
1129
- id: queue_id,
1130
- events: {
1131
- onCreate: function onCreate(task) {
1132
- var _def$events;
1133
- _this3.events.onCreateTask(queue_id, task);
1134
- _this3.handleUpdate(queue_id);
1135
- if ((_def$events = def.events) != null && _def$events.onCreate) def.events.onCreate(task);
1136
- },
1137
- onUpdate: function onUpdate(task) {
1138
- var _def$events2;
1139
- _this3.events.onUpdateTask(queue_id, task);
1140
- _this3.handleUpdate(queue_id);
1141
- if ((_def$events2 = def.events) != null && _def$events2.onUpdate) def.events.onUpdate(task);
1142
- },
1143
- onUpdateListStatus: function onUpdateListStatus(status) {
1144
- var _def$events3;
1145
- _this3.queues.set(queue_id, _extends({}, _this3.get(queue_id), {
1146
- status: status
1147
- }));
1148
- _this3.events.onUpdateQueue(queue_id, _this3.get(queue_id));
1149
- _this3.handleUpdate(queue_id);
1150
- // After finishing a queue, try to run other queues.
1151
- _this3.execute();
1152
- if ((_def$events3 = def.events) != null && _def$events3.onUpdateListStatus) def.events.onUpdateListStatus(status);
1153
- },
1154
- onStorageUpdate: function onStorageUpdate(data) {
1155
- var _def$events4;
1156
- _this3.events.onStorageUpdate(queue_id, data);
1157
- if ((_def$events4 = def.events) != null && _def$events4.onStorageUpdate) def.events.onStorageUpdate(data);
1158
- _this3.handleUpdate(queue_id);
1159
- },
1160
- onBlock: function onBlock(event) {
1161
- // Update queue status
1162
- _this3.queues.set(queue_id, _extends({}, _this3.get(queue_id), {
1163
- status: exports.Status.BLOCKED
1164
- }));
1165
- // Trigger event
1166
- _this3.events.onTaskBlock(queue_id);
1167
- if (def.whenTaskBlocked) {
1168
- def.whenTaskBlocked(event, {
1169
- queue_id: queue_id,
1170
- queue: list,
1171
- context: _this3.getContext(),
1172
- getBlockedTasks: _this3.getBlockedTasks.bind(_this3),
1173
- forceExecute: _this3.forceExecute.bind(_this3),
1174
- retry: _this3.retry.bind(_this3),
1175
- manager: manager
1176
- });
1177
- }
1178
- // Sync
1179
- _this3.handleUpdate(queue_id);
1180
- },
1181
- onUnblock: function onUnblock() {
1182
- // Update queue status
1183
- _this3.queues.set(queue_id, _extends({}, _this3.get(queue_id), {
1184
- status: exports.Status.PENDING
1185
- }));
1186
- // Sync
1187
- _this3.handleUpdate(queue_id);
1188
- _this3.execute();
1189
- }
1190
- },
1191
- actions: def.actions
1192
- });
1193
- return list;
1194
- }
1195
- /**
1196
- * Go through all tasks (from all queues) and return a list of blocked tasks
1197
- *
1198
- * @returns a list of blocked tasks including enough information to get the queue and mutate the storage.
1199
- *
1200
- */;
1201
- _proto.getBlockedTasks = function getBlockedTasks() {
1202
- var queues = this.getAll();
1203
- var blockedTasks = [];
1204
- queues.forEach(function (q, queue_id) {
1205
- q.list.tasks.forEach(function (task) {
1206
- var state = q.list.state.tasks[task.id];
1207
- if (state.status === exports.Status.BLOCKED) {
1208
- blockedTasks.push({
1209
- task_id: task.id,
1210
- queue_id: queue_id,
1211
- action: task.action,
1212
- reason: state.blockedFor,
1213
- storage: {
1214
- get: function get() {
1215
- return q.list.getStorage();
1216
- },
1217
- set: function set(data) {
1218
- return q.list.setStorage(data);
1219
- }
1220
- }
1221
- });
1222
- }
1223
- });
1224
- });
1225
- return blockedTasks;
1226
- }
1227
- /**
1228
- *
1229
- * Add a queue to the manager to keep track of the queue and its state.
1230
- *
1231
- * @param id
1232
- * @param queue
1233
- * @returns
1234
- */;
1235
- _proto.add = function add(id, queue) {
1236
- this.queues.set(id, queue);
1237
- var createdQueue = this.get(id);
1238
- this.events.onCreateQueue(_extends({}, createdQueue, {
1239
- id: id
1240
- }));
1241
- return createdQueue;
1242
- }
1243
- // Create a new queue
1244
- /**
1245
- *
1246
- * Create a new queue by client.
1247
- *
1248
- * It will do the internal things to make a queue from definitions, and running using Manager.
1249
- *
1250
- * Notes:
1251
- * - After creating the queue, it will be run automatically.
1252
- *
1253
- * @returns an ID for queue so it can be used to get the created queue later by client.
1254
- *
1255
- */;
1256
- _proto.create =
1257
- /*#__PURE__*/
1258
- function () {
1259
- var _create = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name, storage, options) {
1260
- var _this4 = this;
1261
- var def, queue_id, createdAt, list, createdQueue;
1262
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1263
- while (1) switch (_context2.prev = _context2.next) {
1264
- case 0:
1265
- if (this.queuesDefs.has(name)) {
1266
- _context2.next = 2;
1267
- break;
1268
- }
1269
- throw new Error('You need to add a queue definition first.');
1270
- case 2:
1271
- _context2.prev = 2;
1272
- def = this.queuesDefs.get(name);
1273
- queue_id = (options == null ? void 0 : options.id) || uuid.v4();
1274
- createdAt = Date.now();
1275
- list = this.createQueue({
1276
- queue_id: queue_id,
1277
- queue_name: name
1278
- });
1279
- list.setStorage(storage);
1280
- createdQueue = this.add(queue_id, {
1281
- list: list,
1282
- createdAt: createdAt,
1283
- name: name,
1284
- status: exports.Status.PENDING,
1285
- actions: {
1286
- run: function run() {
1287
- list.next({
1288
- context: _this4.getContext()
1289
- });
1290
- },
1291
- cancel: function cancel() {
1292
- list.cancel();
1293
- },
1294
- setStorage: function setStorage() {
1295
- list.setStorage.apply(list, arguments);
1296
- },
1297
- getStorage: function getStorage() {
1298
- return list.getStorage();
1299
- }
1300
- }
1301
- }); // Persist initial queue
1302
- // Note: we need to first insert the queue, and then it can be updated by internal events.
1303
- _context2.next = 11;
1304
- return this.persistor.insertQueue({
1305
- id: queue_id,
1306
- createdAt: createdAt,
1307
- name: createdQueue.name,
1308
- status: createdQueue.status,
1309
- tasks: list.tasks,
1310
- state: list.state,
1311
- storage: list.getStorage()
1312
- });
1313
- case 11:
1314
- // adding initial tasks
1315
- def.run.forEach(function (action) {
1316
- list.createTask(action);
1317
- });
1318
- // After creating a new queue, try to run.
1319
- this.execute();
1320
- return _context2.abrupt("return", queue_id);
1321
- case 16:
1322
- _context2.prev = 16;
1323
- _context2.t0 = _context2["catch"](2);
1324
- throw new Error(_context2.t0 == null ? void 0 : _context2.t0.message);
1325
- case 19:
1326
- case "end":
1327
- return _context2.stop();
1328
- }
1329
- }, _callee2, this, [[2, 16]]);
1330
- }));
1331
- function create(_x, _x2, _x3) {
1332
- return _create.apply(this, arguments);
1333
- }
1334
- return create;
1335
- }()
1336
- /**
1337
- * Get a queue by its ID.
1338
- *
1339
- * @returns An object includes queue and its state in `Manager`.
1340
- */
1341
- ;
1342
- _proto.get = function get(queue_id) {
1343
- return this.queues.get(queue_id);
1344
- }
1345
- /**
1346
- * Get all queues from `Manager`
1347
- *
1348
- * @returns a list of queues includes all the queues and their states.
1349
- */;
1350
- _proto.getAll = function getAll() {
1351
- return this.queues;
1352
- }
1353
- /**
1354
- *
1355
- * Ask from manager to run pending queues.
1356
- *
1357
- * It only try to run queues with `PENDING` status and ignore all the other statuses.
1358
- *
1359
- */;
1360
- _proto.execute = function execute() {
1361
- if (!this.shouldExecute()) return;
1362
- for (var _i = 0, _Array$from = Array.from(this.queues); _i < _Array$from.length; _i++) {
1363
- var _Array$from$_i = _Array$from[_i],
1364
- q = _Array$from$_i[1];
1365
- if (q.status === exports.Status.PENDING) {
1366
- q.actions.run();
1367
- }
1368
- }
1369
- }
1370
- /**
1371
- *
1372
- * Try to find queues with `RUNNING` status to run them again.
1373
- *
1374
- * It's useful for recovering the queue at some certain points
1375
- * like running a currepted task (reloaded when it was running) or needs manual trigger from UI.
1376
- *
1377
- * @returns
1378
- */;
1379
- _proto.resume = function resume() {
1380
- if (!this.shouldExecute()) return;
1381
- for (var _i2 = 0, _Array$from2 = Array.from(this.queues); _i2 < _Array$from2.length; _i2++) {
1382
- var _Array$from2$_i = _Array$from2[_i2],
1383
- q = _Array$from2$_i[1];
1384
- if (q.status === exports.Status.RUNNING) {
1385
- q.list.resume({
1386
- context: this.getContext()
1387
- });
1388
- return;
1389
- }
1390
- }
1391
- // If there is no running queue, try to run a new queue.
1392
- this.execute();
1393
- }
1394
- /**
1395
- *
1396
- * Run all `BLOCKED` queues once again.
1397
- *
1398
- * If a queue has `BLOCKED` status and the last task is `BLOCKED` as well,
1399
- * The task will be run one more time.
1400
- *
1401
- * Useful for scenarios like we are blocking the queue under some conditions in task,
1402
- * We can use this method to ask the queue to run the blocked task one more time and
1403
- * maybe this time condtions are met and the queue can be proceed.
1404
- *
1405
- * @returns
1406
- */;
1407
- _proto.retry = function retry() {
1408
- if (!this.shouldExecute()) return;
1409
- for (var _i3 = 0, _Array$from3 = Array.from(this.queues); _i3 < _Array$from3.length; _i3++) {
1410
- var _Array$from3$_i = _Array$from3[_i3],
1411
- q = _Array$from3$_i[1];
1412
- if (q.status === exports.Status.BLOCKED) {
1413
- q.list.checkBlock();
1414
- }
1415
- }
1416
- // If there is no running queue, try to run a new queue.
1417
- this.execute();
1418
- }
1419
- /**
1420
- *
1421
- * Run a blocked task on a specific queue with the ability to pass more data.
1422
- *
1423
- * Useful when we have a custom logic for running queue and needs to pass some specific data
1424
- * to the task and try to run it manually with the provided data.
1425
- *
1426
- */;
1427
- _proto.forceExecute = function forceExecute(queue_id, data) {
1428
- var queue = this.get(queue_id);
1429
- var context = this.getContext();
1430
- if (data) {
1431
- context = _extends({}, context, data);
1432
- }
1433
- queue == null ? void 0 : queue.list.forceRun({
1434
- context: context
1435
- });
1436
- }
1437
- /**
1438
- *
1439
- * Sync in-memory state (of `Manager`) with storage (persist).
1440
- *
1441
- * Usually we call this method after a change detected in the state of manager.
1442
- *
1443
- */;
1444
- _proto.handleUpdate = function handleUpdate(queue_id) {
1445
- var queue = this.get(queue_id);
1446
- if (queue) {
1447
- var status = queue.status;
1448
- var state = queue.list.state;
1449
- var tasks = queue.list.tasks;
1450
- this.persistor.updateQueue(queue_id, {
1451
- status: status,
1452
- state: state,
1453
- tasks: tasks,
1454
- storage: queue.list.getStorage()
1455
- });
1456
- }
1457
- }
1458
- /**
1459
- * Active readonly mode for manager, it means it doesn't run anythin,
1460
- * And only can be used to read the data.
1461
- */;
1462
- _proto.pause = function pause() {
1463
- var _this5 = this;
1464
- if (this.isPaused) return;
1465
- this.isPaused = true;
1466
- this.syncInterval = setInterval(function () {
1467
- _this5.sync();
1468
- }, SYNC_POLLING_INTERVAL);
1469
- }
1470
- /**
1471
- * Activate normal mode which means it will be able to run the queuese as well.
1472
- */;
1473
- _proto.run = function run() {
1474
- // If call this method multiple times, it should be run for once.
1475
- if (this.isPaused) {
1476
- this.isPaused = false;
1477
- if (!!this.syncInterval) {
1478
- clearInterval(this.syncInterval);
1479
- this.syncInterval = null;
1480
- }
1481
- this.sync();
1482
- }
1483
- };
1484
- _proto.getContext = function getContext() {
1485
- var _this$context;
1486
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1487
- //@ts-ignore
1488
- return ((_this$context = this.context) == null ? void 0 : _this$context.current) || {};
1489
- };
1490
- _proto.shouldExecute = function shouldExecute() {
1491
- return !this.isPaused;
1492
- };
1493
- return Manager;
1494
- }();
1495
-
1496
- exports.DB_NAME = DB_NAME;
1497
- exports.Manager = Manager;
1498
- exports.Persistor = Persistor;
1499
- exports.SYNC_POLLING_INTERVAL = SYNC_POLLING_INTERVAL;
1500
- //# sourceMappingURL=queue-manager-core.cjs.development.js.map