-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
805 lines (723 loc) · 21.1 KB
/
index.ts
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
import { EventEmitter, CustomEvent } from '@libp2p/interface/events';
import { simpleUid } from '@windingtree/contracts';
import { Storage } from '@windingtree/sdk-storage';
import { backoffWithJitter } from '@windingtree/sdk-utils';
import { createLogger } from '@windingtree/sdk-logger';
import { serialize } from 'superjson';
const logger = createLogger('Queue');
/**
* Enum to represent the different states a job can be in.
*/
export enum JobStatus {
Pending,
Scheduled,
Started,
Done,
Cancelled,
Failed,
Expired,
}
/**
* Type for the data that a job can operate on.
*/
export type JobData = unknown;
/**
* Interface for the function that a job runs.
*/
export type JobHandler<JobData = unknown, HandlerOptions = unknown> = (
data?: JobData,
options?: HandlerOptions,
) => Promise<boolean>;
export interface JobHistoryInterface {
/** A history of all status changes for the job. */
statusChanges?: { timestamp: number; status: JobStatus }[];
/** A history of all errors for the job. */
errors?: string[];
}
/**
* A class to manage the history of a job. This includes status changes and errors.
*
* @export
* @class JobHistory
*/
export class JobHistory implements JobHistoryInterface {
/** A history of all status changes for the job. */
statusChanges: { timestamp: number; status: JobStatus }[];
/** A history of all errors for the job. */
errors: string[];
/**
* Creates an instance of JobHistory.
* @memberof JobHistory
*/
constructor(config: JobHistoryInterface) {
this.statusChanges = config.statusChanges ?? [];
this.errors = config.errors ?? [];
}
static getStatus(source: JobHistory | JobHistoryInterface) {
return source.statusChanges && source.statusChanges.length > 0
? source.statusChanges[source.statusChanges.length - 1].status
: JobStatus.Pending;
}
/**
* Returns class as object
*
* @returns
* @memberof JobHistory
*/
toJSON(): JobHistoryInterface {
return {
statusChanges: this.statusChanges,
errors: this.errors,
};
}
}
/**
* Configuration object for a job.
*/
export interface JobConfig<T extends JobData = JobData> {
/** The name of the job handler to use. */
handlerName: string;
/** The data for the job to operate on. */
data?: T;
/** The number of seconds after which the job should expire. */
expire?: number;
/** Whether or not the job should be re-run after completion. */
isRecurrent?: boolean;
/** If the job is recurrent, the interval in seconds between runs. */
recurrenceInterval?: number;
/** If the job is recurrent, the maximum number of times the job should be re-run. */
maxRecurrences?: number;
/** The maximum number of times the job should be retried if it fails. */
maxRetries?: number;
/** Initial retries value */
retries?: number;
/** Retries delay */
retriesDelay?: number;
/** Scheduled time */
scheduledTime?: number;
/** The history of the job */
history?: JobHistoryInterface;
}
/**
* A class to represent a job. A job has a handler, some data to operate on, and a status.
*
* @export
* @class Job
* @template T
*/
export class Job<T extends JobData = JobData> {
/** The unique identifier of the job */
id: string;
/** The name of the handler to be used for this job */
handlerName: string;
/** The data to be processed by the job */
data?: T;
/** The time in seconds after which the job should be marked as expired */
expire?: number;
/** Whether the job should be recurrent or not */
isRecurrent: boolean;
/** If the job is recurrent, the interval in seconds between job executions */
recurrenceInterval: number;
/** If the job is recurrent, the maximum number of recurrences */
maxRecurrences: number;
/** The maximum number of times the job should be retried if it fails */
maxRetries: number;
/** The number of times the job has been retried */
retries: number;
/** The period of time between retries */
retriesDelay: number;
/** Scheduled time */
scheduledTime?: number;
/** The history of the job */
history: JobHistory;
/**
* Creates an instance of Job.
* @param {JobConfig<T>} config
* @memberof Job
*/
constructor(config: JobConfig<T>) {
this.id = simpleUid();
this.handlerName = config.handlerName;
this.data = config.data;
this.expire = config.expire;
this.isRecurrent = config.isRecurrent ?? false;
this.recurrenceInterval = config.recurrenceInterval ?? 0;
this.maxRecurrences = config.maxRecurrences ?? 0;
this.maxRetries = config.maxRetries ?? 0;
this.retries = config.retries ?? 0;
this.retriesDelay = config.retriesDelay ?? 0;
if (this.isRecurrent && config.scheduledTime) {
throw new Error('Job cannot be recurrent and scheduled at the same time');
}
this.scheduledTime = config.scheduledTime;
this.history = new JobHistory(config.history ?? {});
}
/**
* Setter for `status` property. Adds a new status change to the job history.
*
* @memberof Job
*/
set status(newStatus: JobStatus) {
this.history.statusChanges.push({
timestamp: Date.now(),
status: newStatus,
});
logger.trace(`Job #${this.id} status changed to: ${this.status}`);
}
/**
* Getter for `status` property. Returns the most recent status of the job.
*
* @memberof Job
*/
get status() {
return JobHistory.getStatus(this.history);
}
/**
* Getter for `expired` property. Returns whether the job has expired.
*
* @readonly
* @memberof Job
*/
get expired() {
const isExpired =
this.status === JobStatus.Expired ||
(this.expire && this.expire * 1000 < Date.now());
if (isExpired) {
this.status = JobStatus.Expired;
}
return isExpired;
}
/**
* Getter for `executable` property. Returns whether the job can be executed.
*
* @readonly
* @memberof Job
*/
get executable() {
return (
!this.expired &&
[JobStatus.Pending, JobStatus.Scheduled].includes(this.status) &&
((!this.isRecurrent &&
(this.maxRetries === 0 ||
(this.maxRetries > 0 && this.retries < this.maxRetries))) ||
(this.isRecurrent &&
(this.maxRecurrences === 0 ||
(this.maxRecurrences > 0 && this.retries < this.maxRecurrences))))
);
}
/**
* Returns Job as config object
*
* @returns {JobConfig<T>}
* @memberof Job
*/
toJSON(): JobConfig<T> {
return {
handlerName: this.handlerName,
data: this.data,
expire: this.expire,
isRecurrent: this.isRecurrent,
recurrenceInterval: this.recurrenceInterval,
maxRecurrences: this.maxRecurrences,
maxRetries: this.maxRetries,
retries: this.retries,
retriesDelay: this.retriesDelay,
history: this.history.toJSON(),
};
}
/**
* Executes the job using the provided handler.
*
* @param {JobHandler<T>} handler
* @returns
* @memberof Job
*/
async execute(handler: JobHandler<T>) {
logger.trace(`Job #${this.id} executed`);
return Promise.resolve(handler(this.data));
}
}
/**
* A class to manage job handlers. Allows for registering and retrieving handlers by name.
*
* @export
* @class JobHandlerRegistry
*/
export class JobHandlerRegistry {
/** Map to store the handlers */
handlers: Map<string, JobHandler>;
/**
* Creates an instance of JobHandlerRegistry.
* @memberof JobHandlerRegistry
*/
constructor() {
this.handlers = new Map();
}
/**
* Registers a handler for a jobs
*
* @param {string} name
* @param {JobHandler} handler
* @memberof JobHandlerRegistry
*/
register(name: string, handler: JobHandler) {
this.handlers.set(name, handler);
}
/**
* Returns a handler by Id
*
* @param {string} name
* @returns {JobHandler}
* @memberof JobHandlerRegistry
*/
getHandler(name: string): JobHandler {
const handler = this.handlers.get(name);
if (!handler) {
throw new Error(`Unable to get job handler: ${name}`);
}
return handler;
}
}
/**
* Queue class constructor options interface.
*
* @export
* @interface QueueOptions
*/
export interface QueueOptions {
/** Queue storage object */
storage?: Storage;
/** Name of the key that is used for storing jobs Ids */
idsKeyName?: string;
/** The maximum number of jobs that can be concurrently active. */
concurrencyLimit?: number;
}
/**
* Queue events interface
*/
export interface QueueEvents<T extends JobData = JobData> {
/**
* @example
*
* ```js
* queue.addEventListener('status', ({ detail }) => {
* // job status changed
* })
* ```
*/
status: CustomEvent<Job<T>>;
/**
* @example
*
* ```js
* queue.addEventListener('stop', () => {
* // queue stopped
* })
* ```
*/
stop: CustomEvent<void>;
}
/**
* The Queue class is responsible for managing and executing jobs.
* It inherits from EventEmitter to allow event-based behavior.
*
* @export
* @class Queue
* @extends {EventEmitter<QueueEvents>}
*/
export class Queue extends EventEmitter<QueueEvents> {
/** Queue storage object */
storage?: Storage;
/** Name of the key that is used for storing jobs Ids */
idsKeyName: string;
/** The maximum number of jobs that can be concurrently active. */
concurrencyLimit: number;
/** The list of all jobs in the queue. */
jobs: Job[];
/** The registry of job handlers, where handlers are stored by their names. */
handlers: JobHandlerRegistry;
/**
* Creates an instance of Queue.
* It initializes the jobs list, the handler registry, and sets the concurrency limit.
* @param {QueueOptions} { concurrencyLimit }
* @memberof Queue
*/
constructor({ storage, idsKeyName, concurrencyLimit }: QueueOptions) {
super();
this.storage = storage;
this.idsKeyName = idsKeyName ?? 'jobsIds';
this.concurrencyLimit = concurrencyLimit ?? 5;
this.jobs = [];
this.handlers = new JobHandlerRegistry();
void this.storageUp();
}
/**
* Restores saved jobs from the storage
*
* @protected
* @returns
* @memberof Queue
*/
protected async storageUp() {
try {
// Ignore storage features if not set up
if (!this.storage) {
return;
}
const jobsIds = await this.storage.get<string[]>(this.idsKeyName);
if (jobsIds) {
for (const id of jobsIds) {
try {
const jobConfig = await this.storage.get<JobConfig>(id);
if (!jobConfig) {
throw new Error(`Unable to get job #${id} from storage`);
}
// Only Pending jobs must be restored
if (
jobConfig.history &&
[JobStatus.Pending, JobStatus.Scheduled].includes(
JobHistory.getStatus(jobConfig.history),
)
) {
this.add(jobConfig);
}
} catch (error) {
logger.error(error);
}
}
} else {
logger.trace('Jobs Ids not found in the storage');
}
} catch (error) {
logger.error('storageUp error:', error);
}
}
/**
* Stores all pending jobs to the storage
*
* @protected
* @returns
* @memberof Queue
*/
protected async storageDown() {
try {
// Ignore storage features if not set up
if (!this.storage) {
return;
}
const pendingJobs = this.jobs.filter((job) => job.executable);
const { ids, configs } = pendingJobs.reduce<{
ids: string[];
configs: JobConfig[];
}>(
(a, v) => {
a.ids.push(v.id);
a.configs.push(v.toJSON());
return a;
},
{
ids: [],
configs: [],
},
);
const jobsIds = new Set(
(await this.storage.get<string[]>(this.idsKeyName)) ?? [],
);
for (let i = 0; i < ids.length; i++) {
try {
jobsIds.add(ids[i]);
await this.storage.set(ids[i], configs[i]);
} catch (error) {
logger.error(`Job #${ids[i]} save error:`, error);
}
}
await this.storage.set(this.idsKeyName, Array.from(jobsIds));
} catch (error) {
logger.error('storageDown error:', error);
}
}
/**
* Updated saved job on storage
*
* @protected
* @param {string} id
* @param {Job} job
* @returns
* @memberof Queue
*/
protected async storageUpdate(id: string, job: Job) {
try {
// Ignore storage features if not set up
if (!this.storage) {
return;
}
const jobsIds = new Set(
(await this.storage.get<string[]>(this.idsKeyName)) ?? [],
);
jobsIds.add(id);
await this.storage.set(id, job.toJSON());
await this.storage.set(this.idsKeyName, Array.from(jobsIds));
} catch (error) {
logger.error('storageDown error:', error);
}
}
/**
* Changes the job status and emits `status` event
*
* @private
* @param {Job} job
* @param {JobStatus} newStatus
* @memberof Queue
*/
private changeJobStatus(job: Job, newStatus: JobStatus) {
job.status = newStatus;
this.dispatchEvent(
new CustomEvent<Job>('status', {
detail: job,
}),
);
void this.storageUpdate(job.id, job);
}
/**
* Executes Job
* @param {Job} job Job to execute
* @returns {Promise<void>}
*/
private async executeJob(job: Job): Promise<void> {
try {
if (!job.executable) {
return;
}
this.changeJobStatus(job, JobStatus.Started);
const handler = this.handlers.getHandler(job.handlerName);
const result = await job.execute(handler);
logger.trace(`Job #${job.id} execution result: ${String(result)}`);
if (result && job.isRecurrent) {
// If the job is recurrent and the handler returned true, reschedule the job
if (!job.expired) {
logger.trace(`Job #${job.id} is done but new one is scheduled`);
this.changeJobStatus(job, JobStatus.Done);
setTimeout(() => {
this.add({
handlerName: job.handlerName,
data: job.data,
expire: job.expire,
isRecurrent: job.isRecurrent,
recurrenceInterval: job.recurrenceInterval,
maxRecurrences: job.maxRecurrences,
maxRetries: job.maxRetries,
retries: job.retries + 1,
});
}, job.recurrenceInterval);
} else {
logger.trace(`Job #${job.id} is expired`);
this.changeJobStatus(job, JobStatus.Expired);
}
} else {
logger.trace(`Job #${job.id} is done`);
this.changeJobStatus(job, JobStatus.Done);
}
} catch (error) {
logger.error(`Job #${job.id} is errored`, error);
job.history.errors.push(String(error));
if (job.maxRetries > 0 && job.retries < job.maxRetries) {
// If the job hasn't reached the maximum number of retries, retry it
job.retries++;
if (job.retriesDelay > 0) {
logger.trace(`Job #${job.id} filed but scheduled for restart`);
this.changeJobStatus(job, JobStatus.Failed);
setTimeout(
() => {
this.add({
handlerName: job.handlerName,
data: job.data,
expire: job.expire,
maxRetries: job.maxRetries,
retries: job.retries + 1,
});
},
backoffWithJitter(
job.retriesDelay,
job.retries,
job.retriesDelay * 10,
),
);
} else {
logger.trace(`Job #${job.id} failed and immediately restarted`);
this.changeJobStatus(job, JobStatus.Pending);
}
} else {
logger.trace(`Job #${job.id} filed`);
this.changeJobStatus(job, JobStatus.Failed);
}
}
}
/**
* Starts processing jobs in the queue.
* It finds executable jobs and runs them concurrently up to the concurrency limit.
* If a job fails and it hasn't reached the maximum number of retries, it is set as pending again.
* If a job is recurrent (i.e., it is supposed to run repeatedly after a certain interval) and
* the job handler returns true (indicating successful completion of the job), the job is rescheduled.
*
* @returns
* @memberof Queue
*/
private async start() {
try {
const now = Date.now();
const activeJobs = this.jobs.filter(
(job) => job.status === JobStatus.Started,
);
logger.trace(`Active jobs: ${activeJobs.length}`);
// Select all pending jobs except for scheduled
const pendingJobs = this.jobs.filter(
(job) =>
job.executable &&
(!job.scheduledTime ||
(job.scheduledTime && job.scheduledTime <= now)),
);
logger.trace(`Pending jobs: ${pendingJobs.length}`);
// Select all scheduled jobs
const scheduledJobs = this.jobs.filter(
(job) => job.executable && job.scheduledTime,
);
if (scheduledJobs.length > 0) {
scheduledJobs.forEach((job) => {
if (job.scheduledTime && job.scheduledTime > now) {
const delay = job.scheduledTime - now;
this.changeJobStatus(job, JobStatus.Scheduled);
setTimeout(() => void this.executeJob(job), delay);
}
});
}
const availableSlots = this.concurrencyLimit - activeJobs.length;
logger.trace(`Available slots: ${availableSlots}`);
if (availableSlots <= 0 || pendingJobs.length === 0) {
this.dispatchEvent(new CustomEvent<void>('stop'));
return; // No available slots or no pending jobs
}
// Get the jobs that will be started now
const jobsToStart = pendingJobs.slice(0, availableSlots);
logger.trace(
`Jobs to start: [${jobsToStart.map((j) => j.id).join(', ')}]`,
);
// Start all the selected jobs concurrently
await Promise.allSettled(
jobsToStart.map(async (job) => this.executeJob(job)),
);
// After these jobs are done, check if there are any more jobs to process
logger.trace('Trying to restart queue');
void this.start();
} catch (error) {
logger.error('Queue start failed', error);
}
}
/**
* Registers a new job handler in the handlers registry.
*
* @param {string} name
* @param {JobHandler} handler
* @memberof Queue
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
registerHandler(name: string, handler: JobHandler<any, any>) {
this.handlers.register(name, handler);
}
/**
* Adds a new job to the queue and starts the queue if it isn't already started.
*
* @template T
* @param {JobConfig<T>} config
* @returns {string}
* @memberof Queue
*/
add<T extends JobData = JobData>(config: JobConfig<T>): string {
const job = new Job<T>(config);
// In case of restored Scheduled jobs we need to bring them to Pending again
if (job.status === JobStatus.Scheduled) {
job.status = JobStatus.Pending;
}
this.jobs.push(job);
logger.trace('Job added:', JSON.stringify(serialize(job), null, 2));
void this.storageUpdate(job.id, job);
void this.start();
return job.id;
}
/**
* Returns a job from the queue by its ID. Uses local in-memory source
*
* @param {string} id
* @returns {(Job | undefined)} The job if found, otherwise undefined.
* @memberof Queue
*/
getLocal<T extends JobData = JobData>(id: string): Job<T> | undefined {
const localJob = this.jobs.find((job) => job.id === id) as Job<T>;
if (localJob) {
return localJob;
}
return;
}
/**
* Returns a job config from the queue by its ID. Uses both local and storage search
*
* @param {string} id
* @returns {Promise<JobConfig | undefined>} The job if found, otherwise undefined.
* @memberof Queue
*/
async get<T extends JobData = JobData>(
id: string,
): Promise<JobConfig<T> | undefined> {
const localJob = this.getLocal<T>(id);
if (localJob) {
return localJob.toJSON();
}
if (!this.storage) {
return;
}
// If job not found locally we will try to find on storage
return await this.storage.get<JobConfig<T>>(id);
}
/**
* Cancels a job by setting its status to Cancelled.
*
* @param {string} id
* @returns {boolean} true if the job was found and cancelled, false otherwise.
* @memberof Queue
*/
cancel(id: string): boolean {
const job = this.jobs.find((job) => job.id === id);
if (job) {
logger.trace(`Job #${id} is cancelled`);
job.status = JobStatus.Cancelled;
return true;
}
logger.trace(`Job #${id} has not been cancelled`);
return false;
}
/**
* Deletes a job from the queue.
*
* @param {string} id
* @returns {boolean} true if the job was found and deleted, false otherwise.
* @memberof Queue
*/
delete(id: string): boolean {
const size = this.jobs.length;
this.jobs = this.jobs.filter((job) => job.id !== id);
const isDeleted = this.jobs.length < size;
if (isDeleted) {
logger.trace(`Job #${id} is deleted`);
} else {
logger.trace(`Job #${id} has not been deleted`);
}
return isDeleted;
}
/**
* Graceful queue stop
*
* @memberof Queue
*/
async stop() {
await this.storageDown();
}
}