-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
440 lines (385 loc) · 14 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import { MongoAdapter } from './adapters/mongo.js';
import { RedisAdapter } from './adapters/redis.js';
const prefixRegex = /set(Immediate|Timeout|Interval)$/;
const errors = {
setInterval: {
func: '[josk] [setInterval] the first argument must be a function!',
delay: '[josk] [setInterval] delay must be positive Number!',
uid: '[josk] [setInterval] [uid - task id must be specified (3rd argument)]'
},
setTimeout: {
func: '[josk] [setTimeout] the first argument must be a function!',
delay: '[josk] [setTimeout] delay must be positive Number!',
uid: '[josk] [setTimeout] [uid - task id must be specified (3rd argument)]'
},
setImmediate: {
func: '[josk] [setImmediate] the first argument must be a function!',
uid: '[josk] [setImmediate] [uid - task id must be specified (2nd argument)]'
},
};
/** Class representing a JoSk task runner (cron). */
class JoSk {
/**
* Create a JoSk instance
* @param {object} opts - configuration object
* @param {boolean} [opts.debug] - Enable debug logging
* @param {function} [opts.onError] - Informational hook, called instead of throwing exceptions, see readme for more details
* @param {boolean} [opts.autoClear] - Remove obsolete tasks (any tasks which are not found in the instance memory during runtime, but exists in the database)
* @param {number} [opts.zombieTime] - Time in milliseconds, after this period of time - task will be interpreted as "zombie". This parameter allows to rescue task from "zombie mode" in case when: `ready()` wasn't called, exception during runtime was thrown, or caused by bad logic
* @param {function} [opts.onExecuted] - Informational hook, called when task is finished, see readme for more details
* @param {number} [opts.minRevolvingDelay] - Minimum revolving delay — the minimum delay between tasks executions in milliseconds
* @param {number} [opts.maxRevolvingDelay] - Maximum revolving delay — the maximum delay between tasks executions in milliseconds
*/
constructor(opts = {}) {
this.debug = opts.debug || false;
this.onError = opts.onError || false;
this.autoClear = opts.autoClear || false;
this.zombieTime = opts.zombieTime || 900000;
this.onExecuted = opts.onExecuted || false;
this.isDestroyed = false;
this.minRevolvingDelay = opts.minRevolvingDelay || 128;
this.maxRevolvingDelay = opts.maxRevolvingDelay || 768;
this.nextRevolutionTimeout = null;
if (!opts.adapter || typeof opts.adapter !== 'object') {
throw new Error('{adapter} option is required for JoSk', {
description: 'JoSk requires MongoAdapter, RedisAdapter, or CustomAdapter to connect to an intermediate database'
});
}
this.tasks = {};
this._debug = (...args) => {
this.debug === true && console.info.call(console, '[DEBUG] [josk]', ...args);
};
this.adapter = opts.adapter;
this.adapter.joskInstance = this;
const adapterMethods = ['acquireLock', 'releaseLock', 'remove', 'add', 'update', 'iterate', 'ping'];
for (let i = adapterMethods.length - 1; i >= 0; i--) {
if (typeof this.adapter[adapterMethods[i]] !== 'function') {
throw new Error(`{adapter} instance is missing {${adapterMethods[i]}} method that is required!`);
}
}
this.__tick();
}
/**
* @async
* @memberOf JoSk
* @name ping
* @description Check package readiness and connection to Storage
* @returns {Promise<object>}
* @throws {mix}
*/
async ping() {
return await this.adapter.ping();
}
/**
* @async
* @memberOf JoSk
* Create recurring task (loop)
* @name setInterval
* @param {function} func - Function (task) to execute
* @param {number} delay - Delay between task execution in milliseconds
* @param {string} uid - Unique function (task) identification as a string
* @returns {Promise<string>} - Timer ID
*/
async setInterval(func, delay, uid) {
if (this.__checkState()) {
return '';
}
if (typeof func !== 'function') {
throw new Error(errors.setInterval.func);
}
if (delay < 0) {
throw new Error(errors.setInterval.delay);
}
if (typeof uid !== 'string') {
throw new Error(errors.setInterval.uid);
}
const timerId = `${uid}setInterval`;
this.tasks[timerId] = func;
await this.__add(timerId, true, delay);
return timerId;
}
/**
* @async
* @memberOf JoSk
* Create delayed task
* @name setTimeout
* @param {function} func - Function (task) to execute
* @param {number} delay - Delay before task execution in milliseconds
* @param {string} uid - Unique function (task) identification as a string
* @returns {Promise<string>} - Timer ID
*/
async setTimeout(func, delay, uid) {
if (this.__checkState()) {
return '';
}
if (typeof func !== 'function') {
throw new Error(errors.setTimeout.func);
}
if (delay < 0) {
throw new Error(errors.setTimeout.delay);
}
if (typeof uid !== 'string') {
throw new Error(errors.setTimeout.uid);
}
const timerId = `${uid}setTimeout`;
this.tasks[timerId] = func;
await this.__add(timerId, false, delay);
return timerId;
}
/**
* @async
* @memberOf JoSk
* Create task, which would get executed immediately and only once across multi-server setup
* @name setImmediate
* @param {function} func - Function (task) to execute
* @param {string} uid - Unique function (task) identification as a string
* @returns {Promise<string>} - Timer ID
*/
async setImmediate(func, uid) {
if (this.__checkState()) {
return '';
}
if (typeof func !== 'function') {
throw new Error(errors.setImmediate.func);
}
if (typeof uid !== 'string') {
throw new Error(errors.setImmediate.uid);
}
const timerId = `${uid}setImmediate`;
this.tasks[timerId] = func;
await this.__add(timerId, false, 0);
return timerId;
}
/**
* @async
* @memberOf JoSk
* Cancel (abort) current interval timer.
* Must be called in a separate event loop from `.setInterval()`
* @name clearInterval
* @param {string|Promise<string>} timerId - Unique function (task) identification as a string, returned from `.setInterval()`
* @param {function} [callback] - optional callback
* @returns {Promise<boolean>} - `true` if task cleared, `false` if task doesn't exist
*/
async clearInterval(timerId) {
if (typeof timerId === 'object' && timerId instanceof Promise) {
return await this.__remove(await timerId);
}
return await this.__remove(timerId);
}
/**
* @async
* @memberOf JoSk
* Cancel (abort) current timeout timer.
* Must be called in a separate event loop from `.setTimeout()`
* @name clearTimeout
* @param {string|Promise<string>} timerId - Unique function (task) identification as a string, returned from `.setTimeout()`
* @param {function} [callback] - optional callback
* @returns {Promise<boolean>} - `true` if task cleared, `false` if task doesn't exist
*/
async clearTimeout(timerId) {
if (typeof timerId === 'object' && timerId instanceof Promise) {
return await this.__remove(await timerId);
}
return await this.__remove(timerId);
}
/**
* @memberOf JoSk
* Destroy JoSk instance and stop all tasks
* @name destroy
* @returns {boolean} - `true` if instance successfully destroyed, `false` if instance already destroyed
*/
destroy() {
if (!this.isDestroyed) {
this.isDestroyed = true;
if (this.nextRevolutionTimeout) {
clearTimeout(this.nextRevolutionTimeout);
this.nextRevolutionTimeout = null;
}
return true;
}
return false;
}
__checkState() {
if (this.isDestroyed) {
if (this.onError) {
const reason = 'JoSk instance destroyed';
this.onError(reason, {
description: 'invoking methods of destroyed JoSk instance',
error: new Error(reason),
uid: null
});
} else {
this._debug('[__checkState] [warn] invoking methods of destroyed JoSk instance, call cause no action');
}
return true;
}
return false;
}
async __remove(timerId) {
if (typeof timerId !== 'string') {
return false;
}
const isRemoved = await this.adapter.remove(timerId);
if (isRemoved && this.tasks?.[timerId]) {
delete this.tasks[timerId];
}
return isRemoved;
}
async __add(uid, isInterval, delay) {
if (this.isDestroyed) {
return;
}
await this.adapter.add(uid, isInterval, delay);
}
async __execute(task) {
if (this.isDestroyed || task.isDeleted === true) {
return;
}
if (!task || typeof task !== 'object' || typeof task.uid !== 'string') {
if (this.onError) {
this.onError('JoSk#__execute received malformed task', {
description: 'Something went wrong with one of your tasks - malformed or undefined',
error: null,
task: task,
uid: task.uid,
});
} else {
this._debug('[__execute] received malformed task', task);
}
return;
}
let executionsQty = 0;
if (this.tasks && typeof this.tasks[task.uid] === 'function') {
if (this.tasks[task.uid].isMissing === true) {
return;
}
const ready = async (readyArg1) => {
executionsQty++;
if (executionsQty >= 2) {
const error = new Error(`[josk] [${task.uid}] Resolution method is overspecified. Specify a callback *or* return a Promise. Task resolution was called more than once!`);
if (typeof readyArg1 === 'function') {
readyArg1(error, false);
return false;
}
throw error;
}
const date = new Date();
const timestamp = +date;
if (typeof readyArg1 === 'function') {
readyArg1(void 0, true);
}
if (task.isInterval === true) {
if (typeof readyArg1 === 'object' && readyArg1 instanceof Date && +readyArg1 >= timestamp) {
await this.adapter.update(task, readyArg1);
} else if (typeof readyArg1 === 'number' && readyArg1 >= timestamp) {
await this.adapter.update(task, new Date(readyArg1));
} else {
await this.adapter.update(task, new Date(timestamp + task.delay));
}
}
if (this.onExecuted) {
this.onExecuted(task.uid.replace(prefixRegex, ''), {
uid: task.uid,
date: date,
delay: task.delay,
timestamp: timestamp
});
}
return true;
};
let hasError;
let returnedPromise;
try {
if (task.isInterval === false) {
const originalTask = this.tasks[task.uid];
let isRemoved = false;
try {
isRemoved = await this.__remove(task.uid);
} catch (removeError) {
this._debug(`[${task.uid}] [__execute] [__remove] has thrown an exception; Check connection with StorageAdapter; removeError:`, removeError);
}
if (isRemoved === true) {
returnedPromise = originalTask(ready);
}
} else {
returnedPromise = this.tasks[task.uid](ready);
}
if (returnedPromise && returnedPromise instanceof Promise) {
await returnedPromise;
} else {
return;
}
} catch (taskExecError) {
hasError = true;
this.__errorHandler(taskExecError, 'Exception during task execution', 'An exception was thrown during task execution', task.uid);
}
if ((returnedPromise && returnedPromise instanceof Promise) || (executionsQty === 0 && hasError)) {
try {
await ready();
} catch (readyErr) {
this._debug(`[${task.uid}] [__execute] [ready] has thrown an exception; readyErr:`, readyErr);
}
}
return;
}
await this.adapter.update(task, new Date(Date.now() + this.zombieTime));
this.tasks[task.uid] = function () { };
this.tasks[task.uid].isMissing = true;
if (this.autoClear) {
try {
await this.__remove(task.uid);
this._debug(`[FYI] [${task.uid}] task was auto-cleared`);
} catch (removeError) {
this._debug(`[${task.uid}] [__execute] [this.autoClear] [__remove] has thrown an exception; removeError:`, removeError);
}
} else if (this.onError) {
this.onError('One of your tasks is missing', {
description: `Something went wrong with one of your tasks - is missing.
Try to use different instances.
It's safe to ignore this message.
If this task is obsolete - simply remove it with \`JoSk#clearTimeout('${task.uid}')\`,
or enable autoClear with \`new JoSk({autoClear: true})\``,
error: null,
uid: task.uid
});
} else {
this._debug(`[__execute] [${task.uid}] Something went wrong with one of your tasks is missing.
Try to use different instances.
It's safe to ignore this message.
If this task is obsolete - simply remove it with \`JoSk#clearTimeout(\'${task.uid}\')\`,
or enable autoClear with \`new JoSk({autoClear: true})\``);
}
}
async __iterate() {
if (this.isDestroyed) {
return;
}
const nextExecuteAt = new Date(Date.now() + this.zombieTime);
try {
const isAcquired = await this.adapter.acquireLock();
if (isAcquired) {
await this.adapter.iterate(nextExecuteAt);
await this.adapter.releaseLock();
}
this.__tick();
} catch (runError) {
this.__errorHandler(runError, '[__iterate] runError:', 'adapter.iterate has returned an error', null);
}
}
__tick() {
if (this.isDestroyed) {
return;
}
this.nextRevolutionTimeout = setTimeout(this.__iterate.bind(this), Math.round((Math.random() * this.maxRevolvingDelay) + this.minRevolvingDelay));
}
__errorHandler(error, title, description, uid) {
if (error) {
if (this.onError) {
this.onError(title, { description, error, uid });
} else {
console.error(title, { description, error, uid });
}
}
}
}
export { JoSk, MongoAdapter, RedisAdapter };