@rango-dev/queue-manager-core 0.1.10-next.69

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.
package/src/manager.ts ADDED
@@ -0,0 +1,606 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import Persistor from './persistor';
3
+ import Queue, { QueueEventHandlers, TaskEvent } from './queue';
4
+ import { QueueStorage, Status } from './types';
5
+
6
+ export type ManagerContext = object;
7
+ export type QueueName = string;
8
+ export type QueueID = string;
9
+ export type BlockedTask = {
10
+ queue_id: string;
11
+ task_id: string;
12
+ action: string;
13
+ reason: Record<string, unknown>;
14
+ storage: {
15
+ get: () => QueueStorage;
16
+ set: (data: QueueStorage) => QueueStorage;
17
+ };
18
+ };
19
+
20
+ export type SetStorage<T> = (nextStorage: T) => T;
21
+
22
+ export interface ExecuterActions<
23
+ T extends QueueStorage = QueueStorage,
24
+ V extends string = string,
25
+ C = ManagerContext
26
+ > {
27
+ next: () => void;
28
+ retry: () => void;
29
+ failed: () => void;
30
+ schedule: (actionName: V) => void;
31
+ setStorage: SetStorage<T>;
32
+ getStorage: () => T;
33
+ block: (reason: Record<string, unknown>) => void;
34
+ unblock: () => void;
35
+ context: C;
36
+ }
37
+
38
+ export interface QueueDef<
39
+ T extends QueueStorage = QueueStorage,
40
+ V extends string = string,
41
+ C = ManagerContext
42
+ > {
43
+ name: QueueName;
44
+ actions: {
45
+ [K in V]: (actions: ExecuterActions<T, V, C>) => void | Promise<void>;
46
+ };
47
+ events?: Partial<QueueEventHandlers>;
48
+ run: V[];
49
+ whenTaskBlocked?: (
50
+ event: any,
51
+ params: {
52
+ queue_id: string;
53
+ queue: Queue;
54
+ context: C;
55
+ getBlockedTasks: () => BlockedTask[];
56
+ forceExecute: (queue_id: string, data?: object) => void;
57
+ retry: () => void;
58
+ manager: Manager;
59
+ }
60
+ ) => void;
61
+ }
62
+
63
+ export interface Events {
64
+ onCreateQueue: (queue: QueueInfo & { id: QueueID }) => void;
65
+ onUpdateQueue: (queue_id: QueueID, queue: QueueInfo) => void;
66
+ onCreateTask: (queue_id: QueueID, event: TaskEvent) => void;
67
+ onUpdateTask: (queue_id: QueueID, event: TaskEvent) => void;
68
+ onStorageUpdate: (queue_id: QueueID, data: QueueStorage) => void;
69
+ onTaskBlock: (queue_id: QueueID) => void;
70
+ onPersistedDataLoaded: (manager: Manager) => void;
71
+ }
72
+
73
+ interface ManagerOptions {
74
+ events?: Partial<Events>;
75
+ queuesDefs: QueueDef[];
76
+ context?: ManagerContext;
77
+ isPaused?: boolean;
78
+ }
79
+
80
+ export interface QueueInfo {
81
+ name: QueueName;
82
+ createdAt: number;
83
+ status: Status;
84
+ list: Queue;
85
+ actions: {
86
+ run: () => void;
87
+ cancel: () => void;
88
+ setStorage: SetStorage<any>;
89
+ getStorage: () => any;
90
+ };
91
+ }
92
+
93
+ class Manager {
94
+ private queuesDefs = new Map<QueueName, QueueDef>();
95
+ private queues = new Map<QueueID, QueueInfo>();
96
+ private events: Events;
97
+ private persistor: Persistor;
98
+ private context: ManagerContext;
99
+ private isPaused: boolean = false;
100
+
101
+ /**
102
+ *
103
+ * Making an instance, initilize events, setup a persistor and try to recover the last state of the manager.
104
+ *
105
+ * */
106
+ constructor(options: ManagerOptions) {
107
+ const defaultEventHandlers: Events = {
108
+ onCreateQueue: () => {
109
+ // ...
110
+ },
111
+ onCreateTask: () => {
112
+ // ...
113
+ },
114
+ onUpdateQueue: () => {
115
+ // ...
116
+ },
117
+ onUpdateTask: () => {
118
+ // ...
119
+ },
120
+ onStorageUpdate: () => {
121
+ // ...
122
+ },
123
+ onTaskBlock: () => {
124
+ // ...
125
+ },
126
+ onPersistedDataLoaded: () => {
127
+ // ..
128
+ },
129
+ };
130
+
131
+ if (options.events) {
132
+ this.events = {
133
+ ...defaultEventHandlers,
134
+ ...options.events,
135
+ };
136
+ } else {
137
+ this.events = defaultEventHandlers;
138
+ }
139
+
140
+ options.queuesDefs.map((qDef) => {
141
+ this.queuesDefs.set(qDef.name, qDef);
142
+ });
143
+
144
+ this.context = options.context || {};
145
+ this.persistor = new Persistor();
146
+ this.sync();
147
+
148
+ if (options.isPaused) {
149
+ this.pause();
150
+ }
151
+ }
152
+
153
+ /**
154
+ *
155
+ * Reading persisted data from storage then brings into memory.
156
+ *
157
+ * Notes:
158
+ * - Reset the memory, so we can call this method whenever we want and not only on the initialize process.
159
+ * - All the events will be tirggered (like onCreateQueue, onCreateTask, onBlock, ....)
160
+ * - Try to `resume` if the status is `running`.
161
+ * - Trigger `onPersistedDataLoaded` event when queues recovered from storage.
162
+ *
163
+ */
164
+ private async sync() {
165
+ // Reset queues, if anything is exist in memory.
166
+ this.queues = new Map();
167
+
168
+ // Reading queues from storage
169
+ const queues = await this.persistor.getAll();
170
+
171
+ // Brings them into memory
172
+ queues.forEach((q) => {
173
+ const list = this.createQueue({
174
+ queue_id: q.id,
175
+ queue_name: q.name,
176
+ });
177
+ this.add(q.id, {
178
+ list,
179
+ createdAt: q.createdAt,
180
+ name: q.name,
181
+ status: q.status,
182
+ actions: {
183
+ run: () => {
184
+ list.next({
185
+ context: this.getContext(),
186
+ });
187
+ },
188
+ cancel: () => {
189
+ list.cancel();
190
+ },
191
+ setStorage: (...args) => {
192
+ list.setStorage(...args);
193
+ },
194
+ getStorage: () => {
195
+ return list.getStorage();
196
+ },
197
+ },
198
+ });
199
+
200
+ list.initTasks({
201
+ state: q.state,
202
+ tasks: q.tasks,
203
+ storage: q.storage || {},
204
+ });
205
+
206
+ if (q.status === Status.RUNNING && this.shouldExecute()) {
207
+ console.log('[INIT] Try to resume');
208
+ list.resume({
209
+ context: this.getContext(),
210
+ });
211
+ }
212
+ });
213
+
214
+ // Trigger an event to let the subscribers we are done here.
215
+ this.events.onPersistedDataLoaded(this);
216
+ }
217
+
218
+ /**
219
+ *
220
+ * Making a new instance from `Queue` and adds Manager's event handlers to it.
221
+ *
222
+ * @returns An instance of `Queue` with wrapped event handlers from Manager.
223
+ *
224
+ */
225
+ private createQueue({
226
+ queue_id,
227
+ queue_name,
228
+ }: {
229
+ queue_id: QueueID;
230
+ queue_name: QueueName;
231
+ }) {
232
+ const manager = this;
233
+ const def = this.queuesDefs.get(queue_name)!;
234
+ const list = new Queue({
235
+ id: queue_id,
236
+ events: {
237
+ onCreate: (task) => {
238
+ this.events.onCreateTask(queue_id, task);
239
+ this.handleUpdate(queue_id);
240
+
241
+ if (def.events?.onCreate) def.events.onCreate(task);
242
+ },
243
+ onUpdate: (task) => {
244
+ this.events.onUpdateTask(queue_id, task);
245
+ this.handleUpdate(queue_id);
246
+
247
+ if (def.events?.onUpdate) def.events.onUpdate(task);
248
+ },
249
+ onUpdateListStatus: (status) => {
250
+ this.queues.set(queue_id, {
251
+ ...this.get(queue_id)!,
252
+ status,
253
+ });
254
+ this.events.onUpdateQueue(queue_id, this.get(queue_id)!);
255
+
256
+ this.handleUpdate(queue_id);
257
+
258
+ // After finishing a queue, try to run other queues.
259
+ this.execute();
260
+ if (def.events?.onUpdateListStatus)
261
+ def.events.onUpdateListStatus(status);
262
+ },
263
+ onStorageUpdate: (data) => {
264
+ this.events.onStorageUpdate(queue_id, data);
265
+ if (def.events?.onStorageUpdate) def.events.onStorageUpdate(data);
266
+ this.handleUpdate(queue_id);
267
+ },
268
+ onBlock: (event) => {
269
+ // Update queue status
270
+ this.queues.set(queue_id, {
271
+ ...this.get(queue_id)!,
272
+ status: Status.BLOCKED,
273
+ });
274
+
275
+ // Trigger event
276
+ this.events.onTaskBlock(queue_id);
277
+ if (def.whenTaskBlocked) {
278
+ def.whenTaskBlocked(event, {
279
+ queue_id: queue_id,
280
+ queue: list,
281
+ context: this.getContext(),
282
+ getBlockedTasks: this.getBlockedTasks.bind(this),
283
+ forceExecute: this.forceExecute.bind(this),
284
+ retry: this.retry.bind(this),
285
+ manager,
286
+ });
287
+ }
288
+
289
+ // Sync
290
+ this.handleUpdate(queue_id);
291
+ },
292
+ onUnblock: () => {
293
+ // Update queue status
294
+ this.queues.set(queue_id, {
295
+ ...this.get(queue_id)!,
296
+ status: Status.PENDING,
297
+ });
298
+
299
+ // Sync
300
+ this.handleUpdate(queue_id);
301
+
302
+ this.execute();
303
+ },
304
+ },
305
+ actions: def.actions,
306
+ });
307
+ return list;
308
+ }
309
+
310
+ /**
311
+ * Go through all tasks (from all queues) and return a list of blocked tasks
312
+ *
313
+ * @returns a list of blocked tasks including enough information to get the queue and mutate the storage.
314
+ *
315
+ */
316
+ private getBlockedTasks() {
317
+ const queues = this.getAll();
318
+ const blockedTasks: BlockedTask[] = [];
319
+ queues.forEach((q, queue_id) => {
320
+ q.list.tasks.forEach((task) => {
321
+ const state = q.list.state.tasks[task.id];
322
+ if (state.status === Status.BLOCKED) {
323
+ blockedTasks.push({
324
+ task_id: task.id,
325
+ queue_id: queue_id,
326
+ action: task.action,
327
+ reason: state.blockedFor,
328
+ storage: {
329
+ get: () => {
330
+ return q.list.getStorage();
331
+ },
332
+ set: (data) => {
333
+ return q.list.setStorage(data);
334
+ },
335
+ },
336
+ });
337
+ }
338
+ });
339
+ });
340
+
341
+ return blockedTasks;
342
+ }
343
+
344
+ /**
345
+ *
346
+ * Add a queue to the manager to keep track of the queue and its state.
347
+ *
348
+ * @param id
349
+ * @param queue
350
+ * @returns
351
+ */
352
+ private add(id: QueueID, queue: QueueInfo) {
353
+ this.queues.set(id, queue);
354
+ const createdQueue = this.get(id)!;
355
+ this.events.onCreateQueue({ ...createdQueue, id });
356
+
357
+ return createdQueue;
358
+ }
359
+
360
+ // Create a new queue
361
+ /**
362
+ *
363
+ * Create a new queue by client.
364
+ *
365
+ * It will do the internal things to make a queue from definitions, and running using Manager.
366
+ *
367
+ * Notes:
368
+ * - After creating the queue, it will be run automatically.
369
+ *
370
+ * @returns an ID for queue so it can be used to get the created queue later by client.
371
+ *
372
+ */
373
+ public async create(name: QueueName, storage: QueueStorage) {
374
+ if (!this.queuesDefs.has(name)) {
375
+ throw new Error('You need to add a queue definition first.');
376
+ }
377
+
378
+ const def = this.queuesDefs.get(name)!;
379
+ const queue_id: QueueID = uuidv4();
380
+ const createdAt = Date.now();
381
+ const list = this.createQueue({
382
+ queue_id: queue_id,
383
+ queue_name: name,
384
+ });
385
+ list.setStorage(storage);
386
+
387
+ const createdQueue = this.add(queue_id, {
388
+ list,
389
+ createdAt,
390
+ name,
391
+ status: Status.PENDING,
392
+ actions: {
393
+ run: () => {
394
+ list.next({
395
+ context: this.getContext(),
396
+ });
397
+ },
398
+ cancel: () => {
399
+ list.cancel();
400
+ },
401
+ setStorage: (...args) => {
402
+ list.setStorage(...args);
403
+ },
404
+ getStorage: () => {
405
+ return list.getStorage();
406
+ },
407
+ },
408
+ });
409
+
410
+ // Persist initial queue
411
+ // Note: we need to first insert the queue, and then it can be updated by internal events.
412
+ await this.persistor.insertQueue({
413
+ id: queue_id,
414
+ createdAt,
415
+ name: createdQueue.name,
416
+ status: createdQueue.status,
417
+ tasks: list.tasks,
418
+ state: list.state,
419
+ storage: list.getStorage(),
420
+ });
421
+
422
+ // adding initial tasks
423
+ def.run.forEach((action) => {
424
+ console.log('action', action);
425
+ list.createTask(action);
426
+ });
427
+
428
+ // After creating a new queue, try to run.
429
+ this.execute();
430
+ return queue_id;
431
+ }
432
+
433
+ /**
434
+ * Get a queue by its ID.
435
+ *
436
+ * @returns An object includes queue and its state in `Manager`.
437
+ */
438
+ public get(queue_id: QueueID) {
439
+ return this.queues.get(queue_id);
440
+ }
441
+
442
+ /**
443
+ * Get all queues from `Manager`
444
+ *
445
+ * @returns a list of queues includes all the queues and their states.
446
+ */
447
+ public getAll() {
448
+ return this.queues;
449
+ }
450
+
451
+ /**
452
+ *
453
+ * Ask from manager to run pending queues.
454
+ *
455
+ * It only try to run queues with `PENDING` status and ignore all the other statuses.
456
+ *
457
+ */
458
+ public execute() {
459
+ if (!this.shouldExecute()) return;
460
+
461
+ for (const [, q] of Array.from(this.queues)) {
462
+ if (q.status === Status.PENDING) {
463
+ console.log('There is a pending queue. Run it.');
464
+ q.actions.run();
465
+ }
466
+ }
467
+
468
+ console.log('There is no pending queue.');
469
+ }
470
+
471
+ /**
472
+ *
473
+ * Try to find queues with `RUNNING` status to run them again.
474
+ *
475
+ * It's useful for recovering the queue at some certain points
476
+ * like running a currepted task (reloaded when it was running) or needs manual trigger from UI.
477
+ *
478
+ * @returns
479
+ */
480
+ public resume() {
481
+ if (!this.shouldExecute()) return;
482
+
483
+ for (const [, q] of Array.from(this.queues)) {
484
+ if (q.status === Status.RUNNING) {
485
+ console.log("Found a running queue. Let's resume the queue.", q);
486
+ q.list.resume({
487
+ context: this.getContext(),
488
+ });
489
+ return;
490
+ }
491
+ }
492
+
493
+ // If there is no running queue, try to run a new queue.
494
+ this.execute();
495
+ }
496
+
497
+ /**
498
+ *
499
+ * Run all `BLOCKED` queues once again.
500
+ *
501
+ * If a queue has `BLOCKED` status and the last task is `BLOCKED` as well,
502
+ * The task will be run one more time.
503
+ *
504
+ * Useful for scenarios like we are blocking the queue under some conditions in task,
505
+ * We can use this method to ask the queue to run the blocked task one more time and
506
+ * maybe this time condtions are met and the queue can be proceed.
507
+ *
508
+ * @returns
509
+ */
510
+ public retry() {
511
+ if (!this.shouldExecute()) return;
512
+
513
+ for (const [, q] of Array.from(this.queues)) {
514
+ if (q.status === Status.BLOCKED) {
515
+ console.log(
516
+ `[Retry] Found: ${q.list.id}, Running onBlock callback.`,
517
+ q
518
+ );
519
+ q.list.checkBlock();
520
+ }
521
+ }
522
+
523
+ // If there is no running queue, try to run a new queue.
524
+ this.execute();
525
+ }
526
+
527
+ /**
528
+ *
529
+ * Run a blocked task on a specific queue with the ability to pass more data.
530
+ *
531
+ * Useful when we have a custom logic for running queue and needs to pass some specific data
532
+ * to the task and try to run it manually with the provided data.
533
+ *
534
+ */
535
+ public forceExecute(queue_id: string, data?: object) {
536
+ const queue = this.get(queue_id);
537
+ let context = this.getContext();
538
+ if (data) {
539
+ context = {
540
+ ...context,
541
+ ...data,
542
+ };
543
+ }
544
+
545
+ queue?.list.forceRun({
546
+ context,
547
+ });
548
+ }
549
+
550
+ /**
551
+ *
552
+ * Sync in-memory state (of `Manager`) with storage (persist).
553
+ *
554
+ * Usually we call this method after a change detected in the state of manager.
555
+ *
556
+ */
557
+ private handleUpdate(queue_id: QueueID) {
558
+ const queue = this.get(queue_id);
559
+
560
+ if (queue) {
561
+ const status = queue.status;
562
+ const state = queue.list.state;
563
+ const tasks = queue.list.tasks;
564
+ this.persistor.updateQueue(queue_id, {
565
+ status,
566
+ state,
567
+ tasks,
568
+ storage: queue.list.getStorage(),
569
+ });
570
+ }
571
+ }
572
+
573
+ /**
574
+ * Active readonly mode for manager, it means it doesn't run anythin,
575
+ * And only can be used to read the data.
576
+ */
577
+ public pause() {
578
+ this.isPaused = true;
579
+ }
580
+
581
+ /**
582
+ * Activate normal mode which means it will be able to run the queuese as well.
583
+ */
584
+ public run() {
585
+ // If call this method multiple times, it should be run for once.
586
+ if (this.isPaused) {
587
+ this.isPaused = false;
588
+ this.sync();
589
+ }
590
+ }
591
+
592
+ private getContext() {
593
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
594
+ //@ts-ignore
595
+ return this.context?.current || {};
596
+ }
597
+
598
+ private shouldExecute() {
599
+ console.log('[shouldExecute] checking and result is:', {
600
+ isPaused: this.isPaused,
601
+ });
602
+ return !this.isPaused;
603
+ }
604
+ }
605
+
606
+ export { Manager };
@@ -0,0 +1,63 @@
1
+ import { openDB, DBSchema, IDBPDatabase } from 'idb';
2
+
3
+ import { QueueID } from './manager';
4
+ import { PersistedQueue } from './types';
5
+
6
+ const DB_NAME = 'queues-manager';
7
+ const OBJECT_STORE_NAME = 'queues';
8
+ const VERSION = 1;
9
+
10
+ type UpdatePersistedQueue = Partial<
11
+ Pick<PersistedQueue, 'status' | 'state' | 'tasks' | 'storage'>
12
+ >;
13
+
14
+ interface Database extends DBSchema {
15
+ queues: {
16
+ value: PersistedQueue;
17
+ key: string;
18
+ };
19
+ }
20
+
21
+ class Persistor {
22
+ db: Promise<IDBPDatabase<Database>>;
23
+ constructor() {
24
+ this.db = openDB<Database>(DB_NAME, VERSION, {
25
+ upgrade(db) {
26
+ db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'id' });
27
+ },
28
+ });
29
+ }
30
+ async insertQueue(queue: PersistedQueue) {
31
+ const db = await this.db;
32
+ const queueRecord = await db.get(OBJECT_STORE_NAME, queue.id);
33
+ if (queueRecord) {
34
+ console.log('[Persistor] Queue already exists inside persistor.');
35
+ } else {
36
+ await db.add(OBJECT_STORE_NAME, queue);
37
+ console.log('[Persistor] Queue added to IndexedDB successfully.');
38
+ }
39
+ }
40
+ async updateQueue(id: QueueID, queue: UpdatePersistedQueue) {
41
+ const db = await this.db;
42
+ const currentRecord = await db.get(OBJECT_STORE_NAME, id);
43
+
44
+ if (!currentRecord) {
45
+ console.log("[Persistor] Requested queue for update doesn't exist.");
46
+ return;
47
+ }
48
+
49
+ const updatedRecord = {
50
+ ...currentRecord,
51
+ ...queue,
52
+ };
53
+ await db.put(OBJECT_STORE_NAME, updatedRecord);
54
+ }
55
+ async getAll() {
56
+ const db = await this.db;
57
+ const results = await db.getAll(OBJECT_STORE_NAME);
58
+
59
+ return results;
60
+ }
61
+ }
62
+
63
+ export default Persistor;