@rango-dev/queue-manager-core 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/index.js.map +2 -2
- package/dist/manager.d.ts +8 -5
- package/dist/manager.d.ts.map +1 -1
- package/dist/queue-manager-core.build.json +1 -1
- package/package.json +1 -1
- package/src/manager.ts +13 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
# [0.32.0](https://github.com/rango-exchange/rango-client/compare/queue-manager-core@0.31.0...queue-manager-core@0.32.0) (2025-08-05)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
1
5
|
# [0.31.0](https://github.com/rango-exchange/rango-client/compare/queue-manager-core@0.30.0...queue-manager-core@0.31.0) (2025-07-22)
|
|
2
6
|
|
|
3
7
|
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/manager.ts", "../src/persistor.ts", "../src/queue.ts", "../src/types.ts"],
|
|
4
|
-
"sourcesContent": ["import type { QueueEventHandlers, TaskEvent } from './queue';\nimport type { QueueStorage } from './types';\n\nimport { v4 as uuidv4 } from 'uuid';\n\nimport Persistor from './persistor';\nimport Queue from './queue';\nimport { Status, SYNC_POLLING_INTERVAL } from './types';\n\nexport type ManagerContext = object;\nexport type QueueName = string;\nexport type QueueID = string;\nexport type BlockedTask = {\n queue_id: string;\n task_id: string;\n action: string;\n reason: Record<string, unknown>;\n storage: {\n get: () => QueueStorage;\n set: (data: QueueStorage) => QueueStorage;\n };\n};\n\nexport type SetStorage<T> = (nextStorage: T) => T;\n\nexport interface ExecuterActions<\n T extends QueueStorage = QueueStorage,\n V extends string = string,\n C = ManagerContext\n> {\n next: () => void;\n retry: () => void;\n failed: () => void;\n schedule: (actionName: V) => void;\n setStorage: SetStorage<T>;\n getStorage: () => T;\n block: (reason: Record<string, unknown>) => void;\n unblock: () => void;\n context: C;\n}\n\nexport interface QueueDef<\n T extends QueueStorage = QueueStorage,\n V extends string = string,\n C = ManagerContext\n> {\n name: QueueName;\n actions: {\n [K in V]: (actions: ExecuterActions<T, V, C>) => void | Promise<void>;\n };\n events?: Partial<QueueEventHandlers>;\n run: V[];\n whenTaskBlocked?: (\n event: any,\n params: {\n queue_id: string;\n queue: Queue;\n context: C;\n getBlockedTasks: () => BlockedTask[];\n forceExecute: (queue_id: string, data?: object) => void;\n retry: () => void;\n manager: Manager;\n }\n ) => void;\n}\n\nexport interface Events {\n onCreateQueue: (queue: QueueInfo & { id: QueueID }) => void;\n onUpdateQueue: (queue_id: QueueID, queue: QueueInfo) => void;\n onCreateTask: (queue_id: QueueID, event: TaskEvent) => void;\n onUpdateTask: (queue_id: QueueID, event: TaskEvent) => void;\n onStorageUpdate: (queue_id: QueueID, data: QueueStorage) => void;\n onTaskBlock: (queue_id: QueueID) => void;\n onDeleteQueue: (queue_id: QueueID) => void;\n onPersistedDataLoaded: (manager: Manager) => void;\n}\n\ninterface ManagerOptions {\n events?: Partial<Events>;\n queuesDefs: QueueDef[];\n context?: ManagerContext;\n isPaused?: boolean;\n}\n\nexport interface QueueInfo {\n name: QueueName;\n createdAt: number;\n status: Status;\n list: Queue;\n actions: {\n run: () => void;\n cancel: () => void;\n setStorage: SetStorage<any>;\n getStorage: () => any;\n };\n}\n\nclass Manager {\n private queuesDefs = new Map<QueueName, QueueDef>();\n private queues = new Map<QueueID, QueueInfo>();\n private events: Events;\n private persistor: Persistor;\n private context: ManagerContext;\n private isPaused = false;\n // The client won't get any update on pause, We are using a polling mode to fix this issue for now.\n private syncInterval: number | null = null;\n\n /**\n *\n * Making an instance, initilize events, setup a persistor and try to recover the last state of the manager.\n *\n *\n */\n constructor(options: ManagerOptions) {\n const defaultEventHandlers: Events = {\n onCreateQueue: () => {\n // ...\n },\n onCreateTask: () => {\n // ...\n },\n onUpdateQueue: () => {\n // ...\n },\n onUpdateTask: () => {\n // ...\n },\n onStorageUpdate: () => {\n // ...\n },\n onTaskBlock: () => {\n // ...\n },\n onPersistedDataLoaded: () => {\n // ..\n },\n onDeleteQueue: () => {\n // ...\n },\n };\n\n if (options.events) {\n this.events = {\n ...defaultEventHandlers,\n ...options.events,\n };\n } else {\n this.events = defaultEventHandlers;\n }\n\n options.queuesDefs.map((qDef) => {\n this.queuesDefs.set(qDef.name, qDef);\n });\n\n this.context = options.context || {};\n this.persistor = new Persistor();\n\n void this.sync();\n\n if (options.isPaused) {\n this.pause();\n }\n }\n\n // Create a new queue\n /**\n *\n * Create a new queue by client.\n *\n * It will do the internal things to make a queue from definitions, and running using Manager.\n *\n * Notes:\n * - After creating the queue, it will be run automatically.\n *\n * @returns an ID for queue so it can be used to get the created queue later by client.\n *\n */\n public async create(\n name: QueueName,\n storage: QueueStorage,\n options?: { id?: QueueID }\n ) {\n if (!this.queuesDefs.has(name)) {\n throw new Error('You need to add a queue definition first.');\n }\n\n try {\n const def = this.queuesDefs.get(name)!;\n const queue_id: QueueID = options?.id || uuidv4();\n const createdAt = Date.now();\n const list = this.createQueue({\n queue_id: queue_id,\n queue_name: name,\n });\n list.setStorage(storage);\n\n const createdQueue = this.add(queue_id, {\n list,\n createdAt,\n name,\n status: Status.PENDING,\n actions: {\n run: () => {\n list.next({\n context: this.getContext(),\n });\n },\n cancel: () => {\n list.cancel();\n },\n setStorage: (...args) => {\n list.setStorage(...args);\n },\n getStorage: () => {\n return list.getStorage();\n },\n },\n });\n\n /*\n * Persist initial queue\n * Note: we need to first insert the queue, and then it can be updated by internal events.\n */\n await this.persistor.insertQueue({\n id: queue_id,\n createdAt,\n name: createdQueue.name,\n status: createdQueue.status,\n tasks: list.tasks,\n state: list.state,\n storage: list.getStorage(),\n });\n\n // adding initial tasks\n def.run.forEach((action) => {\n list.createTask(action);\n });\n\n // After creating a new queue, try to run.\n this.execute();\n return queue_id;\n } catch (e) {\n throw new Error((e as any)?.message);\n }\n }\n /**\n *\n * Reading persisted data from storage then brings into memory.\n *\n * Notes:\n * - Reset the memory, so we can call this method whenever we want and not only on the initialize process.\n * - All the events will be tirggered (like onCreateQueue, onCreateTask, onBlock, ....)\n * - Try to `resume` if the status is `running`.\n * - Trigger `onPersistedDataLoaded` event when queues recovered from storage.\n *\n */\n\n /**\n * Get a queue by its ID.\n *\n * @returns An object includes queue and its state in `Manager`.\n */\n public get(queue_id: QueueID) {\n return this.queues.get(queue_id);\n }\n\n /**\n * Get all queues from `Manager`\n *\n * @returns a list of queues includes all the queues and their states.\n */\n public getAll() {\n return this.queues;\n }\n\n public deleteQueue(queue_id: QueueID) {\n this.queues.delete(queue_id);\n void this.persistor.deleteQueue(queue_id);\n }\n\n public async clearQueue() {\n // Identify queues that are not running\n this.queues.forEach((queue, queue_id) => {\n if (\n queue.status !== Status.RUNNING &&\n queue.status !== Status.PENDING &&\n queue.status !== Status.BLOCKED\n ) {\n this.deleteQueue(queue_id);\n }\n });\n }\n\n /**\n *\n * Ask from manager to run pending queues.\n *\n * It only try to run queues with `PENDING` status and ignore all the other statuses.\n *\n */\n public execute() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.PENDING) {\n q.actions.run();\n }\n }\n }\n\n /**\n *\n * Try to find queues with `RUNNING` status to run them again.\n *\n * It's useful for recovering the queue at some certain points\n * like running a currepted task (reloaded when it was running) or needs manual trigger from UI.\n *\n * @returns\n */\n public resume() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.RUNNING) {\n q.list.resume({\n context: this.getContext(),\n });\n return;\n }\n }\n\n // If there is no running queue, try to run a new queue.\n this.execute();\n }\n\n /**\n *\n * Run all `BLOCKED` queues once again.\n *\n * If a queue has `BLOCKED` status and the last task is `BLOCKED` as well,\n * The task will be run one more time.\n *\n * Useful for scenarios like we are blocking the queue under some conditions in task,\n * We can use this method to ask the queue to run the blocked task one more time and\n * maybe this time condtions are met and the queue can be proceed.\n *\n * @returns\n */\n public retry() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.BLOCKED) {\n q.list.checkBlock();\n }\n }\n\n // If there is no running queue, try to run a new queue.\n this.execute();\n }\n\n /**\n *\n * Run a blocked task on a specific queue with the ability to pass more data.\n *\n * Useful when we have a custom logic for running queue and needs to pass some specific data\n * to the task and try to run it manually with the provided data.\n *\n */\n public forceExecute(queue_id: string, data?: object) {\n const queue = this.get(queue_id);\n let context = this.getContext();\n if (data) {\n context = {\n ...context,\n ...data,\n };\n }\n\n queue?.list.forceRun({\n context,\n });\n }\n\n /**\n * Active readonly mode for manager, it means it doesn't run anythin,\n * And only can be used to read the data.\n */\n public pause() {\n if (this.isPaused) {\n return;\n }\n this.isPaused = true;\n this.syncInterval = window.setInterval(() => {\n void this.sync();\n }, SYNC_POLLING_INTERVAL);\n }\n\n /**\n * Activate normal mode which means it will be able to run the queuese as well.\n */\n public run() {\n // If call this method multiple times, it should be run for once.\n if (this.isPaused) {\n this.isPaused = false;\n if (!!this.syncInterval) {\n clearInterval(this.syncInterval);\n this.syncInterval = null;\n }\n void this.sync();\n }\n }\n\n private async sync() {\n try {\n // Reading queues from storage\n const queues = await this.persistor.getAll();\n\n // Reset queues, if anything is exist in memory.\n this.queues = new Map();\n\n // Brings them into memory\n queues.forEach((q) => {\n const list = this.createQueue({\n queue_id: q.id,\n queue_name: q.name,\n });\n this.add(q.id, {\n list,\n createdAt: q.createdAt,\n name: q.name,\n status: q.status,\n actions: {\n run: () => {\n list.next({\n context: this.getContext(),\n });\n },\n cancel: () => {\n list.cancel();\n },\n setStorage: (...args) => {\n list.setStorage(...args);\n },\n getStorage: () => {\n return list.getStorage();\n },\n },\n });\n\n list.initTasks({\n state: q.state,\n tasks: q.tasks,\n storage: q.storage || {},\n });\n\n if (q.status === Status.RUNNING && this.shouldExecute()) {\n list.resume({\n context: this.getContext(),\n });\n }\n });\n } catch (e) {\n console.log(`IndexDB Error: ${e}`);\n }\n\n // Trigger an event to let the subscribers we are done here.\n this.events.onPersistedDataLoaded(this);\n }\n\n /**\n *\n * Making a new instance from `Queue` and adds Manager's event handlers to it.\n *\n * @returns An instance of `Queue` with wrapped event handlers from Manager.\n *\n */\n private createQueue(info: { queue_id: QueueID; queue_name: QueueName }) {\n const { queue_id, queue_name } = info;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const manager = this;\n const def = this.queuesDefs.get(queue_name)!;\n const list = new Queue({\n id: queue_id,\n events: {\n onCreate: (task) => {\n this.events.onCreateTask(queue_id, task);\n this.handleUpdate(queue_id);\n\n if (def.events?.onCreate) {\n def.events.onCreate(task);\n }\n },\n onUpdate: (task) => {\n this.events.onUpdateTask(queue_id, task);\n this.handleUpdate(queue_id);\n\n if (def.events?.onUpdate) {\n def.events.onUpdate(task);\n }\n },\n onUpdateListStatus: (status) => {\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status,\n });\n this.events.onUpdateQueue(queue_id, this.get(queue_id)!);\n\n this.handleUpdate(queue_id);\n\n // After finishing a queue, try to run other queues.\n this.execute();\n if (def.events?.onUpdateListStatus) {\n def.events.onUpdateListStatus(status);\n }\n },\n onStorageUpdate: (data) => {\n this.events.onStorageUpdate(queue_id, data);\n if (def.events?.onStorageUpdate) {\n def.events.onStorageUpdate(data);\n }\n this.handleUpdate(queue_id);\n },\n onBlock: (event) => {\n // Update queue status\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status: Status.BLOCKED,\n });\n\n // Trigger event\n this.events.onTaskBlock(queue_id);\n if (def.whenTaskBlocked) {\n def.whenTaskBlocked(event, {\n queue_id: queue_id,\n queue: list,\n context: this.getContext(),\n getBlockedTasks: this.getBlockedTasks.bind(this),\n forceExecute: this.forceExecute.bind(this),\n retry: this.retry.bind(this),\n manager,\n });\n }\n\n // Sync\n this.handleUpdate(queue_id);\n },\n onUnblock: () => {\n // Update queue status\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status: Status.PENDING,\n });\n\n // Sync\n this.handleUpdate(queue_id);\n\n this.execute();\n },\n },\n actions: def.actions,\n });\n return list;\n }\n\n /**\n * Go through all tasks (from all queues) and return a list of blocked tasks\n *\n * @returns a list of blocked tasks including enough information to get the queue and mutate the storage.\n *\n */\n private getBlockedTasks() {\n const queues = this.getAll();\n const blockedTasks: BlockedTask[] = [];\n queues.forEach((q, queue_id) => {\n q.list.tasks.forEach((task) => {\n const state = q.list.state.tasks[task.id];\n if (state.status === Status.BLOCKED) {\n blockedTasks.push({\n task_id: task.id,\n queue_id: queue_id,\n action: task.action,\n reason: state.blockedFor,\n storage: {\n get: () => {\n return q.list.getStorage();\n },\n set: (data) => {\n return q.list.setStorage(data);\n },\n },\n });\n }\n });\n });\n\n return blockedTasks;\n }\n\n /**\n *\n * Add a queue to the manager to keep track of the queue and its state.\n *\n * @param id\n * @param queue\n * @returns\n */\n private add(id: QueueID, queue: QueueInfo) {\n this.queues.set(id, queue);\n const createdQueue = this.get(id)!;\n this.events.onCreateQueue({ ...createdQueue, id });\n\n return createdQueue;\n }\n\n /**\n *\n * Sync in-memory state (of `Manager`) with storage (persist).\n *\n * Usually we call this method after a change detected in the state of manager.\n *\n */\n private handleUpdate(queue_id: QueueID) {\n const queue = this.get(queue_id);\n\n if (queue) {\n const status = queue.status;\n const state = queue.list.state;\n const tasks = queue.list.tasks;\n void this.persistor.updateQueue(queue_id, {\n status,\n state,\n tasks,\n storage: queue.list.getStorage(),\n });\n }\n }\n\n private getContext() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-ts-comment\n //@ts-ignore\n return this.context?.current || {};\n }\n\n private shouldExecute() {\n return !this.isPaused;\n }\n}\n\nexport { Manager };\n", "import type { QueueID } from './manager';\nimport type { PersistedQueue } from './types';\nimport type { DBSchema, IDBPDatabase } from 'idb';\n\nexport const DB_NAME = 'queues-manager';\nconst OBJECT_STORE_NAME = 'queues';\nconst VERSION = 1;\n\ntype UpdatePersistedQueue = Partial<\n Pick<PersistedQueue, 'status' | 'state' | 'tasks' | 'storage'>\n>;\n\ninterface Database extends DBSchema {\n queues: {\n value: PersistedQueue;\n key: string;\n };\n}\n\nclass Persistor {\n db: Promise<IDBPDatabase<Database>>;\n constructor() {\n this.db = import('idb')\n .then(async (idb) => {\n return idb.openDB<Database>(DB_NAME, VERSION, {\n upgrade(db) {\n db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'id' });\n },\n });\n })\n .catch(() => {\n throw new Error(\"Couldn't load idb.\");\n });\n }\n\n async insertQueue(queue: PersistedQueue) {\n const db = await this.db;\n const queueRecord = await db.get(OBJECT_STORE_NAME, queue.id);\n if (queueRecord) {\n // Queue already exists inside persistor.\n } else {\n await db.add(OBJECT_STORE_NAME, queue);\n }\n }\n async updateQueue(id: QueueID, queue: UpdatePersistedQueue) {\n const db = await this.db;\n const currentRecord = await db.get(OBJECT_STORE_NAME, id);\n\n if (!currentRecord) {\n return;\n }\n\n const updatedRecord = {\n ...currentRecord,\n ...queue,\n };\n await db.put(OBJECT_STORE_NAME, updatedRecord);\n }\n async getAll() {\n const db = await this.db;\n const results = await db.getAll(OBJECT_STORE_NAME);\n\n return results;\n }\n async deleteQueue(id: QueueID) {\n const db = await this.db;\n const currentRecord = await db.get(OBJECT_STORE_NAME, id);\n\n if (currentRecord) {\n await db.delete(OBJECT_STORE_NAME, id);\n }\n }\n}\n\nexport default Persistor;\n", "import { v4 as uuidv4 } from 'uuid';\nimport { ManagerContext, QueueDef, QueueID } from './manager';\nimport { QueueStorage, Status } from './types';\n\ntype TaskId = string;\nexport type TaskState = {\n status: Status;\n blockedFor: any;\n};\n\nexport interface QueueContext {\n _queue?: {\n id: string;\n };\n}\nexport type NextParams = {\n context: ManagerContext;\n};\n\nexport interface QueueState {\n status: Status;\n activeTaskIndex: number;\n tasks: {\n [key in TaskId]: TaskState;\n };\n}\n\nexport interface Task {\n id: TaskId;\n action: string;\n}\n\nexport type InitTasks = {\n tasks: Task[];\n state: QueueState;\n storage: QueueStorage;\n};\n\nexport interface TaskEvent {\n id: TaskId;\n task: TaskState;\n action: string;\n}\n\nexport interface QueueEventHandlers {\n // all tasks\n onUpdateListStatus: (status: Status) => void;\n // single task\n onCreate: (event: TaskEvent) => void;\n onUpdate: (event: TaskEvent) => void;\n onStorageUpdate: (data: QueueStorage) => void;\n onBlock: (\n data: Omit<TaskEvent, 'task'> & { reason: Record<string, unknown> }\n ) => void;\n onUnblock: (data: { id: string }) => void;\n}\n\ninterface QueueOptions {\n id: QueueID;\n events: QueueEventHandlers;\n actions: QueueDef['actions'];\n}\n\n/**\n *\n * Notes on statuses:\n * - Success: last task has success status\n * - Failed: any of task has been failed\n * - Running: first task is not on pending\n * - Pending: default state. not started\n *\n */\nclass Queue {\n public id: string;\n public state: QueueState = {\n status: Status.PENDING,\n activeTaskIndex: 0,\n tasks: {},\n };\n public tasks: Task[] = [];\n private events: QueueOptions['events'];\n private actions: QueueOptions['actions'];\n private storage: QueueStorage = {};\n\n constructor(options: QueueOptions) {\n this.id = options.id;\n this.events = options.events;\n this.actions = options.actions;\n }\n\n /**\n * Update queue status and trigger an event\n *\n */\n private updateQueueStatus(status: Status) {\n this.state.status = status;\n this.events.onUpdateListStatus(status);\n }\n\n private updateActiveTaskIndex(index: number) {\n this.state.activeTaskIndex = index;\n }\n\n /**\n *\n * Update task state (`status`, `blockedFor`) and trigger an event.\n * @param id\n * @param nextState\n */\n private updateTaskState(id: TaskId, nextState: Partial<TaskState>) {\n if (nextState.status) {\n this.state.tasks[id].status = nextState.status;\n }\n if (nextState.blockedFor) {\n this.state.tasks[id].blockedFor = nextState.blockedFor;\n }\n\n const updatedTaskEvent = {\n id: id,\n task: this.get(id)!,\n action: this.tasks.find((task) => task.id === id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n }\n\n /**\n * Create a task by providing an `action` name.\n *\n * this method creating the task, push it to the queue's tasks and trigger an event.\n * @param action\n */\n createTask(action: string) {\n const id = uuidv4();\n this.tasks.push({\n action,\n id,\n });\n this.state.tasks[id] = {\n status: Status.PENDING,\n blockedFor: null,\n };\n\n const createdTask = this.get(id);\n this.events.onCreate({\n id,\n task: createdTask!,\n action,\n });\n }\n\n /**\n * Initilize a queue with some tasks, instead of an empty queue.\n *\n * Using it for recover the queue state from persistor.\n *\n */\n public initTasks(info: InitTasks) {\n this.state = info.state;\n this.storage = info.storage;\n\n info.tasks.forEach((task) => {\n this.tasks.push(task);\n const action = this.tasks.find((t) => t.id === task.id)!.action;\n this.events.onCreate({\n id: task.id,\n task: this.get(task.id)!,\n action,\n });\n });\n }\n\n public checkBlock() {\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n return;\n }\n const { task, state } = currentActiveTask;\n\n if (state.status === Status.BLOCKED) {\n this.events.onBlock({\n action: task.action,\n id: task.id,\n reason: state.blockedFor,\n });\n }\n }\n\n /**\n * Getting task state by ID\n */\n public get(id: string): TaskState | null {\n const task = this.state.tasks[id];\n\n if (!task) return null;\n\n return task;\n }\n\n /**\n *\n * Checking if status of the last is `SUCCESS` or not\n *\n */\n private lastTaskIsSuccessful() {\n const lastTask = this.tasks[this.tasks.length - 1];\n\n // checking for empty lists.\n if (lastTask) {\n const lastTaskState = this.state.tasks[lastTask.id];\n\n // Maybe we didn't create the state yet. It should has success status as well.\n if (!!lastTaskState && lastTaskState.status === Status.SUCCESS) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * If the first task started (it's not PENDING),\n * it means the queue has been ran.\n *\n * @returns\n */\n private firstTaskIsStarted() {\n const firstTask = this.tasks[0];\n\n // checking for empty lists.\n if (firstTask) {\n const firstTaskState = this.state.tasks[firstTask.id];\n\n // Maybe we didn't create the state yet.\n if (!!firstTaskState) {\n if (firstTaskState.status !== Status.PENDING) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Getting active task index from state and\n * returns the task and its state.\n *\n */\n private getActiveTask() {\n // First try to get task with `activeTask`\n const index = this.state.activeTaskIndex;\n const task = this.tasks[index];\n\n // Consider all the tasks has been executed.\n if (!task) {\n return null;\n }\n\n const state = this.state.tasks[task.id];\n\n return { task, state, index };\n }\n\n /**\n * Update and find the queue status by checking state of each tasks in the queue.\n */\n public check() {\n const currentListStatus = this.state.status;\n let nextListStatus = this.firstTaskIsStarted()\n ? Status.RUNNING\n : Status.PENDING;\n\n if (this.lastTaskIsSuccessful()) {\n nextListStatus = Status.SUCCESS;\n } else {\n // Is there any failed task?\n for (const task of this.tasks) {\n const state = this.state.tasks[task.id];\n\n // If one item fails, we stop to work on the list.\n if (state.status === Status.FAILED) {\n nextListStatus = Status.FAILED;\n break;\n }\n }\n }\n\n // We only update and trigger an event when there is a new value\n if (nextListStatus !== currentListStatus) {\n this.updateQueueStatus(nextListStatus);\n }\n }\n\n /**\n * Execute active task.\n * Based on the state of active task, the behaviour is different. If status is:\n * - Success -> we need to go to next task by updating the active index and try `next` on more time.\n * - Failed, Running, or no active task -> doesn't do anything.\n * - Pending or Blocked -> update the task and queue status to running, and execute the provided `action` for the task.\n *\n * The queue is a linked list somehow, active task means the pointer to where we are in the queue right now.\n *\n */\n public next(params: NextParams) {\n this.check();\n\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n return;\n }\n\n const {\n index: activeTaskIndex,\n task: activeTask,\n state: activeTaskState,\n } = currentActiveTask;\n\n // if `activeTask` is already done, we will go for next one.\n if (activeTaskState.status === Status.SUCCESS) {\n this.updateActiveTaskIndex(activeTaskIndex + 1);\n this.next(params);\n return;\n }\n\n if (\n [Status.FAILED, Status.CANCELED, Status.RUNNING].includes(\n activeTaskState.status\n )\n ) {\n return;\n }\n\n if (\n activeTaskState.status === Status.PENDING ||\n activeTaskState.status === Status.BLOCKED\n ) {\n // Update task status to `running`\n this.updateTaskState(activeTask.id, {\n status: Status.RUNNING,\n });\n this.updateQueueStatus(Status.RUNNING);\n\n // Try to execute task.\n const execute = this.actions[activeTask.action];\n execute({\n context: this.getContext(params),\n next: () => {\n this.markCurrentTaskAsFinished(params);\n },\n retry: () => {\n this.resume(params);\n },\n failed: () => {\n this.updateTaskState(activeTask.id, {\n status: Status.FAILED,\n });\n this.check();\n },\n schedule: (action) => {\n this.createTask(action);\n this.check();\n },\n getStorage: this.getStorage.bind(this),\n setStorage: this.setStorage.bind(this),\n block: (reason: Record<string, unknown>) => {\n this.block({ reason });\n },\n unblock: () => {\n this.unblock();\n },\n });\n }\n }\n\n /**\n * Change the `status` of active task and queue to BLOCKED, then trigger an event.\n */\n public block({\n reason,\n silent = false,\n }: {\n reason: Record<string, unknown>;\n silent?: boolean;\n }) {\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n throw new Error(\"Task isn't exist.\");\n }\n\n this.updateTaskState(currentActiveTask.task.id, {\n status: Status.BLOCKED,\n blockedFor: reason,\n });\n this.updateQueueStatus(Status.BLOCKED);\n\n if (!silent) {\n this.events.onBlock({\n action: currentActiveTask.task.action,\n id: currentActiveTask.task.id,\n reason,\n });\n }\n }\n\n /**\n * If the active task is `BLOCKED`, update the task status to `PENDING`, queue status to `RUNNING`\n * then trigger an event.\n */\n public unblock() {\n const currentActiveTask = this.getActiveTask();\n\n if (\n !currentActiveTask ||\n currentActiveTask.state.status !== Status.BLOCKED\n ) {\n throw new Error('Task is not blocked.');\n }\n\n this.updateTaskState(currentActiveTask.task.id, {\n status: Status.PENDING,\n });\n this.updateQueueStatus(Status.RUNNING);\n this.events.onUnblock({ id: currentActiveTask.task.id });\n }\n\n /**\n * If the active task is `BLOCKED` then execute the `action` for the task.\n *\n * It is useful for when we need to run a blocked task without changing the status of task at the first place.\n * For scenarios like we have some conditions in `action` and needs to run the `action` again\n * to check the conditions are met or not, if yes, so we can proceed the `action`.\n *\n */\n public forceRun(params: NextParams) {\n const currentTask = this.getActiveTask();\n\n if (!currentTask || currentTask.state.status !== Status.BLOCKED) {\n throw new Error('Task is not blocked.');\n }\n\n // Try to execute task.\n const execute = this.actions[currentTask.task.action];\n execute({\n context: this.getContext(params),\n next: () => {\n /*\n NOTE:\n When running `forceRun`, the status of task can be `BLOCKED`\n So we need to change to `Running` first. \n */\n // Update task status to `running`\n this.updateTaskState(currentTask.task.id, {\n status: Status.RUNNING,\n });\n this.updateQueueStatus(Status.RUNNING);\n\n this.markCurrentTaskAsFinished(params);\n },\n retry: () => {\n this.resume(params);\n },\n failed: () => {\n this.updateTaskState(currentTask.task.id, {\n status: Status.FAILED,\n });\n this.check();\n },\n schedule: (action) => {\n this.createTask(action);\n this.check();\n },\n getStorage: this.getStorage.bind(this),\n setStorage: this.setStorage.bind(this),\n block: (reason: Record<string, unknown>) => {\n this.block({ reason });\n },\n unblock: () => {\n this.unblock();\n },\n });\n }\n private markCurrentTaskAsFinished(params: NextParams) {\n this.check();\n const activeTaskIndex = this.state.activeTaskIndex;\n const activeTask = this.tasks[activeTaskIndex];\n\n if (!activeTask) return;\n\n const activeTaskState = this.state.tasks[activeTask.id];\n if (activeTaskState.status === Status.RUNNING) {\n this.updateTaskState(activeTask.id, {\n status: Status.SUCCESS,\n });\n this.updateActiveTaskIndex(activeTaskIndex + 1);\n\n const updatedTaskEvent = {\n id: activeTask.id,\n task: this.get(activeTask.id)!,\n action: this.tasks.find((task) => task.id === activeTask.id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n this.next(params);\n }\n }\n\n /**\n * If the active task is `RUNNING`, change it to `PENING` the try to run the task by calling `next`.\n * If it's other than `RUNNING` we reset the queue state and run the queue from the beggining.\n *\n * @param params\n * @returns\n */\n public resume(params: NextParams) {\n const activeTaskIndex = this.state.activeTaskIndex;\n const activeTask = this.tasks[activeTaskIndex];\n if (!activeTask) return;\n\n const activeTaskState = this.state.tasks[activeTask.id];\n if (activeTaskState.status === Status.RUNNING) {\n this.updateTaskState(activeTask.id, {\n status: Status.PENDING,\n });\n this.next(params);\n } else {\n this.resetState();\n this.next(params);\n }\n }\n\n /**\n *\n * Cancel the queue by changing active task and queue status to `CANCELED`.\n *\n */\n public cancel() {\n const currentActiveTask = this.getActiveTask();\n\n if (\n !currentActiveTask ||\n [Status.FAILED, Status.CANCELED, Status.SUCCESS].includes(\n currentActiveTask.state.status\n )\n ) {\n return;\n }\n\n const { task } = currentActiveTask;\n\n // Update task status to `canceled`\n this.updateTaskState(task.id, {\n status: Status.CANCELED,\n });\n const updatedTaskEvent = {\n id: task.id,\n task: this.get(task.id)!,\n action: this.tasks.find((t) => t.id === task.id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n\n // Update queue status to `canceled`\n this.updateQueueStatus(Status.CANCELED);\n }\n\n /**\n * Update queue status, and all the tasks inside queue to `PENDING`.\n */\n private resetState() {\n this.state.activeTaskIndex = 0;\n this.state.status = Status.PENDING;\n Object.keys(this.state.tasks).forEach((id) => {\n this.state.tasks[id].status = Status.PENDING;\n });\n }\n\n public getStorage() {\n return this.storage;\n }\n public setStorage(data: QueueStorage) {\n this.storage = data;\n this.events.onStorageUpdate(data);\n return this.storage;\n }\n\n private getContext(params: NextParams): QueueContext & ManagerContext {\n return {\n ...params.context,\n _queue: {\n id: this.id,\n },\n };\n }\n}\n\nexport default Queue;\n", "import type { QueueID, QueueName } from './manager';\nimport type { QueueState, Task } from './queue';\nimport type Queue from './queue';\n\nexport enum Status {\n PENDING = 'PENDING',\n RUNNING = 'RUNNING',\n FAILED = 'FAILED',\n SUCCESS = 'SUCCESS',\n CANCELED = 'CANCELED',\n BLOCKED = 'BLOCKED',\n}\n\nexport const SYNC_POLLING_INTERVAL = 5_000;\n\nexport type QueueStorage = Record<string, unknown>;\n\nexport type QueueType = Queue;\n\nexport interface PersistedQueue {\n id: QueueID;\n createdAt: number;\n name: QueueName;\n status: Status;\n state: QueueState;\n tasks: Task[];\n storage: QueueStorage;\n}\n"],
|
|
5
|
-
"mappings": "+EAGA,OAAS,MAAMA,MAAc,OCCtB,IAAMC,EAAU,iBACjBC,EAAoB,SAc1B,IAAMC,EAAN,KAAgB,CAnBhB,MAmBgB,CAAAC,EAAA,kBAEd,aAA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Q,aAAaJ,EAAmB,CACtC,IAAMQ,EAAQ,KAAK,IAAIR,CAAQ,EAE/B,GAAIQ,EAAO,CACT,IAAMU,EAASV,EAAM,OACfa,EAAQb,EAAM,KAAK,MACnBe,EAAQf,EAAM,KAAK,MACpB,KAAK,UAAU,YAAYR,EAAU,CACxC,OAAAkB,EACA,MAAAG,EACA,MAAAE,EACA,QAASf,EAAM,KAAK,WAAW,CACjC,CAAC,CACH,CACF,CAEQ,YAAa,CAGnB,OAAO,KAAK,SAAS,SAAW,CAAC,CACnC,CAEQ,eAAgB,CACtB,MAAO,CAAC,KAAK,QACf,CACF",
|
|
4
|
+
"sourcesContent": ["import type { QueueEventHandlers, TaskEvent } from './queue';\nimport type { QueueStorage } from './types';\n\nimport { v4 as uuidv4 } from 'uuid';\n\nimport Persistor from './persistor';\nimport Queue from './queue';\nimport { Status, SYNC_POLLING_INTERVAL } from './types';\n\nexport type ManagerContext = object;\nexport type QueueName = string;\nexport type QueueID = string;\n\nexport type BlockedReason = Record<string, unknown>;\nexport type BlockedTask = {\n queue_id: string;\n task_id: string;\n action: string;\n reason: BlockedReason;\n storage: {\n get: () => QueueStorage;\n set: (data: QueueStorage) => QueueStorage;\n };\n};\n\nexport type SetStorage<T> = (nextStorage: T) => T;\n\nexport interface ExecuterActions<\n T extends QueueStorage = QueueStorage,\n V extends string = string,\n C = ManagerContext\n> {\n next: () => void;\n retry: () => void;\n failed: () => void;\n schedule: (actionName: V) => void;\n setStorage: SetStorage<T>;\n getStorage: () => T;\n block: (reason: BlockedReason) => void;\n unblock: () => void;\n context: C;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype WhenTaskBlockedEvent = any;\nexport interface QueueDef<\n T extends QueueStorage = QueueStorage,\n V extends string = string,\n C = ManagerContext\n> {\n name: QueueName;\n actions: {\n [K in V]: (actions: ExecuterActions<T, V, C>) => void | Promise<void>;\n };\n events?: Partial<QueueEventHandlers>;\n run: V[];\n whenTaskBlocked?: (\n event: WhenTaskBlockedEvent,\n params: {\n queue_id: string;\n queue: Queue;\n context: C;\n getBlockedTasks: () => BlockedTask[];\n forceExecute: (queue_id: string, data?: object) => void;\n retry: () => void;\n manager: Manager;\n }\n ) => void;\n}\n\nexport interface Events {\n onCreateQueue: (queue: QueueInfo & { id: QueueID }) => void;\n onUpdateQueue: (queue_id: QueueID, queue: QueueInfo) => void;\n onCreateTask: (queue_id: QueueID, event: TaskEvent) => void;\n onUpdateTask: (queue_id: QueueID, event: TaskEvent) => void;\n onStorageUpdate: (queue_id: QueueID, data: QueueStorage) => void;\n onTaskBlock: (queue_id: QueueID) => void;\n onDeleteQueue: (queue_id: QueueID) => void;\n onPersistedDataLoaded: (manager: Manager) => void;\n}\n\ninterface ManagerOptions {\n events?: Partial<Events>;\n queuesDefs: QueueDef[];\n context?: ManagerContext;\n isPaused?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype _Storage = any;\nexport interface QueueInfo {\n name: QueueName;\n createdAt: number;\n status: Status;\n list: Queue;\n actions: {\n run: () => void;\n cancel: () => void;\n setStorage: SetStorage<_Storage>;\n getStorage: () => _Storage;\n };\n}\n\nclass Manager {\n private queuesDefs = new Map<QueueName, QueueDef>();\n private queues = new Map<QueueID, QueueInfo>();\n private events: Events;\n private persistor: Persistor;\n private context: ManagerContext;\n private isPaused = false;\n // The client won't get any update on pause, We are using a polling mode to fix this issue for now.\n private syncInterval: number | null = null;\n\n /**\n *\n * Making an instance, initilize events, setup a persistor and try to recover the last state of the manager.\n *\n *\n */\n constructor(options: ManagerOptions) {\n const defaultEventHandlers: Events = {\n onCreateQueue: () => {\n // ...\n },\n onCreateTask: () => {\n // ...\n },\n onUpdateQueue: () => {\n // ...\n },\n onUpdateTask: () => {\n // ...\n },\n onStorageUpdate: () => {\n // ...\n },\n onTaskBlock: () => {\n // ...\n },\n onPersistedDataLoaded: () => {\n // ..\n },\n onDeleteQueue: () => {\n // ...\n },\n };\n\n if (options.events) {\n this.events = {\n ...defaultEventHandlers,\n ...options.events,\n };\n } else {\n this.events = defaultEventHandlers;\n }\n\n options.queuesDefs.map((qDef) => {\n this.queuesDefs.set(qDef.name, qDef);\n });\n\n this.context = options.context || {};\n this.persistor = new Persistor();\n\n void this.sync();\n\n if (options.isPaused) {\n this.pause();\n }\n }\n\n // Create a new queue\n /**\n *\n * Create a new queue by client.\n *\n * It will do the internal things to make a queue from definitions, and running using Manager.\n *\n * Notes:\n * - After creating the queue, it will be run automatically.\n *\n * @returns an ID for queue so it can be used to get the created queue later by client.\n *\n */\n public async create(\n name: QueueName,\n storage: QueueStorage,\n options?: { id?: QueueID }\n ) {\n if (!this.queuesDefs.has(name)) {\n throw new Error('You need to add a queue definition first.');\n }\n\n try {\n const def = this.queuesDefs.get(name)!;\n const queue_id: QueueID = options?.id || uuidv4();\n const createdAt = Date.now();\n const list = this.createQueue({\n queue_id: queue_id,\n queue_name: name,\n });\n list.setStorage(storage);\n\n const createdQueue = this.add(queue_id, {\n list,\n createdAt,\n name,\n status: Status.PENDING,\n actions: {\n run: () => {\n list.next({\n context: this.getContext(),\n });\n },\n cancel: () => {\n list.cancel();\n },\n setStorage: (...args) => {\n list.setStorage(...args);\n },\n getStorage: () => {\n return list.getStorage();\n },\n },\n });\n\n /*\n * Persist initial queue\n * Note: we need to first insert the queue, and then it can be updated by internal events.\n */\n await this.persistor.insertQueue({\n id: queue_id,\n createdAt,\n name: createdQueue.name,\n status: createdQueue.status,\n tasks: list.tasks,\n state: list.state,\n storage: list.getStorage(),\n });\n\n // adding initial tasks\n def.run.forEach((action) => {\n list.createTask(action);\n });\n\n // After creating a new queue, try to run.\n this.execute();\n return queue_id;\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n throw new Error((e as any)?.message);\n }\n }\n /**\n *\n * Reading persisted data from storage then brings into memory.\n *\n * Notes:\n * - Reset the memory, so we can call this method whenever we want and not only on the initialize process.\n * - All the events will be tirggered (like onCreateQueue, onCreateTask, onBlock, ....)\n * - Try to `resume` if the status is `running`.\n * - Trigger `onPersistedDataLoaded` event when queues recovered from storage.\n *\n */\n\n /**\n * Get a queue by its ID.\n *\n * @returns An object includes queue and its state in `Manager`.\n */\n public get(queue_id: QueueID) {\n return this.queues.get(queue_id);\n }\n\n /**\n * Get all queues from `Manager`\n *\n * @returns a list of queues includes all the queues and their states.\n */\n public getAll() {\n return this.queues;\n }\n\n public deleteQueue(queue_id: QueueID) {\n this.queues.delete(queue_id);\n void this.persistor.deleteQueue(queue_id);\n }\n\n public async clearQueue() {\n // Identify queues that are not running\n this.queues.forEach((queue, queue_id) => {\n if (\n queue.status !== Status.RUNNING &&\n queue.status !== Status.PENDING &&\n queue.status !== Status.BLOCKED\n ) {\n this.deleteQueue(queue_id);\n }\n });\n }\n\n /**\n *\n * Ask from manager to run pending queues.\n *\n * It only try to run queues with `PENDING` status and ignore all the other statuses.\n *\n */\n public execute() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.PENDING) {\n q.actions.run();\n }\n }\n }\n\n /**\n *\n * Try to find queues with `RUNNING` status to run them again.\n *\n * It's useful for recovering the queue at some certain points\n * like running a currepted task (reloaded when it was running) or needs manual trigger from UI.\n *\n * @returns\n */\n public resume() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.RUNNING) {\n q.list.resume({\n context: this.getContext(),\n });\n return;\n }\n }\n\n // If there is no running queue, try to run a new queue.\n this.execute();\n }\n\n /**\n *\n * Run all `BLOCKED` queues once again.\n *\n * If a queue has `BLOCKED` status and the last task is `BLOCKED` as well,\n * The task will be run one more time.\n *\n * Useful for scenarios like we are blocking the queue under some conditions in task,\n * We can use this method to ask the queue to run the blocked task one more time and\n * maybe this time condtions are met and the queue can be proceed.\n *\n * @returns\n */\n public retry() {\n if (!this.shouldExecute()) {\n return;\n }\n\n for (const [, q] of Array.from(this.queues)) {\n if (q.status === Status.BLOCKED) {\n q.list.checkBlock();\n }\n }\n\n // If there is no running queue, try to run a new queue.\n this.execute();\n }\n\n /**\n *\n * Run a blocked task on a specific queue with the ability to pass more data.\n *\n * Useful when we have a custom logic for running queue and needs to pass some specific data\n * to the task and try to run it manually with the provided data.\n *\n */\n public forceExecute(queue_id: string, data?: object) {\n const queue = this.get(queue_id);\n let context = this.getContext();\n if (data) {\n context = {\n ...context,\n ...data,\n };\n }\n\n queue?.list.forceRun({\n context,\n });\n }\n\n /**\n * Active readonly mode for manager, it means it doesn't run anythin,\n * And only can be used to read the data.\n */\n public pause() {\n if (this.isPaused) {\n return;\n }\n this.isPaused = true;\n this.syncInterval = window.setInterval(() => {\n void this.sync();\n }, SYNC_POLLING_INTERVAL);\n }\n\n /**\n * Activate normal mode which means it will be able to run the queuese as well.\n */\n public run() {\n // If call this method multiple times, it should be run for once.\n if (this.isPaused) {\n this.isPaused = false;\n if (!!this.syncInterval) {\n clearInterval(this.syncInterval);\n this.syncInterval = null;\n }\n void this.sync();\n }\n }\n\n private async sync() {\n try {\n // Reading queues from storage\n const queues = await this.persistor.getAll();\n\n // Reset queues, if anything is exist in memory.\n this.queues = new Map();\n\n // Brings them into memory\n queues.forEach((q) => {\n const list = this.createQueue({\n queue_id: q.id,\n queue_name: q.name,\n });\n this.add(q.id, {\n list,\n createdAt: q.createdAt,\n name: q.name,\n status: q.status,\n actions: {\n run: () => {\n list.next({\n context: this.getContext(),\n });\n },\n cancel: () => {\n list.cancel();\n },\n setStorage: (...args) => {\n list.setStorage(...args);\n },\n getStorage: () => {\n return list.getStorage();\n },\n },\n });\n\n list.initTasks({\n state: q.state,\n tasks: q.tasks,\n storage: q.storage || {},\n });\n\n if (q.status === Status.RUNNING && this.shouldExecute()) {\n list.resume({\n context: this.getContext(),\n });\n }\n });\n } catch (e) {\n console.log(`IndexDB Error: ${e}`);\n }\n\n // Trigger an event to let the subscribers we are done here.\n this.events.onPersistedDataLoaded(this);\n }\n\n /**\n *\n * Making a new instance from `Queue` and adds Manager's event handlers to it.\n *\n * @returns An instance of `Queue` with wrapped event handlers from Manager.\n *\n */\n private createQueue(info: { queue_id: QueueID; queue_name: QueueName }) {\n const { queue_id, queue_name } = info;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const manager = this;\n const def = this.queuesDefs.get(queue_name)!;\n const list = new Queue({\n id: queue_id,\n events: {\n onCreate: (task) => {\n this.events.onCreateTask(queue_id, task);\n this.handleUpdate(queue_id);\n\n if (def.events?.onCreate) {\n def.events.onCreate(task);\n }\n },\n onUpdate: (task) => {\n this.events.onUpdateTask(queue_id, task);\n this.handleUpdate(queue_id);\n\n if (def.events?.onUpdate) {\n def.events.onUpdate(task);\n }\n },\n onUpdateListStatus: (status) => {\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status,\n });\n this.events.onUpdateQueue(queue_id, this.get(queue_id)!);\n\n this.handleUpdate(queue_id);\n\n // After finishing a queue, try to run other queues.\n this.execute();\n if (def.events?.onUpdateListStatus) {\n def.events.onUpdateListStatus(status);\n }\n },\n onStorageUpdate: (data) => {\n this.events.onStorageUpdate(queue_id, data);\n if (def.events?.onStorageUpdate) {\n def.events.onStorageUpdate(data);\n }\n this.handleUpdate(queue_id);\n },\n onBlock: (event) => {\n // Update queue status\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status: Status.BLOCKED,\n });\n\n // Trigger event\n this.events.onTaskBlock(queue_id);\n if (def.whenTaskBlocked) {\n def.whenTaskBlocked(event, {\n queue_id: queue_id,\n queue: list,\n context: this.getContext(),\n getBlockedTasks: this.getBlockedTasks.bind(this),\n forceExecute: this.forceExecute.bind(this),\n retry: this.retry.bind(this),\n manager,\n });\n }\n\n // Sync\n this.handleUpdate(queue_id);\n },\n onUnblock: () => {\n // Update queue status\n this.queues.set(queue_id, {\n ...this.get(queue_id)!,\n status: Status.PENDING,\n });\n\n // Sync\n this.handleUpdate(queue_id);\n\n this.execute();\n },\n },\n actions: def.actions,\n });\n return list;\n }\n\n /**\n * Go through all tasks (from all queues) and return a list of blocked tasks\n *\n * @returns a list of blocked tasks including enough information to get the queue and mutate the storage.\n *\n */\n private getBlockedTasks() {\n const queues = this.getAll();\n const blockedTasks: BlockedTask[] = [];\n queues.forEach((q, queue_id) => {\n q.list.tasks.forEach((task) => {\n const state = q.list.state.tasks[task.id];\n if (state.status === Status.BLOCKED) {\n blockedTasks.push({\n task_id: task.id,\n queue_id: queue_id,\n action: task.action,\n reason: state.blockedFor,\n storage: {\n get: () => {\n return q.list.getStorage();\n },\n set: (data) => {\n return q.list.setStorage(data);\n },\n },\n });\n }\n });\n });\n\n return blockedTasks;\n }\n\n /**\n *\n * Add a queue to the manager to keep track of the queue and its state.\n *\n * @param id\n * @param queue\n * @returns\n */\n private add(id: QueueID, queue: QueueInfo) {\n this.queues.set(id, queue);\n const createdQueue = this.get(id)!;\n this.events.onCreateQueue({ ...createdQueue, id });\n\n return createdQueue;\n }\n\n /**\n *\n * Sync in-memory state (of `Manager`) with storage (persist).\n *\n * Usually we call this method after a change detected in the state of manager.\n *\n */\n private handleUpdate(queue_id: QueueID) {\n const queue = this.get(queue_id);\n\n if (queue) {\n const status = queue.status;\n const state = queue.list.state;\n const tasks = queue.list.tasks;\n void this.persistor.updateQueue(queue_id, {\n status,\n state,\n tasks,\n storage: queue.list.getStorage(),\n });\n }\n }\n\n private getContext() {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n //@ts-ignore\n return this.context?.current || {};\n }\n\n private shouldExecute() {\n return !this.isPaused;\n }\n}\n\nexport { Manager };\n", "import type { QueueID } from './manager';\nimport type { PersistedQueue } from './types';\nimport type { DBSchema, IDBPDatabase } from 'idb';\n\nexport const DB_NAME = 'queues-manager';\nconst OBJECT_STORE_NAME = 'queues';\nconst VERSION = 1;\n\ntype UpdatePersistedQueue = Partial<\n Pick<PersistedQueue, 'status' | 'state' | 'tasks' | 'storage'>\n>;\n\ninterface Database extends DBSchema {\n queues: {\n value: PersistedQueue;\n key: string;\n };\n}\n\nclass Persistor {\n db: Promise<IDBPDatabase<Database>>;\n constructor() {\n this.db = import('idb')\n .then(async (idb) => {\n return idb.openDB<Database>(DB_NAME, VERSION, {\n upgrade(db) {\n db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'id' });\n },\n });\n })\n .catch(() => {\n throw new Error(\"Couldn't load idb.\");\n });\n }\n\n async insertQueue(queue: PersistedQueue) {\n const db = await this.db;\n const queueRecord = await db.get(OBJECT_STORE_NAME, queue.id);\n if (queueRecord) {\n // Queue already exists inside persistor.\n } else {\n await db.add(OBJECT_STORE_NAME, queue);\n }\n }\n async updateQueue(id: QueueID, queue: UpdatePersistedQueue) {\n const db = await this.db;\n const currentRecord = await db.get(OBJECT_STORE_NAME, id);\n\n if (!currentRecord) {\n return;\n }\n\n const updatedRecord = {\n ...currentRecord,\n ...queue,\n };\n await db.put(OBJECT_STORE_NAME, updatedRecord);\n }\n async getAll() {\n const db = await this.db;\n const results = await db.getAll(OBJECT_STORE_NAME);\n\n return results;\n }\n async deleteQueue(id: QueueID) {\n const db = await this.db;\n const currentRecord = await db.get(OBJECT_STORE_NAME, id);\n\n if (currentRecord) {\n await db.delete(OBJECT_STORE_NAME, id);\n }\n }\n}\n\nexport default Persistor;\n", "import { v4 as uuidv4 } from 'uuid';\nimport { ManagerContext, QueueDef, QueueID } from './manager';\nimport { QueueStorage, Status } from './types';\n\ntype TaskId = string;\nexport type TaskState = {\n status: Status;\n blockedFor: any;\n};\n\nexport interface QueueContext {\n _queue?: {\n id: string;\n };\n}\nexport type NextParams = {\n context: ManagerContext;\n};\n\nexport interface QueueState {\n status: Status;\n activeTaskIndex: number;\n tasks: {\n [key in TaskId]: TaskState;\n };\n}\n\nexport interface Task {\n id: TaskId;\n action: string;\n}\n\nexport type InitTasks = {\n tasks: Task[];\n state: QueueState;\n storage: QueueStorage;\n};\n\nexport interface TaskEvent {\n id: TaskId;\n task: TaskState;\n action: string;\n}\n\nexport interface QueueEventHandlers {\n // all tasks\n onUpdateListStatus: (status: Status) => void;\n // single task\n onCreate: (event: TaskEvent) => void;\n onUpdate: (event: TaskEvent) => void;\n onStorageUpdate: (data: QueueStorage) => void;\n onBlock: (\n data: Omit<TaskEvent, 'task'> & { reason: Record<string, unknown> }\n ) => void;\n onUnblock: (data: { id: string }) => void;\n}\n\ninterface QueueOptions {\n id: QueueID;\n events: QueueEventHandlers;\n actions: QueueDef['actions'];\n}\n\n/**\n *\n * Notes on statuses:\n * - Success: last task has success status\n * - Failed: any of task has been failed\n * - Running: first task is not on pending\n * - Pending: default state. not started\n *\n */\nclass Queue {\n public id: string;\n public state: QueueState = {\n status: Status.PENDING,\n activeTaskIndex: 0,\n tasks: {},\n };\n public tasks: Task[] = [];\n private events: QueueOptions['events'];\n private actions: QueueOptions['actions'];\n private storage: QueueStorage = {};\n\n constructor(options: QueueOptions) {\n this.id = options.id;\n this.events = options.events;\n this.actions = options.actions;\n }\n\n /**\n * Update queue status and trigger an event\n *\n */\n private updateQueueStatus(status: Status) {\n this.state.status = status;\n this.events.onUpdateListStatus(status);\n }\n\n private updateActiveTaskIndex(index: number) {\n this.state.activeTaskIndex = index;\n }\n\n /**\n *\n * Update task state (`status`, `blockedFor`) and trigger an event.\n * @param id\n * @param nextState\n */\n private updateTaskState(id: TaskId, nextState: Partial<TaskState>) {\n if (nextState.status) {\n this.state.tasks[id].status = nextState.status;\n }\n if (nextState.blockedFor) {\n this.state.tasks[id].blockedFor = nextState.blockedFor;\n }\n\n const updatedTaskEvent = {\n id: id,\n task: this.get(id)!,\n action: this.tasks.find((task) => task.id === id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n }\n\n /**\n * Create a task by providing an `action` name.\n *\n * this method creating the task, push it to the queue's tasks and trigger an event.\n * @param action\n */\n createTask(action: string) {\n const id = uuidv4();\n this.tasks.push({\n action,\n id,\n });\n this.state.tasks[id] = {\n status: Status.PENDING,\n blockedFor: null,\n };\n\n const createdTask = this.get(id);\n this.events.onCreate({\n id,\n task: createdTask!,\n action,\n });\n }\n\n /**\n * Initilize a queue with some tasks, instead of an empty queue.\n *\n * Using it for recover the queue state from persistor.\n *\n */\n public initTasks(info: InitTasks) {\n this.state = info.state;\n this.storage = info.storage;\n\n info.tasks.forEach((task) => {\n this.tasks.push(task);\n const action = this.tasks.find((t) => t.id === task.id)!.action;\n this.events.onCreate({\n id: task.id,\n task: this.get(task.id)!,\n action,\n });\n });\n }\n\n public checkBlock() {\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n return;\n }\n const { task, state } = currentActiveTask;\n\n if (state.status === Status.BLOCKED) {\n this.events.onBlock({\n action: task.action,\n id: task.id,\n reason: state.blockedFor,\n });\n }\n }\n\n /**\n * Getting task state by ID\n */\n public get(id: string): TaskState | null {\n const task = this.state.tasks[id];\n\n if (!task) return null;\n\n return task;\n }\n\n /**\n *\n * Checking if status of the last is `SUCCESS` or not\n *\n */\n private lastTaskIsSuccessful() {\n const lastTask = this.tasks[this.tasks.length - 1];\n\n // checking for empty lists.\n if (lastTask) {\n const lastTaskState = this.state.tasks[lastTask.id];\n\n // Maybe we didn't create the state yet. It should has success status as well.\n if (!!lastTaskState && lastTaskState.status === Status.SUCCESS) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * If the first task started (it's not PENDING),\n * it means the queue has been ran.\n *\n * @returns\n */\n private firstTaskIsStarted() {\n const firstTask = this.tasks[0];\n\n // checking for empty lists.\n if (firstTask) {\n const firstTaskState = this.state.tasks[firstTask.id];\n\n // Maybe we didn't create the state yet.\n if (!!firstTaskState) {\n if (firstTaskState.status !== Status.PENDING) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Getting active task index from state and\n * returns the task and its state.\n *\n */\n private getActiveTask() {\n // First try to get task with `activeTask`\n const index = this.state.activeTaskIndex;\n const task = this.tasks[index];\n\n // Consider all the tasks has been executed.\n if (!task) {\n return null;\n }\n\n const state = this.state.tasks[task.id];\n\n return { task, state, index };\n }\n\n /**\n * Update and find the queue status by checking state of each tasks in the queue.\n */\n public check() {\n const currentListStatus = this.state.status;\n let nextListStatus = this.firstTaskIsStarted()\n ? Status.RUNNING\n : Status.PENDING;\n\n if (this.lastTaskIsSuccessful()) {\n nextListStatus = Status.SUCCESS;\n } else {\n // Is there any failed task?\n for (const task of this.tasks) {\n const state = this.state.tasks[task.id];\n\n // If one item fails, we stop to work on the list.\n if (state.status === Status.FAILED) {\n nextListStatus = Status.FAILED;\n break;\n }\n }\n }\n\n // We only update and trigger an event when there is a new value\n if (nextListStatus !== currentListStatus) {\n this.updateQueueStatus(nextListStatus);\n }\n }\n\n /**\n * Execute active task.\n * Based on the state of active task, the behaviour is different. If status is:\n * - Success -> we need to go to next task by updating the active index and try `next` on more time.\n * - Failed, Running, or no active task -> doesn't do anything.\n * - Pending or Blocked -> update the task and queue status to running, and execute the provided `action` for the task.\n *\n * The queue is a linked list somehow, active task means the pointer to where we are in the queue right now.\n *\n */\n public next(params: NextParams) {\n this.check();\n\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n return;\n }\n\n const {\n index: activeTaskIndex,\n task: activeTask,\n state: activeTaskState,\n } = currentActiveTask;\n\n // if `activeTask` is already done, we will go for next one.\n if (activeTaskState.status === Status.SUCCESS) {\n this.updateActiveTaskIndex(activeTaskIndex + 1);\n this.next(params);\n return;\n }\n\n if (\n [Status.FAILED, Status.CANCELED, Status.RUNNING].includes(\n activeTaskState.status\n )\n ) {\n return;\n }\n\n if (\n activeTaskState.status === Status.PENDING ||\n activeTaskState.status === Status.BLOCKED\n ) {\n // Update task status to `running`\n this.updateTaskState(activeTask.id, {\n status: Status.RUNNING,\n });\n this.updateQueueStatus(Status.RUNNING);\n\n // Try to execute task.\n const execute = this.actions[activeTask.action];\n execute({\n context: this.getContext(params),\n next: () => {\n this.markCurrentTaskAsFinished(params);\n },\n retry: () => {\n this.resume(params);\n },\n failed: () => {\n this.updateTaskState(activeTask.id, {\n status: Status.FAILED,\n });\n this.check();\n },\n schedule: (action) => {\n this.createTask(action);\n this.check();\n },\n getStorage: this.getStorage.bind(this),\n setStorage: this.setStorage.bind(this),\n block: (reason: Record<string, unknown>) => {\n this.block({ reason });\n },\n unblock: () => {\n this.unblock();\n },\n });\n }\n }\n\n /**\n * Change the `status` of active task and queue to BLOCKED, then trigger an event.\n */\n public block({\n reason,\n silent = false,\n }: {\n reason: Record<string, unknown>;\n silent?: boolean;\n }) {\n const currentActiveTask = this.getActiveTask();\n\n if (!currentActiveTask) {\n throw new Error(\"Task isn't exist.\");\n }\n\n this.updateTaskState(currentActiveTask.task.id, {\n status: Status.BLOCKED,\n blockedFor: reason,\n });\n this.updateQueueStatus(Status.BLOCKED);\n\n if (!silent) {\n this.events.onBlock({\n action: currentActiveTask.task.action,\n id: currentActiveTask.task.id,\n reason,\n });\n }\n }\n\n /**\n * If the active task is `BLOCKED`, update the task status to `PENDING`, queue status to `RUNNING`\n * then trigger an event.\n */\n public unblock() {\n const currentActiveTask = this.getActiveTask();\n\n if (\n !currentActiveTask ||\n currentActiveTask.state.status !== Status.BLOCKED\n ) {\n throw new Error('Task is not blocked.');\n }\n\n this.updateTaskState(currentActiveTask.task.id, {\n status: Status.PENDING,\n });\n this.updateQueueStatus(Status.RUNNING);\n this.events.onUnblock({ id: currentActiveTask.task.id });\n }\n\n /**\n * If the active task is `BLOCKED` then execute the `action` for the task.\n *\n * It is useful for when we need to run a blocked task without changing the status of task at the first place.\n * For scenarios like we have some conditions in `action` and needs to run the `action` again\n * to check the conditions are met or not, if yes, so we can proceed the `action`.\n *\n */\n public forceRun(params: NextParams) {\n const currentTask = this.getActiveTask();\n\n if (!currentTask || currentTask.state.status !== Status.BLOCKED) {\n throw new Error('Task is not blocked.');\n }\n\n // Try to execute task.\n const execute = this.actions[currentTask.task.action];\n execute({\n context: this.getContext(params),\n next: () => {\n /*\n NOTE:\n When running `forceRun`, the status of task can be `BLOCKED`\n So we need to change to `Running` first. \n */\n // Update task status to `running`\n this.updateTaskState(currentTask.task.id, {\n status: Status.RUNNING,\n });\n this.updateQueueStatus(Status.RUNNING);\n\n this.markCurrentTaskAsFinished(params);\n },\n retry: () => {\n this.resume(params);\n },\n failed: () => {\n this.updateTaskState(currentTask.task.id, {\n status: Status.FAILED,\n });\n this.check();\n },\n schedule: (action) => {\n this.createTask(action);\n this.check();\n },\n getStorage: this.getStorage.bind(this),\n setStorage: this.setStorage.bind(this),\n block: (reason: Record<string, unknown>) => {\n this.block({ reason });\n },\n unblock: () => {\n this.unblock();\n },\n });\n }\n private markCurrentTaskAsFinished(params: NextParams) {\n this.check();\n const activeTaskIndex = this.state.activeTaskIndex;\n const activeTask = this.tasks[activeTaskIndex];\n\n if (!activeTask) return;\n\n const activeTaskState = this.state.tasks[activeTask.id];\n if (activeTaskState.status === Status.RUNNING) {\n this.updateTaskState(activeTask.id, {\n status: Status.SUCCESS,\n });\n this.updateActiveTaskIndex(activeTaskIndex + 1);\n\n const updatedTaskEvent = {\n id: activeTask.id,\n task: this.get(activeTask.id)!,\n action: this.tasks.find((task) => task.id === activeTask.id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n this.next(params);\n }\n }\n\n /**\n * If the active task is `RUNNING`, change it to `PENING` the try to run the task by calling `next`.\n * If it's other than `RUNNING` we reset the queue state and run the queue from the beggining.\n *\n * @param params\n * @returns\n */\n public resume(params: NextParams) {\n const activeTaskIndex = this.state.activeTaskIndex;\n const activeTask = this.tasks[activeTaskIndex];\n if (!activeTask) return;\n\n const activeTaskState = this.state.tasks[activeTask.id];\n if (activeTaskState.status === Status.RUNNING) {\n this.updateTaskState(activeTask.id, {\n status: Status.PENDING,\n });\n this.next(params);\n } else {\n this.resetState();\n this.next(params);\n }\n }\n\n /**\n *\n * Cancel the queue by changing active task and queue status to `CANCELED`.\n *\n */\n public cancel() {\n const currentActiveTask = this.getActiveTask();\n\n if (\n !currentActiveTask ||\n [Status.FAILED, Status.CANCELED, Status.SUCCESS].includes(\n currentActiveTask.state.status\n )\n ) {\n return;\n }\n\n const { task } = currentActiveTask;\n\n // Update task status to `canceled`\n this.updateTaskState(task.id, {\n status: Status.CANCELED,\n });\n const updatedTaskEvent = {\n id: task.id,\n task: this.get(task.id)!,\n action: this.tasks.find((t) => t.id === task.id)!.action,\n };\n this.events.onUpdate(updatedTaskEvent);\n\n // Update queue status to `canceled`\n this.updateQueueStatus(Status.CANCELED);\n }\n\n /**\n * Update queue status, and all the tasks inside queue to `PENDING`.\n */\n private resetState() {\n this.state.activeTaskIndex = 0;\n this.state.status = Status.PENDING;\n Object.keys(this.state.tasks).forEach((id) => {\n this.state.tasks[id].status = Status.PENDING;\n });\n }\n\n public getStorage() {\n return this.storage;\n }\n public setStorage(data: QueueStorage) {\n this.storage = data;\n this.events.onStorageUpdate(data);\n return this.storage;\n }\n\n private getContext(params: NextParams): QueueContext & ManagerContext {\n return {\n ...params.context,\n _queue: {\n id: this.id,\n },\n };\n }\n}\n\nexport default Queue;\n", "import type { QueueID, QueueName } from './manager';\nimport type { QueueState, Task } from './queue';\nimport type Queue from './queue';\n\nexport enum Status {\n PENDING = 'PENDING',\n RUNNING = 'RUNNING',\n FAILED = 'FAILED',\n SUCCESS = 'SUCCESS',\n CANCELED = 'CANCELED',\n BLOCKED = 'BLOCKED',\n}\n\nexport const SYNC_POLLING_INTERVAL = 5_000;\n\nexport type QueueStorage = Record<string, unknown>;\n\nexport type QueueType = Queue;\n\nexport interface PersistedQueue {\n id: QueueID;\n createdAt: number;\n name: QueueName;\n status: Status;\n state: QueueState;\n tasks: Task[];\n storage: QueueStorage;\n}\n"],
|
|
5
|
+
"mappings": "+EAGA,OAAS,MAAMA,MAAc,OCCtB,IAAMC,EAAU,iBACjBC,EAAoB,SAc1B,IAAMC,EAAN,KAAgB,CAnBhB,MAmBgB,CAAAC,EAAA,kBAEd,aAAc,CACZ,KAAK,GAAK,OAAO,KAAK,EACnB,KAAK,MAAOC,GACJA,EAAI,OAAiBC,EAAS,EAAS,CAC5C,QAAQC,EAAI,CACVA,EAAG,kBAAkBC,EAAmB,CAAE,QAAS,IAAK,CAAC,C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K,MACpB,KAAK,UAAU,YAAYR,EAAU,CACxC,OAAAkB,EACA,MAAAG,EACA,MAAAE,EACA,QAASf,EAAM,KAAK,WAAW,CACjC,CAAC,CACH,CACF,CAEQ,YAAa,CAGnB,OAAO,KAAK,SAAS,SAAW,CAAC,CACnC,CAEQ,eAAgB,CACtB,MAAO,CAAC,KAAK,QACf,CACF",
|
|
6
6
|
"names": ["uuidv4", "DB_NAME", "OBJECT_STORE_NAME", "Persistor", "__name", "idb", "DB_NAME", "db", "OBJECT_STORE_NAME", "queue", "id", "currentRecord", "updatedRecord", "persistor_default", "uuidv4", "Status", "SYNC_POLLING_INTERVAL", "Queue", "options", "__name", "status", "index", "id", "nextState", "updatedTaskEvent", "task", "action", "uuidv4", "createdTask", "info", "t", "currentActiveTask", "state", "lastTask", "lastTaskState", "firstTask", "firstTaskState", "currentListStatus", "nextListStatus", "params", "activeTaskIndex", "activeTask", "activeTaskState", "execute", "reason", "silent", "currentTask", "data", "queue_default", "Manager", "options", "defaultEventHandlers", "qDef", "persistor_default", "__name", "name", "storage", "def", "queue_id", "uuidv4", "createdAt", "list", "createdQueue", "args", "action", "e", "queue", "q", "data", "context", "queues", "info", "queue_name", "manager", "queue_default", "task", "status", "event", "blockedTasks", "state", "id", "tasks"]
|
|
7
7
|
}
|
package/dist/manager.d.ts
CHANGED
|
@@ -5,11 +5,12 @@ import { Status } from './types';
|
|
|
5
5
|
export type ManagerContext = object;
|
|
6
6
|
export type QueueName = string;
|
|
7
7
|
export type QueueID = string;
|
|
8
|
+
export type BlockedReason = Record<string, unknown>;
|
|
8
9
|
export type BlockedTask = {
|
|
9
10
|
queue_id: string;
|
|
10
11
|
task_id: string;
|
|
11
12
|
action: string;
|
|
12
|
-
reason:
|
|
13
|
+
reason: BlockedReason;
|
|
13
14
|
storage: {
|
|
14
15
|
get: () => QueueStorage;
|
|
15
16
|
set: (data: QueueStorage) => QueueStorage;
|
|
@@ -23,10 +24,11 @@ export interface ExecuterActions<T extends QueueStorage = QueueStorage, V extend
|
|
|
23
24
|
schedule: (actionName: V) => void;
|
|
24
25
|
setStorage: SetStorage<T>;
|
|
25
26
|
getStorage: () => T;
|
|
26
|
-
block: (reason:
|
|
27
|
+
block: (reason: BlockedReason) => void;
|
|
27
28
|
unblock: () => void;
|
|
28
29
|
context: C;
|
|
29
30
|
}
|
|
31
|
+
type WhenTaskBlockedEvent = any;
|
|
30
32
|
export interface QueueDef<T extends QueueStorage = QueueStorage, V extends string = string, C = ManagerContext> {
|
|
31
33
|
name: QueueName;
|
|
32
34
|
actions: {
|
|
@@ -34,7 +36,7 @@ export interface QueueDef<T extends QueueStorage = QueueStorage, V extends strin
|
|
|
34
36
|
};
|
|
35
37
|
events?: Partial<QueueEventHandlers>;
|
|
36
38
|
run: V[];
|
|
37
|
-
whenTaskBlocked?: (event:
|
|
39
|
+
whenTaskBlocked?: (event: WhenTaskBlockedEvent, params: {
|
|
38
40
|
queue_id: string;
|
|
39
41
|
queue: Queue;
|
|
40
42
|
context: C;
|
|
@@ -62,6 +64,7 @@ interface ManagerOptions {
|
|
|
62
64
|
context?: ManagerContext;
|
|
63
65
|
isPaused?: boolean;
|
|
64
66
|
}
|
|
67
|
+
type _Storage = any;
|
|
65
68
|
export interface QueueInfo {
|
|
66
69
|
name: QueueName;
|
|
67
70
|
createdAt: number;
|
|
@@ -70,8 +73,8 @@ export interface QueueInfo {
|
|
|
70
73
|
actions: {
|
|
71
74
|
run: () => void;
|
|
72
75
|
cancel: () => void;
|
|
73
|
-
setStorage: SetStorage<
|
|
74
|
-
getStorage: () =>
|
|
76
|
+
setStorage: SetStorage<_Storage>;
|
|
77
|
+
getStorage: () => _Storage;
|
|
75
78
|
};
|
|
76
79
|
}
|
|
77
80
|
declare class Manager {
|
package/dist/manager.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../src/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB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":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/types.ts":{"bytes":601,"imports":[],"format":"esm"},"src/queue.ts":{"bytes":14782,"imports":[{"path":"uuid","kind":"import-statement","external":true},{"path":"./manager","kind":"import-statement","external":true},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/manager.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/persistor.ts":{"bytes":1834,"imports":[{"path":"idb","kind":"dynamic-import","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/types.ts":{"bytes":601,"imports":[],"format":"esm"},"src/queue.ts":{"bytes":14782,"imports":[{"path":"uuid","kind":"import-statement","external":true},{"path":"./manager","kind":"import-statement","external":true},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/manager.ts":{"bytes":16794,"imports":[{"path":"uuid","kind":"import-statement","external":true},{"path":"src/persistor.ts","kind":"import-statement","original":"./persistor"},{"path":"src/queue.ts","kind":"import-statement","original":"./queue"},{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":158,"imports":[{"path":"src/manager.ts","kind":"import-statement","original":"./manager"},{"path":"src/persistor.ts","kind":"import-statement","original":"./persistor"},{"path":"src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"dist/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":48633},"dist/index.js":{"imports":[{"path":"uuid","kind":"import-statement","external":true},{"path":"idb","kind":"dynamic-import","external":true},{"path":"uuid","kind":"import-statement","external":true}],"exports":["DB_NAME","Manager","Persistor","SYNC_POLLING_INTERVAL","Status"],"entryPoint":"src/index.ts","inputs":{"src/manager.ts":{"bytesInOutput":4564},"src/persistor.ts":{"bytesInOutput":568},"src/queue.ts":{"bytesInOutput":4844},"src/types.ts":{"bytesInOutput":148},"src/index.ts":{"bytesInOutput":0}},"bytes":10326}}}
|
package/package.json
CHANGED
package/src/manager.ts
CHANGED
|
@@ -10,11 +10,13 @@ import { Status, SYNC_POLLING_INTERVAL } from './types';
|
|
|
10
10
|
export type ManagerContext = object;
|
|
11
11
|
export type QueueName = string;
|
|
12
12
|
export type QueueID = string;
|
|
13
|
+
|
|
14
|
+
export type BlockedReason = Record<string, unknown>;
|
|
13
15
|
export type BlockedTask = {
|
|
14
16
|
queue_id: string;
|
|
15
17
|
task_id: string;
|
|
16
18
|
action: string;
|
|
17
|
-
reason:
|
|
19
|
+
reason: BlockedReason;
|
|
18
20
|
storage: {
|
|
19
21
|
get: () => QueueStorage;
|
|
20
22
|
set: (data: QueueStorage) => QueueStorage;
|
|
@@ -34,11 +36,13 @@ export interface ExecuterActions<
|
|
|
34
36
|
schedule: (actionName: V) => void;
|
|
35
37
|
setStorage: SetStorage<T>;
|
|
36
38
|
getStorage: () => T;
|
|
37
|
-
block: (reason:
|
|
39
|
+
block: (reason: BlockedReason) => void;
|
|
38
40
|
unblock: () => void;
|
|
39
41
|
context: C;
|
|
40
42
|
}
|
|
41
43
|
|
|
44
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
45
|
+
type WhenTaskBlockedEvent = any;
|
|
42
46
|
export interface QueueDef<
|
|
43
47
|
T extends QueueStorage = QueueStorage,
|
|
44
48
|
V extends string = string,
|
|
@@ -51,7 +55,7 @@ export interface QueueDef<
|
|
|
51
55
|
events?: Partial<QueueEventHandlers>;
|
|
52
56
|
run: V[];
|
|
53
57
|
whenTaskBlocked?: (
|
|
54
|
-
event:
|
|
58
|
+
event: WhenTaskBlockedEvent,
|
|
55
59
|
params: {
|
|
56
60
|
queue_id: string;
|
|
57
61
|
queue: Queue;
|
|
@@ -82,6 +86,8 @@ interface ManagerOptions {
|
|
|
82
86
|
isPaused?: boolean;
|
|
83
87
|
}
|
|
84
88
|
|
|
89
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
90
|
+
type _Storage = any;
|
|
85
91
|
export interface QueueInfo {
|
|
86
92
|
name: QueueName;
|
|
87
93
|
createdAt: number;
|
|
@@ -90,8 +96,8 @@ export interface QueueInfo {
|
|
|
90
96
|
actions: {
|
|
91
97
|
run: () => void;
|
|
92
98
|
cancel: () => void;
|
|
93
|
-
setStorage: SetStorage<
|
|
94
|
-
getStorage: () =>
|
|
99
|
+
setStorage: SetStorage<_Storage>;
|
|
100
|
+
getStorage: () => _Storage;
|
|
95
101
|
};
|
|
96
102
|
}
|
|
97
103
|
|
|
@@ -240,6 +246,7 @@ class Manager {
|
|
|
240
246
|
this.execute();
|
|
241
247
|
return queue_id;
|
|
242
248
|
} catch (e) {
|
|
249
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
243
250
|
throw new Error((e as any)?.message);
|
|
244
251
|
}
|
|
245
252
|
}
|
|
@@ -643,7 +650,7 @@ class Manager {
|
|
|
643
650
|
}
|
|
644
651
|
|
|
645
652
|
private getContext() {
|
|
646
|
-
// eslint-disable-next-line @typescript-eslint/
|
|
653
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
647
654
|
//@ts-ignore
|
|
648
655
|
return this.context?.current || {};
|
|
649
656
|
}
|