@mrjacket/ahko 0.3.0 → 0.5.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 +28 -0
- package/README.md +59 -3
- package/dist/ahko.d.ts +23 -7
- package/dist/errors/timeout.error.d.ts +15 -2
- package/dist/index.cjs +651 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +649 -54
- package/dist/index.js.map +1 -1
- package/dist/models/options.model.d.ts +24 -0
- package/dist/models/strategy.model.d.ts +6 -2
- package/dist/scheduler/debounce-coordinator.d.ts +41 -0
- package/dist/scheduler/signal.d.ts +20 -0
- package/dist/scheduler/task-queue.d.ts +16 -3
- package/dist/scheduler/task-runner.d.ts +17 -8
- package/dist/scheduler/throttle-coordinator.d.ts +43 -0
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/strategy.model.ts","../src/models/state.model.ts","../src/retry/backoff.ts","../src/scheduler/idle-scheduler.ts","../src/scheduler/task-queue.ts","../src/errors/cancellation.error.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/errors/timeout.error.ts"],"sourcesContent":["/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n /** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */\n IDLE = \"idle\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy = EScheduleStrategy | \"immediate\" | \"delay\" | \"idle\";\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","import type { IRetryOptions } from \"../models/retry.model.js\";\n\n/**\n * Default base delay for backoff calculations in milliseconds.\n */\nexport const DEFAULT_BASE_DELAY = 250;\n\n/**\n * Default maximum delay ceiling for backoff calculations in milliseconds.\n */\nexport const DEFAULT_MAX_DELAY = 10_000;\n\n/**\n * Computes backoff delay in milliseconds for a retry attempt based on configured policy.\n *\n * @param attempt - 1-based index of the attempt that failed (1 for first failure, 2 for second, etc.).\n * @param options - Retry configuration options.\n * @param randomFn - Injectable random generator function (defaults to Math.random) for deterministic testing.\n * @returns Delay duration in milliseconds before next attempt.\n */\nexport function calculateBackoff(\n attempt: number,\n options?: IRetryOptions,\n randomFn: () => number = Math.random\n): number {\n const backoff = options?.backoff ?? \"exponential\";\n\n if (backoff === \"none\") {\n return 0;\n }\n\n const baseDelay =\n typeof options?.baseDelay === \"number\" && !Number.isNaN(options.baseDelay) && options.baseDelay >= 0\n ? options.baseDelay\n : DEFAULT_BASE_DELAY;\n\n const maxDelay =\n typeof options?.maxDelay === \"number\" && !Number.isNaN(options.maxDelay) && options.maxDelay >= baseDelay\n ? options.maxDelay\n : Math.max(DEFAULT_MAX_DELAY, baseDelay);\n\n let calculatedDelay: number;\n\n if (backoff === \"linear\") {\n calculatedDelay = baseDelay * Math.max(1, attempt);\n } else {\n // exponential: baseDelay * 2^(attempt - 1)\n const exponent = Math.max(0, attempt - 1);\n // Prevent 2^exponent overflow\n const factor = exponent > 30 ? 2 ** 30 : 2 ** exponent;\n calculatedDelay = baseDelay * factor;\n }\n\n const cappedDelay = Math.min(calculatedDelay, maxDelay);\n\n if (options?.jitter) {\n // Full jitter: uniformly random between 0 and cappedDelay\n return Math.floor(randomFn() * (cappedDelay + 1));\n }\n\n return Math.floor(cappedDelay);\n}\n","/**\n * Handle returned by the IdleScheduler allowing cancellation of an idle request.\n */\nexport interface IIdleHandle {\n /**\n * Cancels the scheduled idle callback and cleans up platform resources.\n */\n cancel(): void;\n}\n\n/**\n * Platform-agnostic scheduler for opportunistic idle task execution.\n *\n * Automatically detects and selects platform capabilities:\n * 1. Browser: `requestIdleCallback` / `cancelIdleCallback` (with optional timeout)\n * 2. Node.js: `setImmediate` / `clearImmediate` as low-priority primitive\n * 3. Fallback: `setTimeout(..., 0)` / `clearTimeout`\n */\nexport class IdleScheduler {\n /**\n * Schedules a callback to execute during the next idle opportunity.\n *\n * @param callback - Function to invoke when idle opportunity arises.\n * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).\n * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).\n * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.\n */\n public static schedule(\n callback: () => void,\n timeout?: number,\n runtime: typeof globalThis = globalThis\n ): IIdleHandle {\n // 1. Browser requestIdleCallback\n if (\n typeof (runtime as Record<string, unknown>).requestIdleCallback === \"function\" &&\n typeof (runtime as Record<string, unknown>).cancelIdleCallback === \"function\"\n ) {\n const requestFn = (runtime as Record<string, unknown>).requestIdleCallback as (\n cb: (deadline?: unknown) => void,\n opts?: { timeout?: number }\n ) => number;\n\n const cancelFn = (runtime as Record<string, unknown>).cancelIdleCallback as (\n handle: number\n ) => void;\n\n const id = requestFn(\n () => callback(),\n typeof timeout === \"number\" && !Number.isNaN(timeout) && timeout >= 0\n ? { timeout }\n : undefined\n );\n\n return {\n cancel: () => cancelFn(id),\n };\n }\n\n // 2. Node.js setImmediate\n if (\n typeof (runtime as Record<string, unknown>).setImmediate === \"function\" &&\n typeof (runtime as Record<string, unknown>).clearImmediate === \"function\"\n ) {\n const setImmFn = (runtime as Record<string, unknown>).setImmediate as (\n cb: () => void\n ) => ReturnType<typeof setImmediate>;\n\n const clearImmFn = (runtime as Record<string, unknown>).clearImmediate as (\n handle: ReturnType<typeof setImmediate>\n ) => void;\n\n const handle = setImmFn(() => callback());\n\n return {\n cancel: () => clearImmFn(handle),\n };\n }\n\n // 3. Universal fallback setTimeout(0)\n const setTimerFn = runtime.setTimeout.bind(runtime);\n const clearTimerFn = runtime.clearTimeout.bind(runtime);\n\n const timerId = setTimerFn(() => callback(), 0);\n\n return {\n cancel: () => clearTimerFn(timerId),\n };\n }\n}\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { calculateBackoff } from \"../retry/backoff.js\";\nimport { IdleScheduler, type IIdleHandle } from \"./idle-scheduler.js\";\nimport { TaskRunner } from \"./task-runner.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Entry tracking idle callback handles for deterministic cancellation and cleanup.\n */\ninterface IIdleEntry {\n runner: TaskRunner<unknown>;\n handle: IIdleHandle;\n}\n\n/**\n * Entry tracking backoff delay timers for retry attempts.\n */\ninterface IRetryEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Set of tasks currently awaiting an idle opportunity */\n private readonly idleEntries = new Set<IIdleEntry>();\n\n /** Set of tasks currently awaiting a retry backoff timer */\n private readonly retryEntries = new Set<IRetryEntry>();\n\n /** WeakMap associating task runners with their scheduling options */\n private readonly runnerOptions = new WeakMap<TaskRunner<unknown>, IScheduleOptions>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or not a valid number.\n */\n constructor(concurrency = Infinity) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n this.concurrency = concurrency;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (\n strategy !== EScheduleStrategy.IMMEDIATE &&\n strategy !== EScheduleStrategy.DELAY &&\n strategy !== EScheduleStrategy.IDLE\n ) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies: \"immediate\", \"delay\", \"idle\".`\n );\n }\n\n if (options?.retry) {\n if (\n typeof options.retry.attempts !== \"number\" ||\n Number.isNaN(options.retry.attempts) ||\n options.retry.attempts < 1 ||\n !Number.isInteger(options.retry.attempts)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry attempts \"${options.retry.attempts}\". attempts must be an integer greater than or equal to 1.`\n );\n }\n\n if (\n options.retry.baseDelay !== undefined &&\n (typeof options.retry.baseDelay !== \"number\" ||\n Number.isNaN(options.retry.baseDelay) ||\n options.retry.baseDelay < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry baseDelay \"${options.retry.baseDelay}\". baseDelay must be a non-negative number in milliseconds.`\n );\n }\n\n if (\n options.retry.maxDelay !== undefined &&\n (typeof options.retry.maxDelay !== \"number\" ||\n Number.isNaN(options.retry.maxDelay) ||\n options.retry.maxDelay < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry maxDelay \"${options.retry.maxDelay}\". maxDelay must be a non-negative number in milliseconds.`\n );\n }\n }\n\n if (options) {\n this.runnerOptions.set(runner as TaskRunner<unknown>, options);\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.IDLE) {\n if (\n options?.idleTimeout !== undefined &&\n (typeof options.idleTimeout !== \"number\" ||\n Number.isNaN(options.idleTimeout) ||\n options.idleTimeout < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid idleTimeout \"${options.idleTimeout}\". idleTimeout must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleIdle(runner as TaskRunner<unknown>, options?.idleTimeout);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Schedules a task to be placed into the queue during an idle opportunity,\n * handling early cancellation safely.\n */\n private scheduleIdle(runner: TaskRunner<unknown>, idleTimeout?: number): void {\n let idleEntry!: IIdleEntry;\n\n const handle = IdleScheduler.schedule(() => {\n this.idleEntries.delete(idleEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, idleTimeout);\n\n idleEntry = { runner, handle };\n this.idleEntries.add(idleEntry);\n\n runner.onCancel = () => {\n if (this.idleEntries.has(idleEntry)) {\n handle.cancel();\n this.idleEntries.delete(idleEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available.\n */\n private pump(): void {\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n }\n }\n\n /**\n * Internal execution of an active task runner.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n const options = this.runnerOptions.get(runner);\n\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.reject(error);\n return;\n }\n\n const shouldRetry = await runner.canRetry(error, options?.retry);\n if (shouldRetry) {\n // Free concurrency slot immediately during backoff\n this.activeRunners.delete(runner);\n this.scheduleRetry(runner, options);\n return;\n }\n\n if (runner.state === ETaskState.TIMED_OUT) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Schedules a retry attempt following backoff delay,\n * without holding a concurrency slot.\n */\n private scheduleRetry(runner: TaskRunner<unknown>, options?: IScheduleOptions): void {\n const backoffDelay = calculateBackoff(runner.attempt - 1, options?.retry);\n\n if (backoffDelay === 0) {\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n this.queue.push(runner);\n this.pump();\n return;\n }\n\n const retryEntry: IRetryEntry = {\n runner,\n timerId: setTimeout(() => {\n this.retryEntries.delete(retryEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, backoffDelay),\n };\n\n this.retryEntries.add(retryEntry);\n\n runner.onCancel = () => {\n if (this.retryEntries.has(retryEntry)) {\n clearTimeout(retryEntry.timerId);\n this.retryEntries.delete(retryEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks:\n this.queue.length +\n this.delayedEntries.size +\n this.idleEntries.size +\n this.retryEntries.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport type { IRetryOptions } from \"../models/retry.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private readonly abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n private readonly externalSignal?: AbortSignal;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /** Current execution attempt count (1-indexed) */\n public attempt = 1;\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.cleanup();\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.cleanup();\n this.rejectPromise(reason);\n }\n\n /**\n * Evaluates if the task should be retried following an execution failure.\n *\n * @param error - The error encountered during the attempt.\n * @param retryOptions - Configured retry policy.\n * @returns A promise resolving to true if retry should proceed, false otherwise.\n */\n public async canRetry(error: unknown, retryOptions?: IRetryOptions): Promise<boolean> {\n if (this._state === ETaskState.CANCELLED || this.abortController.signal.aborted) {\n return false;\n }\n\n if (!retryOptions || typeof retryOptions.attempts !== \"number\") {\n return false;\n }\n\n if (this.attempt >= retryOptions.attempts) {\n return false;\n }\n\n if (typeof retryOptions.shouldRetry === \"function\") {\n try {\n const allowed = await retryOptions.shouldRetry(error, this.attempt);\n if (!allowed) {\n return false;\n }\n } catch {\n return false;\n }\n }\n\n this.attempt++;\n this._state = ETaskState.PENDING;\n return true;\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n try {\n const result = await this.task(context);\n this._state = ETaskState.COMPLETED;\n return result;\n } catch (error) {\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted;\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport { EScheduleStrategy } from \"./models/strategy.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const runner = new TaskRunner<T>(task, options?.signal);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Convenience method to schedule a task during platform idle opportunities.\n *\n * Equivalent to calling `schedule(task, { ...options, strategy: \"idle\" })`.\n * In browsers, uses `requestIdleCallback` when available.\n * In Node.js, uses `setImmediate`.\n * Falls back to `setTimeout(..., 0)` if neither is available.\n *\n * @template T - Inferred return type of the task.\n * @param task - Task function to run when idle.\n * @param options - Scheduling options (excluding strategy).\n * @returns A promise resolving to the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * const result = await ahko.idle(async ({ signal }) => {\n * return computeAnalytics();\n * });\n * ```\n */\n public idle<T>(\n task: ITask<T>,\n options?: Omit<IScheduleOptions, \"strategy\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.IDLE,\n });\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.3.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task execution timed out\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoTimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n"],"mappings":";AAGO,IAAM,YAAN,cAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACVO,IAAM,yBAAN,cAAqC,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,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,WAAO,KAAK,SAAS,MAAM;AAAA,MACzB,GAAG;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaO,QAAoB;AACzB,WAAO,KAAK,MAAM,SAAS;AAAA,EAC7B;AACF;;;ACzHO,IAAM,UAAU;;;ACEhB,IAAM,iBAAN,cAA6B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACZO,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9C,YAAY,UAAU,4BAA4B,SAAwB;AACxE,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;","names":["EScheduleStrategy","ETaskState"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/strategy.model.ts","../src/errors/timeout.error.ts","../src/models/state.model.ts","../src/retry/backoff.ts","../src/errors/cancellation.error.ts","../src/scheduler/debounce-coordinator.ts","../src/scheduler/idle-scheduler.ts","../src/scheduler/throttle-coordinator.ts","../src/scheduler/task-queue.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/scheduler/signal.ts"],"sourcesContent":["/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n /** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */\n IDLE = \"idle\",\n /** Enforce maximum execution frequency for tasks sharing the same key */\n THROTTLE = \"throttle\",\n /** Delay execution until calls sharing the same key stop arriving */\n DEBOUNCE = \"debounce\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy =\n | EScheduleStrategy\n | \"immediate\"\n | \"delay\"\n | \"idle\"\n | \"throttle\"\n | \"debounce\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Options for constructing an AhkoTimeoutError.\n */\nexport interface IAhkoTimeoutErrorOptions extends ErrorOptions {\n /**\n * The timeout threshold in milliseconds that was exceeded.\n */\n timeoutMs?: number;\n}\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * The timeout threshold in milliseconds that was exceeded, if configured.\n */\n public readonly timeoutMs?: number;\n\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including optional timeoutMs and cause.\n */\n constructor(\n message = \"Task execution timed out\",\n options?: IAhkoTimeoutErrorOptions\n ) {\n super(message, options);\n this.name = \"AhkoTimeoutError\";\n this.timeoutMs = options?.timeoutMs;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","import type { IRetryOptions } from \"../models/retry.model.js\";\n\n/**\n * Default base delay for backoff calculations in milliseconds.\n */\nexport const DEFAULT_BASE_DELAY = 250;\n\n/**\n * Default maximum delay ceiling for backoff calculations in milliseconds.\n */\nexport const DEFAULT_MAX_DELAY = 10_000;\n\n/**\n * Computes backoff delay in milliseconds for a retry attempt based on configured policy.\n *\n * @param attempt - 1-based index of the attempt that failed (1 for first failure, 2 for second, etc.).\n * @param options - Retry configuration options.\n * @param randomFn - Injectable random generator function (defaults to Math.random) for deterministic testing.\n * @returns Delay duration in milliseconds before next attempt.\n */\nexport function calculateBackoff(\n attempt: number,\n options?: IRetryOptions,\n randomFn: () => number = Math.random\n): number {\n const backoff = options?.backoff ?? \"exponential\";\n\n if (backoff === \"none\") {\n return 0;\n }\n\n const baseDelay =\n typeof options?.baseDelay === \"number\" && !Number.isNaN(options.baseDelay) && options.baseDelay >= 0\n ? options.baseDelay\n : DEFAULT_BASE_DELAY;\n\n const maxDelay =\n typeof options?.maxDelay === \"number\" && !Number.isNaN(options.maxDelay) && options.maxDelay >= baseDelay\n ? options.maxDelay\n : Math.max(DEFAULT_MAX_DELAY, baseDelay);\n\n let calculatedDelay: number;\n\n if (backoff === \"linear\") {\n calculatedDelay = baseDelay * Math.max(1, attempt);\n } else {\n // exponential: baseDelay * 2^(attempt - 1)\n const exponent = Math.max(0, attempt - 1);\n // Prevent 2^exponent overflow\n const factor = exponent > 30 ? 2 ** 30 : 2 ** exponent;\n calculatedDelay = baseDelay * factor;\n }\n\n const cappedDelay = Math.min(calculatedDelay, maxDelay);\n\n if (options?.jitter) {\n // Full jitter: uniformly random between 0 and cappedDelay\n return Math.floor(randomFn() * (cappedDelay + 1));\n }\n\n return Math.floor(cappedDelay);\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\n/**\n * Internal tracking entry for a coalesced debounced task.\n */\ninterface IDebounceEntry<T = unknown> {\n readonly key: string | symbol;\n task: ITask<T>;\n options?: IScheduleOptions;\n timerId: ReturnType<typeof setTimeout>;\n resolve: (value: T) => void;\n reject: (reason: unknown) => void;\n readonly promise: Promise<T>;\n abortListener?: () => void;\n}\n\n/**\n * Coordinates debounce execution with Promise coalescing by explicit key.\n *\n * Incoming calls with the same key extend the quiet window and share the\n * eventual execution Promise, guaranteeing that all callers receive the final result.\n */\nexport class DebounceCoordinator {\n private readonly entries = new Map<string | symbol, IDebounceEntry<unknown>>();\n\n /**\n * Schedules a task under the debounce strategy.\n *\n * @param key - Explicit identity key.\n * @param task - Work to execute once calls stop arriving.\n * @param waitMs - Quiet window duration in milliseconds.\n * @param options - Scheduling options.\n * @param dispatchFn - Callback invoked when the debounce window expires to dispatch the task to the queue.\n * @returns Shared promise that resolves/rejects with the final execution outcome.\n */\n public schedule<T>(\n key: string | symbol,\n task: ITask<T>,\n waitMs: number,\n options: IScheduleOptions | undefined,\n dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>\n ): Promise<T> {\n const existing = this.entries.get(key) as IDebounceEntry<T> | undefined;\n\n if (existing) {\n clearTimeout(existing.timerId);\n if (existing.options?.signal && existing.abortListener) {\n existing.options.signal.removeEventListener(\"abort\", existing.abortListener);\n }\n\n existing.task = task;\n existing.options = options;\n\n if (options?.signal?.aborted) {\n this.entries.delete(key);\n const err = new AhkoCancellationError(\n typeof options.signal.reason === \"string\"\n ? options.signal.reason\n : \"Debounced task was cancelled prior to execution\",\n { cause: options.signal.reason instanceof Error ? options.signal.reason : undefined }\n );\n existing.reject(err);\n return existing.promise;\n }\n\n if (options?.signal) {\n const listener = () => {\n this.cancel(key, options.signal?.reason);\n };\n existing.abortListener = listener;\n options.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n existing.timerId = setTimeout(() => {\n void this.flush(key, dispatchFn);\n }, waitMs);\n\n return existing.promise;\n }\n\n let resolvePromise!: (value: T) => void;\n let rejectPromise!: (reason: unknown) => void;\n\n const promise = new Promise<T>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n\n if (options?.signal?.aborted) {\n const err = new AhkoCancellationError(\n typeof options.signal.reason === \"string\"\n ? options.signal.reason\n : \"Debounced task was cancelled prior to execution\",\n { cause: options.signal.reason instanceof Error ? options.signal.reason : undefined }\n );\n rejectPromise(err);\n return promise;\n }\n\n let abortListener: (() => void) | undefined;\n if (options?.signal) {\n abortListener = () => {\n this.cancel(key, options.signal?.reason);\n };\n options.signal.addEventListener(\"abort\", abortListener, { once: true });\n }\n\n const timerId = setTimeout(() => {\n void this.flush(key, dispatchFn);\n }, waitMs);\n\n const entry: IDebounceEntry<T> = {\n key,\n task,\n options,\n timerId,\n resolve: resolvePromise,\n reject: rejectPromise,\n promise,\n abortListener,\n };\n\n this.entries.set(key, entry as IDebounceEntry<unknown>);\n return promise;\n }\n\n /**\n * Dispatches the coalesced task when the quiet window expires.\n */\n private async flush<T>(\n key: string | symbol,\n dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>\n ): Promise<void> {\n const entry = this.entries.get(key) as IDebounceEntry<T> | undefined;\n if (!entry) {\n return;\n }\n\n this.entries.delete(key);\n if (entry.options?.signal && entry.abortListener) {\n entry.options.signal.removeEventListener(\"abort\", entry.abortListener);\n }\n\n try {\n const result = await dispatchFn(entry.task, entry.options);\n entry.resolve(result);\n } catch (error) {\n entry.reject(error);\n }\n }\n\n /**\n * Cancels a pending debounced task by key.\n *\n * @param key - Identity key to cancel.\n * @param reason - Optional cancellation reason.\n */\n public cancel(key: string | symbol, reason?: unknown): void {\n const entry = this.entries.get(key);\n if (!entry) {\n return;\n }\n\n clearTimeout(entry.timerId);\n this.entries.delete(key);\n\n if (entry.options?.signal && entry.abortListener) {\n entry.options.signal.removeEventListener(\"abort\", entry.abortListener);\n }\n\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Debounced task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n entry.reject(cancelError);\n }\n\n /**\n * Number of pending debounced tasks waiting for quiet window expiry.\n */\n public get size(): number {\n return this.entries.size;\n }\n\n /**\n * Cancels all pending debounced entries and clears the map.\n */\n public clear(): void {\n for (const [key, entry] of this.entries) {\n clearTimeout(entry.timerId);\n if (entry.options?.signal && entry.abortListener) {\n entry.options.signal.removeEventListener(\"abort\", entry.abortListener);\n }\n entry.reject(new AhkoCancellationError(\"Debounced tasks cleared\"));\n }\n this.entries.clear();\n }\n}\n","/**\n * Handle returned by the IdleScheduler allowing cancellation of an idle request.\n */\nexport interface IIdleHandle {\n /**\n * Cancels the scheduled idle callback and cleans up platform resources.\n */\n cancel(): void;\n}\n\n/**\n * Platform-agnostic scheduler for opportunistic idle task execution.\n *\n * Automatically detects and selects platform capabilities:\n * 1. Browser: `requestIdleCallback` / `cancelIdleCallback` (with optional timeout)\n * 2. Node.js: `setImmediate` / `clearImmediate` as low-priority primitive\n * 3. Fallback: `setTimeout(..., 0)` / `clearTimeout`\n */\nexport class IdleScheduler {\n /**\n * Schedules a callback to execute during the next idle opportunity.\n *\n * @param callback - Function to invoke when idle opportunity arises.\n * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).\n * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).\n * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.\n */\n public static schedule(\n callback: () => void,\n timeout?: number,\n runtime: typeof globalThis = globalThis\n ): IIdleHandle {\n // 1. Browser requestIdleCallback\n if (\n typeof (runtime as Record<string, unknown>).requestIdleCallback === \"function\" &&\n typeof (runtime as Record<string, unknown>).cancelIdleCallback === \"function\"\n ) {\n const requestFn = (runtime as Record<string, unknown>).requestIdleCallback as (\n cb: (deadline?: unknown) => void,\n opts?: { timeout?: number }\n ) => number;\n\n const cancelFn = (runtime as Record<string, unknown>).cancelIdleCallback as (\n handle: number\n ) => void;\n\n const id = requestFn(\n () => callback(),\n typeof timeout === \"number\" && !Number.isNaN(timeout) && timeout >= 0\n ? { timeout }\n : undefined\n );\n\n return {\n cancel: () => cancelFn(id),\n };\n }\n\n // 2. Node.js setImmediate\n if (\n typeof (runtime as Record<string, unknown>).setImmediate === \"function\" &&\n typeof (runtime as Record<string, unknown>).clearImmediate === \"function\"\n ) {\n const setImmFn = (runtime as Record<string, unknown>).setImmediate as (\n cb: () => void\n ) => ReturnType<typeof setImmediate>;\n\n const clearImmFn = (runtime as Record<string, unknown>).clearImmediate as (\n handle: ReturnType<typeof setImmediate>\n ) => void;\n\n const handle = setImmFn(() => callback());\n\n return {\n cancel: () => clearImmFn(handle),\n };\n }\n\n // 3. Universal fallback setTimeout(0)\n const setTimerFn = runtime.setTimeout.bind(runtime);\n const clearTimerFn = runtime.clearTimeout.bind(runtime);\n\n const timerId = setTimerFn(() => callback(), 0);\n\n return {\n cancel: () => clearTimerFn(timerId),\n };\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\n/**\n * Internal tracking entry for throttled executions.\n */\ninterface IThrottleEntry<T = unknown> {\n readonly key: string | symbol;\n windowTimerId?: ReturnType<typeof setTimeout>;\n trailingTask?: ITask<T>;\n trailingOptions?: IScheduleOptions;\n trailingResolve?: (value: T) => void;\n trailingReject?: (reason: unknown) => void;\n trailingPromise?: Promise<T>;\n abortListener?: () => void;\n}\n\n/**\n * Coordinates throttle execution with leading execution, trailing execution,\n * and Promise coalescing by explicit key.\n *\n * Incoming calls with the same key within the throttle period coalesce into a\n * single shared trailing execution, preventing overload while ensuring callers\n * receive the final result.\n */\nexport class ThrottleCoordinator {\n private readonly entries = new Map<string | symbol, IThrottleEntry<unknown>>();\n\n /**\n * Schedules a task under the throttle strategy.\n *\n * @param key - Explicit identity key.\n * @param task - Work to execute.\n * @param waitMs - Throttle interval duration in milliseconds.\n * @param options - Scheduling options.\n * @param dispatchFn - Callback invoked to dispatch task execution into the queue.\n * @returns Promise resolving with the leading execution or coalesced trailing result.\n */\n public schedule<T>(\n key: string | symbol,\n task: ITask<T>,\n waitMs: number,\n options: IScheduleOptions | undefined,\n dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>\n ): Promise<T> {\n const existing = this.entries.get(key) as IThrottleEntry<T> | undefined;\n\n if (!existing) {\n // Leading execution: runs immediately\n const entry: IThrottleEntry<T> = {\n key,\n };\n\n entry.windowTimerId = setTimeout(() => {\n void this.onWindowExpire(key, waitMs, dispatchFn);\n }, waitMs);\n\n this.entries.set(key, entry as IThrottleEntry<unknown>);\n\n return dispatchFn(task, options);\n }\n\n // Trailing call within active window: coalesce with latest work\n existing.trailingTask = task;\n existing.trailingOptions = options;\n\n if (existing.trailingPromise) {\n return existing.trailingPromise;\n }\n\n let resolvePromise!: (value: T) => void;\n let rejectPromise!: (reason: unknown) => void;\n\n existing.trailingPromise = new Promise<T>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n existing.trailingResolve = resolvePromise;\n existing.trailingReject = rejectPromise;\n\n if (options?.signal) {\n const listener = () => {\n if (existing.trailingReject) {\n existing.trailingReject(\n new AhkoCancellationError(\"Throttled trailing task was cancelled\", {\n cause: options.signal?.reason instanceof Error ? options.signal.reason : undefined,\n })\n );\n existing.trailingTask = undefined;\n existing.trailingOptions = undefined;\n existing.trailingPromise = undefined;\n existing.trailingResolve = undefined;\n existing.trailingReject = undefined;\n }\n };\n existing.abortListener = listener;\n options.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n return existing.trailingPromise;\n }\n\n /**\n * Invoked when the throttle interval window timer expires.\n */\n private async onWindowExpire<T>(\n key: string | symbol,\n waitMs: number,\n dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>\n ): Promise<void> {\n const entry = this.entries.get(key) as IThrottleEntry<T> | undefined;\n if (!entry) {\n return;\n }\n\n if (entry.trailingTask) {\n const task = entry.trailingTask;\n const options = entry.trailingOptions;\n const resolve = entry.trailingResolve;\n const reject = entry.trailingReject;\n\n // Reset trailing slots for subsequent calls\n entry.trailingTask = undefined;\n entry.trailingOptions = undefined;\n entry.trailingPromise = undefined;\n entry.trailingResolve = undefined;\n entry.trailingReject = undefined;\n\n // Re-arm window timer for the trailing run\n entry.windowTimerId = setTimeout(() => {\n void this.onWindowExpire(key, waitMs, dispatchFn);\n }, waitMs);\n\n try {\n const result = await dispatchFn(task, options);\n resolve?.(result);\n } catch (error) {\n reject?.(error);\n }\n return;\n }\n\n // No trailing task arrived during the window: settle and delete key\n this.entries.delete(key);\n }\n\n /**\n * Cancels any pending trailing throttled task for a given key.\n *\n * @param key - Identity key to cancel.\n * @param reason - Optional cancellation reason.\n */\n public cancel(key: string | symbol, reason?: unknown): void {\n const entry = this.entries.get(key);\n if (!entry) {\n return;\n }\n\n if (entry.windowTimerId !== undefined) {\n clearTimeout(entry.windowTimerId);\n }\n this.entries.delete(key);\n\n if (entry.trailingReject) {\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Throttled task was cancelled\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n entry.trailingReject(cancelError);\n }\n }\n\n /**\n * Number of keys currently actively throttled.\n */\n public get size(): number {\n return this.entries.size;\n }\n\n /**\n * Clears all throttled entries and timers.\n */\n public clear(): void {\n for (const [key, entry] of this.entries) {\n if (entry.windowTimerId !== undefined) {\n clearTimeout(entry.windowTimerId);\n }\n if (entry.trailingReject) {\n entry.trailingReject(new AhkoCancellationError(\"Throttled tasks cleared\"));\n }\n }\n this.entries.clear();\n }\n}\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport { AhkoTimeoutError } from \"../errors/timeout.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { calculateBackoff } from \"../retry/backoff.js\";\nimport { DebounceCoordinator } from \"./debounce-coordinator.js\";\nimport { IdleScheduler, type IIdleHandle } from \"./idle-scheduler.js\";\nimport { TaskRunner } from \"./task-runner.js\";\nimport { ThrottleCoordinator } from \"./throttle-coordinator.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Entry tracking idle callback handles for deterministic cancellation and cleanup.\n */\ninterface IIdleEntry {\n runner: TaskRunner<unknown>;\n handle: IIdleHandle;\n}\n\n/**\n * Entry tracking backoff delay timers for retry attempts.\n */\ninterface IRetryEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Minimum interval in milliseconds between consecutive task starts */\n public readonly minIntervalMs: number;\n\n /** Timestamp of the most recent task start */\n private lastTaskStartTime = 0;\n\n /** Active rate limit timer for pacing consecutive tasks */\n private rateLimitTimer?: ReturnType<typeof setTimeout>;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Set of tasks currently awaiting an idle opportunity */\n private readonly idleEntries = new Set<IIdleEntry>();\n\n /** Set of tasks currently awaiting a retry backoff timer */\n private readonly retryEntries = new Set<IRetryEntry>();\n\n /** Coordinator for debounced tasks with key coalescing */\n public readonly debounceCoordinator = new DebounceCoordinator();\n\n /** Coordinator for throttled tasks with leading/trailing coalescing */\n public readonly throttleCoordinator = new ThrottleCoordinator();\n\n /** WeakMap associating task runners with their scheduling options */\n private readonly runnerOptions = new WeakMap<TaskRunner<unknown>, IScheduleOptions>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @param minIntervalMs - Minimum interval in milliseconds between task dispatches.\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or minIntervalMs is invalid.\n */\n constructor(concurrency = Infinity, minIntervalMs = 0) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n if (\n typeof minIntervalMs !== \"number\" ||\n Number.isNaN(minIntervalMs) ||\n !Number.isFinite(minIntervalMs) ||\n minIntervalMs < 0\n ) {\n throw new AhkoConfigurationError(\n `Invalid minIntervalMs \"${minIntervalMs}\". minIntervalMs must be a non-negative finite number.`\n );\n }\n this.concurrency = concurrency;\n this.minIntervalMs = minIntervalMs;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (\n strategy !== EScheduleStrategy.IMMEDIATE &&\n strategy !== EScheduleStrategy.DELAY &&\n strategy !== EScheduleStrategy.IDLE &&\n strategy !== EScheduleStrategy.THROTTLE &&\n strategy !== EScheduleStrategy.DEBOUNCE\n ) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies: \"immediate\", \"delay\", \"idle\", \"throttle\", \"debounce\".`\n );\n }\n\n if (strategy === EScheduleStrategy.THROTTLE || strategy === EScheduleStrategy.DEBOUNCE) {\n if (!options?.key || (typeof options.key !== \"string\" && typeof options.key !== \"symbol\")) {\n throw new AhkoConfigurationError(\n `Strategy \"${strategy}\" requires a valid \"key\" of type string or symbol.`\n );\n }\n const waitMs = options.waitMs ?? options.delay;\n if (typeof waitMs !== \"number\" || Number.isNaN(waitMs) || !Number.isFinite(waitMs) || waitMs < 0) {\n throw new AhkoConfigurationError(\n `Strategy \"${strategy}\" requires a non-negative finite \"waitMs\" or \"delay\" in milliseconds.`\n );\n }\n }\n\n if (options?.retry) {\n if (\n typeof options.retry.attempts !== \"number\" ||\n Number.isNaN(options.retry.attempts) ||\n options.retry.attempts < 1 ||\n !Number.isInteger(options.retry.attempts)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry attempts \"${options.retry.attempts}\". attempts must be an integer greater than or equal to 1.`\n );\n }\n\n if (\n options.retry.baseDelay !== undefined &&\n (typeof options.retry.baseDelay !== \"number\" ||\n Number.isNaN(options.retry.baseDelay) ||\n options.retry.baseDelay < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry baseDelay \"${options.retry.baseDelay}\". baseDelay must be a non-negative number in milliseconds.`\n );\n }\n\n if (\n options.retry.maxDelay !== undefined &&\n (typeof options.retry.maxDelay !== \"number\" ||\n Number.isNaN(options.retry.maxDelay) ||\n options.retry.maxDelay < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid retry maxDelay \"${options.retry.maxDelay}\". maxDelay must be a non-negative number in milliseconds.`\n );\n }\n }\n\n if (options?.timeoutMs !== undefined) {\n if (\n typeof options.timeoutMs !== \"number\" ||\n Number.isNaN(options.timeoutMs) ||\n !Number.isFinite(options.timeoutMs) ||\n options.timeoutMs <= 0\n ) {\n throw new AhkoConfigurationError(\n `Invalid timeoutMs \"${options.timeoutMs}\". timeoutMs must be a positive finite number greater than 0.`\n );\n }\n }\n\n if (options) {\n this.runnerOptions.set(runner as TaskRunner<unknown>, options);\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.IDLE) {\n if (\n options?.idleTimeout !== undefined &&\n (typeof options.idleTimeout !== \"number\" ||\n Number.isNaN(options.idleTimeout) ||\n options.idleTimeout < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid idleTimeout \"${options.idleTimeout}\". idleTimeout must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleIdle(runner as TaskRunner<unknown>, options?.idleTimeout);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Schedules a task to be placed into the queue during an idle opportunity,\n * handling early cancellation safely.\n */\n private scheduleIdle(runner: TaskRunner<unknown>, idleTimeout?: number): void {\n let idleEntry!: IIdleEntry;\n\n const handle = IdleScheduler.schedule(() => {\n this.idleEntries.delete(idleEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, idleTimeout);\n\n idleEntry = { runner, handle };\n this.idleEntries.add(idleEntry);\n\n runner.onCancel = () => {\n if (this.idleEntries.has(idleEntry)) {\n handle.cancel();\n this.idleEntries.delete(idleEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available and minIntervalMs is respected.\n */\n private pump(): void {\n if (this.queue.length === 0 || this.activeRunners.size >= this.concurrency) {\n return;\n }\n\n if (this.minIntervalMs > 0 && this.lastTaskStartTime > 0) {\n const now = Date.now();\n const elapsed = now - this.lastTaskStartTime;\n if (elapsed < this.minIntervalMs) {\n if (this.rateLimitTimer === undefined) {\n const delay = this.minIntervalMs - elapsed;\n this.rateLimitTimer = setTimeout(() => {\n this.rateLimitTimer = undefined;\n this.pump();\n }, delay);\n }\n return;\n }\n }\n\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n if (this.minIntervalMs > 0 && this.lastTaskStartTime > 0) {\n const now = Date.now();\n const elapsed = now - this.lastTaskStartTime;\n if (elapsed < this.minIntervalMs) {\n if (this.rateLimitTimer === undefined) {\n const delay = this.minIntervalMs - elapsed;\n this.rateLimitTimer = setTimeout(() => {\n this.rateLimitTimer = undefined;\n this.pump();\n }, delay);\n }\n break;\n }\n }\n\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n this.lastTaskStartTime = Date.now();\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n\n if (this.minIntervalMs > 0) {\n if (this.queue.length > 0 && this.activeRunners.size < this.concurrency) {\n if (this.rateLimitTimer === undefined) {\n this.rateLimitTimer = setTimeout(() => {\n this.rateLimitTimer = undefined;\n this.pump();\n }, this.minIntervalMs);\n }\n }\n break;\n }\n }\n }\n\n /**\n * Internal execution of an active task runner.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n const options = this.runnerOptions.get(runner);\n\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.reject(error);\n return;\n }\n\n const shouldRetry = await runner.canRetry(error, options?.retry);\n if (shouldRetry) {\n // Free concurrency slot immediately during backoff\n this.activeRunners.delete(runner);\n this.scheduleRetry(runner, options);\n return;\n }\n\n if (runner.state === ETaskState.TIMED_OUT || error instanceof AhkoTimeoutError) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n this.runnerOptions.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Schedules a retry attempt following backoff delay,\n * without holding a concurrency slot.\n */\n private scheduleRetry(runner: TaskRunner<unknown>, options?: IScheduleOptions): void {\n const backoffDelay = calculateBackoff(runner.attempt - 1, options?.retry);\n\n if (backoffDelay === 0) {\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n this.queue.push(runner);\n this.pump();\n return;\n }\n\n const retryEntry: IRetryEntry = {\n runner,\n timerId: setTimeout(() => {\n this.retryEntries.delete(retryEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, backoffDelay),\n };\n\n this.retryEntries.add(retryEntry);\n\n runner.onCancel = () => {\n if (this.retryEntries.has(retryEntry)) {\n clearTimeout(retryEntry.timerId);\n this.retryEntries.delete(retryEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks:\n this.queue.length +\n this.delayedEntries.size +\n this.idleEntries.size +\n this.retryEntries.size +\n this.debounceCoordinator.size +\n this.throttleCoordinator.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport { AhkoTimeoutError } from \"../errors/timeout.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport type { IRetryOptions } from \"../models/retry.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, timeout enforcement, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n public readonly externalSignal?: AbortSignal;\n\n /** Maximum execution duration allowed in milliseconds */\n public readonly timeoutMs?: number;\n\n /** Active timeout timer identifier */\n private timeoutTimerId?: ReturnType<typeof setTimeout>;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /** Current execution attempt count (1-indexed) */\n public attempt = 1;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n * @param timeoutMs - Optional maximum execution time in milliseconds.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal, timeoutMs?: number) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.timeoutMs = timeoutMs;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.abortController.abort(cancelError);\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.cleanup();\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.cleanup();\n this.rejectPromise(reason);\n }\n\n /**\n * Evaluates if the task should be retried following an execution failure or timeout.\n *\n * @param error - The error encountered during the attempt.\n * @param retryOptions - Configured retry policy.\n * @returns A promise resolving to true if retry should proceed, false otherwise.\n */\n public async canRetry(error: unknown, retryOptions?: IRetryOptions): Promise<boolean> {\n if (this._state === ETaskState.CANCELLED || (this.externalSignal?.aborted ?? false)) {\n return false;\n }\n\n if (!retryOptions || typeof retryOptions.attempts !== \"number\") {\n return false;\n }\n\n if (this.attempt >= retryOptions.attempts) {\n return false;\n }\n\n if (typeof retryOptions.shouldRetry === \"function\") {\n try {\n const allowed = await retryOptions.shouldRetry(error, this.attempt);\n if (!allowed) {\n return false;\n }\n } catch {\n return false;\n }\n }\n\n this.attempt++;\n this._state = ETaskState.PENDING;\n this.abortController = new AbortController();\n return true;\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation/timeout.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n let abortListener: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n abortListener = () => {\n if (this._state === ETaskState.TIMED_OUT) {\n reject(\n new AhkoTimeoutError(\n `Task execution timed out after ${this.timeoutMs}ms`,\n { timeoutMs: this.timeoutMs }\n )\n );\n } else {\n const reason = this.abortController.signal.reason;\n reject(\n new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: reason instanceof Error ? reason : undefined,\n })\n );\n }\n };\n this.abortController.signal.addEventListener(\"abort\", abortListener, { once: true });\n });\n\n let timeoutPromise: Promise<never> | undefined;\n if (this.timeoutMs !== undefined) {\n timeoutPromise = new Promise<never>((_, reject) => {\n this.timeoutTimerId = setTimeout(() => {\n if (this._state !== ETaskState.RUNNING) {\n return;\n }\n this._state = ETaskState.TIMED_OUT;\n const timeoutError = new AhkoTimeoutError(\n `Task execution timed out after ${this.timeoutMs}ms`,\n { timeoutMs: this.timeoutMs }\n );\n this.abortController.abort(timeoutError);\n reject(timeoutError);\n }, this.timeoutMs);\n });\n }\n\n let taskExecutionPromise: Promise<T>;\n try {\n taskExecutionPromise = Promise.resolve(this.task(context));\n } catch (syncError) {\n taskExecutionPromise = Promise.reject(syncError);\n }\n\n // Suppress unhandled rejection in background if task finishes or fails after timeout/cancellation\n taskExecutionPromise.catch(() => {});\n\n const racePromises: Array<Promise<T | never>> = [\n taskExecutionPromise,\n abortPromise,\n ];\n if (timeoutPromise) {\n racePromises.push(timeoutPromise);\n }\n\n try {\n const result = await Promise.race(racePromises);\n this.clearTimeoutTimer();\n if (abortListener) {\n this.abortController.signal.removeEventListener(\"abort\", abortListener);\n }\n\n if ((this._state as ETaskState) === ETaskState.TIMED_OUT) {\n throw new AhkoTimeoutError(\n `Task execution timed out after ${this.timeoutMs}ms`,\n { timeoutMs: this.timeoutMs }\n );\n }\n\n if ((this._state as ETaskState) === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled during execution\");\n }\n\n this._state = ETaskState.COMPLETED;\n return result;\n } catch (error) {\n this.clearTimeoutTimer();\n if (abortListener) {\n this.abortController.signal.removeEventListener(\"abort\", abortListener);\n }\n\n if ((this._state as ETaskState) === ETaskState.TIMED_OUT || error instanceof AhkoTimeoutError) {\n this._state = ETaskState.TIMED_OUT;\n if (error instanceof AhkoTimeoutError) {\n throw error;\n }\n throw new AhkoTimeoutError(\n `Task execution timed out after ${this.timeoutMs}ms`,\n {\n timeoutMs: this.timeoutMs,\n cause: error instanceof Error ? error : undefined,\n }\n );\n }\n\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted ||\n (this.externalSignal?.aborted ?? false);\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n if (error instanceof AhkoCancellationError) {\n throw error;\n }\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Clears the active timeout timer.\n */\n private clearTimeoutTimer(): void {\n if (this.timeoutTimerId !== undefined) {\n clearTimeout(this.timeoutTimerId);\n this.timeoutTimerId = undefined;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.clearTimeoutTimer();\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n this.clearTimeoutTimer();\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport { EScheduleStrategy } from \"./models/strategy.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency, options?.minIntervalMs);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n * @throws {AhkoTimeoutError} If task execution exceeds timeoutMs.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (strategy === EScheduleStrategy.DEBOUNCE) {\n if (!options?.key || (typeof options.key !== \"string\" && typeof options.key !== \"symbol\")) {\n throw new AhkoConfigurationError(\n `Strategy \"debounce\" requires a valid \"key\" of type string or symbol.`\n );\n }\n const waitMs = options.waitMs ?? options.delay;\n if (typeof waitMs !== \"number\" || Number.isNaN(waitMs) || !Number.isFinite(waitMs) || waitMs < 0) {\n throw new AhkoConfigurationError(\n `Strategy \"debounce\" requires a non-negative finite \"waitMs\" or \"delay\" in milliseconds.`\n );\n }\n return this.queue.debounceCoordinator.schedule(\n options.key,\n task,\n waitMs,\n options,\n (t, opts) => this.schedule(t, { ...opts, strategy: EScheduleStrategy.IMMEDIATE })\n );\n }\n\n if (strategy === EScheduleStrategy.THROTTLE) {\n if (!options?.key || (typeof options.key !== \"string\" && typeof options.key !== \"symbol\")) {\n throw new AhkoConfigurationError(\n `Strategy \"throttle\" requires a valid \"key\" of type string or symbol.`\n );\n }\n const waitMs = options.waitMs ?? options.delay;\n if (typeof waitMs !== \"number\" || Number.isNaN(waitMs) || !Number.isFinite(waitMs) || waitMs < 0) {\n throw new AhkoConfigurationError(\n `Strategy \"throttle\" requires a non-negative finite \"waitMs\" or \"delay\" in milliseconds.`\n );\n }\n return this.queue.throttleCoordinator.schedule(\n options.key,\n task,\n waitMs,\n options,\n (t, opts) => this.schedule(t, { ...opts, strategy: EScheduleStrategy.IMMEDIATE })\n );\n }\n\n const runner = new TaskRunner<T>(task, options?.signal, options?.timeoutMs);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Convenience method to schedule a task during platform idle opportunities.\n *\n * Equivalent to calling `schedule(task, { ...options, strategy: \"idle\" })`.\n * In browsers, uses `requestIdleCallback` when available.\n * In Node.js, uses `setImmediate`.\n * Falls back to `setTimeout(..., 0)` if neither is available.\n *\n * @template T - Inferred return type of the task.\n * @param task - Task function to run when idle.\n * @param options - Scheduling options (excluding strategy).\n * @returns A promise resolving to the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n */\n public idle<T>(\n task: ITask<T>,\n options?: Omit<IScheduleOptions, \"strategy\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.IDLE,\n });\n }\n\n /**\n * Convenience method to schedule a debounced task with key-based Promise coalescing.\n *\n * @template T - Inferred return type of the task.\n * @param key - Explicit identity key.\n * @param task - Work to execute once calls stop arriving.\n * @param waitMs - Quiet window duration in milliseconds.\n * @param options - Additional schedule options.\n * @returns Shared promise resolving with the final execution outcome.\n */\n public debounce<T>(\n key: string | symbol,\n task: ITask<T>,\n waitMs: number,\n options?: Omit<IScheduleOptions, \"strategy\" | \"key\" | \"waitMs\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.DEBOUNCE,\n key,\n waitMs,\n });\n }\n\n /**\n * Convenience method to schedule a throttled task with leading execution and coalesced trailing run.\n *\n * @template T - Inferred return type of the task.\n * @param key - Explicit identity key.\n * @param task - Work to execute.\n * @param waitMs - Throttle interval duration in milliseconds.\n * @param options - Additional schedule options.\n * @returns Promise resolving with the leading or coalesced trailing result.\n */\n public throttle<T>(\n key: string | symbol,\n task: ITask<T>,\n waitMs: number,\n options?: Omit<IScheduleOptions, \"strategy\" | \"key\" | \"waitMs\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.THROTTLE,\n key,\n waitMs,\n });\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.5.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Result of combining multiple AbortSignals.\n */\nexport interface ICombinedSignal {\n /**\n * The unified AbortSignal that aborts when any source signal aborts.\n */\n readonly signal: AbortSignal;\n\n /**\n * Detaches all registered event listeners from source signals to prevent memory leaks.\n */\n cleanup: () => void;\n}\n\n/**\n * Combines multiple AbortSignals into a single coordinated AbortSignal with deterministic cleanup.\n *\n * @param signals - Array of source AbortSignals (undefined entries are ignored).\n * @returns A unified signal interface with explicit cleanup callback.\n */\nexport function combineSignals(\n signals: ReadonlyArray<AbortSignal | undefined>\n): ICombinedSignal {\n const activeSignals = signals.filter(\n (signal): signal is AbortSignal => signal !== undefined\n );\n\n if (activeSignals.length === 0) {\n const controller = new AbortController();\n return {\n signal: controller.signal,\n cleanup: () => {},\n };\n }\n\n // Check if any source signal is already aborted\n const alreadyAborted = activeSignals.find((s) => s.aborted);\n if (alreadyAborted) {\n const controller = new AbortController();\n controller.abort(alreadyAborted.reason);\n return {\n signal: controller.signal,\n cleanup: () => {},\n };\n }\n\n if (activeSignals.length === 1) {\n return {\n signal: activeSignals[0],\n cleanup: () => {},\n };\n }\n\n const controller = new AbortController();\n const cleanupFns: Array<() => void> = [];\n\n const onAbort = (event: Event): void => {\n const target = event.target as AbortSignal;\n cleanup();\n controller.abort(target.reason);\n };\n\n for (const sig of activeSignals) {\n sig.addEventListener(\"abort\", onAbort, { once: true });\n cleanupFns.push(() => {\n sig.removeEventListener(\"abort\", onAbort);\n });\n }\n\n const cleanup = (): void => {\n for (const fn of cleanupFns) {\n fn();\n }\n cleanupFns.length = 0;\n };\n\n return {\n signal: controller.signal,\n cleanup,\n };\n}\n"],"mappings":";AAGO,IAAM,YAAN,cAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACVO,IAAM,yBAAN,cAAqC,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACdO,IAAK,oBAAL,kBAAKA,uBAAL;AAEL,EAAAA,mBAAA,eAAY;AAEZ,EAAAA,mBAAA,WAAQ;AAER,EAAAA,mBAAA,UAAO;AAEP,EAAAA,mBAAA,cAAW;AAEX,EAAAA,mBAAA,cAAW;AAVD,SAAAA;AAAA,GAAA;;;ACYL,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA,EAI9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQhB,YACE,UAAU,4BACV,SACA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,YAAY,SAAS;AA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,UAAMA,cAAa,IAAI,gBAAgB;AACvC,IAAAA,YAAW,MAAM,eAAe,MAAM;AACtC,WAAO;AAAA,MACL,QAAQA,YAAW;AAAA,MACnB,SAAS,MAAM;AAAA,MAAC;AAAA,IAClB;AAAA,EACF;AAEA,MAAI,cAAc,WAAW,GAAG;AAC9B,WAAO;AAAA,MACL,QAAQ,cAAc,CAAC;AAAA,MACvB,SAAS,MAAM;AAAA,MAAC;AAAA,IAClB;AAAA,EACF;AAEA,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,aAAgC,CAAC;AAEvC,QAAM,UAAU,CAAC,UAAuB;AACtC,UAAM,SAAS,MAAM;AACrB,YAAQ;AACR,eAAW,MAAM,OAAO,MAAM;AAAA,EAChC;AAEA,aAAW,OAAO,eAAe;AAC/B,QAAI,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACrD,eAAW,KAAK,MAAM;AACpB,UAAI,oBAAoB,SAAS,OAAO;AAAA,IAC1C,CAAC;AAAA,EACH;AAEA,QAAM,UAAU,MAAY;AAC1B,eAAW,MAAM,YAAY;AAC3B,SAAG;AAAA,IACL;AACA,eAAW,SAAS;AAAA,EACtB;AAEA,SAAO;AAAA,IACL,QAAQ,WAAW;AAAA,IACnB;AAAA,EACF;AACF;","names":["EScheduleStrategy","ETaskState","controller"]}
|
|
@@ -24,6 +24,23 @@ export interface IScheduleOptions {
|
|
|
24
24
|
* Automatic retry options for transient failure handling.
|
|
25
25
|
*/
|
|
26
26
|
retry?: IRetryOptions;
|
|
27
|
+
/**
|
|
28
|
+
* Maximum execution time in milliseconds allowed per attempt.
|
|
29
|
+
* If the task does not complete within this duration, execution
|
|
30
|
+
* is aborted and the task rejects with an AhkoTimeoutError.
|
|
31
|
+
* Must be a positive finite number greater than 0 if provided.
|
|
32
|
+
*/
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
/**
|
|
35
|
+
* Explicit identity key for "debounce" and "throttle" strategies.
|
|
36
|
+
* Tasks sharing the same key coalesce into shared executions.
|
|
37
|
+
*/
|
|
38
|
+
key?: string | symbol;
|
|
39
|
+
/**
|
|
40
|
+
* Duration in milliseconds for debounce quiet window or throttle period.
|
|
41
|
+
* If omitted, falls back to `delay` if specified.
|
|
42
|
+
*/
|
|
43
|
+
waitMs?: number;
|
|
27
44
|
/**
|
|
28
45
|
* External cancellation signal.
|
|
29
46
|
* If aborted before start, the task is removed from the queue without execution.
|
|
@@ -41,4 +58,11 @@ export interface IAhkoOptions {
|
|
|
41
58
|
* @default Infinity
|
|
42
59
|
*/
|
|
43
60
|
concurrency?: number;
|
|
61
|
+
/**
|
|
62
|
+
* Minimum interval in milliseconds that must elapse between consecutive task starts.
|
|
63
|
+
* Paces task execution to prevent burst workloads even when concurrency slots are free.
|
|
64
|
+
* Must be a non-negative finite number if provided.
|
|
65
|
+
* @default 0
|
|
66
|
+
*/
|
|
67
|
+
minIntervalMs?: number;
|
|
44
68
|
}
|
|
@@ -7,9 +7,13 @@ export declare enum EScheduleStrategy {
|
|
|
7
7
|
/** Delay execution for a designated duration before queuing */
|
|
8
8
|
DELAY = "delay",
|
|
9
9
|
/** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */
|
|
10
|
-
IDLE = "idle"
|
|
10
|
+
IDLE = "idle",
|
|
11
|
+
/** Enforce maximum execution frequency for tasks sharing the same key */
|
|
12
|
+
THROTTLE = "throttle",
|
|
13
|
+
/** Delay execution until calls sharing the same key stop arriving */
|
|
14
|
+
DEBOUNCE = "debounce"
|
|
11
15
|
}
|
|
12
16
|
/**
|
|
13
17
|
* Union type representing valid scheduling strategy identifiers.
|
|
14
18
|
*/
|
|
15
|
-
export type TScheduleStrategy = EScheduleStrategy | "immediate" | "delay" | "idle";
|
|
19
|
+
export type TScheduleStrategy = EScheduleStrategy | "immediate" | "delay" | "idle" | "throttle" | "debounce";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { IScheduleOptions } from "../models/options.model.js";
|
|
2
|
+
import type { ITask } from "../models/task.model.js";
|
|
3
|
+
/**
|
|
4
|
+
* Coordinates debounce execution with Promise coalescing by explicit key.
|
|
5
|
+
*
|
|
6
|
+
* Incoming calls with the same key extend the quiet window and share the
|
|
7
|
+
* eventual execution Promise, guaranteeing that all callers receive the final result.
|
|
8
|
+
*/
|
|
9
|
+
export declare class DebounceCoordinator {
|
|
10
|
+
private readonly entries;
|
|
11
|
+
/**
|
|
12
|
+
* Schedules a task under the debounce strategy.
|
|
13
|
+
*
|
|
14
|
+
* @param key - Explicit identity key.
|
|
15
|
+
* @param task - Work to execute once calls stop arriving.
|
|
16
|
+
* @param waitMs - Quiet window duration in milliseconds.
|
|
17
|
+
* @param options - Scheduling options.
|
|
18
|
+
* @param dispatchFn - Callback invoked when the debounce window expires to dispatch the task to the queue.
|
|
19
|
+
* @returns Shared promise that resolves/rejects with the final execution outcome.
|
|
20
|
+
*/
|
|
21
|
+
schedule<T>(key: string | symbol, task: ITask<T>, waitMs: number, options: IScheduleOptions | undefined, dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>): Promise<T>;
|
|
22
|
+
/**
|
|
23
|
+
* Dispatches the coalesced task when the quiet window expires.
|
|
24
|
+
*/
|
|
25
|
+
private flush;
|
|
26
|
+
/**
|
|
27
|
+
* Cancels a pending debounced task by key.
|
|
28
|
+
*
|
|
29
|
+
* @param key - Identity key to cancel.
|
|
30
|
+
* @param reason - Optional cancellation reason.
|
|
31
|
+
*/
|
|
32
|
+
cancel(key: string | symbol, reason?: unknown): void;
|
|
33
|
+
/**
|
|
34
|
+
* Number of pending debounced tasks waiting for quiet window expiry.
|
|
35
|
+
*/
|
|
36
|
+
get size(): number;
|
|
37
|
+
/**
|
|
38
|
+
* Cancels all pending debounced entries and clears the map.
|
|
39
|
+
*/
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result of combining multiple AbortSignals.
|
|
3
|
+
*/
|
|
4
|
+
export interface ICombinedSignal {
|
|
5
|
+
/**
|
|
6
|
+
* The unified AbortSignal that aborts when any source signal aborts.
|
|
7
|
+
*/
|
|
8
|
+
readonly signal: AbortSignal;
|
|
9
|
+
/**
|
|
10
|
+
* Detaches all registered event listeners from source signals to prevent memory leaks.
|
|
11
|
+
*/
|
|
12
|
+
cleanup: () => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Combines multiple AbortSignals into a single coordinated AbortSignal with deterministic cleanup.
|
|
16
|
+
*
|
|
17
|
+
* @param signals - Array of source AbortSignals (undefined entries are ignored).
|
|
18
|
+
* @returns A unified signal interface with explicit cleanup callback.
|
|
19
|
+
*/
|
|
20
|
+
export declare function combineSignals(signals: ReadonlyArray<AbortSignal | undefined>): ICombinedSignal;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { IScheduleOptions } from "../models/options.model.js";
|
|
2
2
|
import type { IAhkoStats } from "../models/stats.model.js";
|
|
3
|
+
import { DebounceCoordinator } from "./debounce-coordinator.js";
|
|
3
4
|
import { TaskRunner } from "./task-runner.js";
|
|
5
|
+
import { ThrottleCoordinator } from "./throttle-coordinator.js";
|
|
4
6
|
/**
|
|
5
7
|
* Memory-safe FIFO task queue managing concurrency allocation,
|
|
6
8
|
* delayed scheduling, and task lifecycle counters.
|
|
@@ -8,6 +10,12 @@ import { TaskRunner } from "./task-runner.js";
|
|
|
8
10
|
export declare class TaskQueue {
|
|
9
11
|
/** Maximum concurrent active tasks */
|
|
10
12
|
readonly concurrency: number;
|
|
13
|
+
/** Minimum interval in milliseconds between consecutive task starts */
|
|
14
|
+
readonly minIntervalMs: number;
|
|
15
|
+
/** Timestamp of the most recent task start */
|
|
16
|
+
private lastTaskStartTime;
|
|
17
|
+
/** Active rate limit timer for pacing consecutive tasks */
|
|
18
|
+
private rateLimitTimer?;
|
|
11
19
|
/** Queue of pending task runners waiting for a concurrency slot */
|
|
12
20
|
private readonly queue;
|
|
13
21
|
/** Set of task runners currently executing */
|
|
@@ -18,6 +26,10 @@ export declare class TaskQueue {
|
|
|
18
26
|
private readonly idleEntries;
|
|
19
27
|
/** Set of tasks currently awaiting a retry backoff timer */
|
|
20
28
|
private readonly retryEntries;
|
|
29
|
+
/** Coordinator for debounced tasks with key coalescing */
|
|
30
|
+
readonly debounceCoordinator: DebounceCoordinator;
|
|
31
|
+
/** Coordinator for throttled tasks with leading/trailing coalescing */
|
|
32
|
+
readonly throttleCoordinator: ThrottleCoordinator;
|
|
21
33
|
/** WeakMap associating task runners with their scheduling options */
|
|
22
34
|
private readonly runnerOptions;
|
|
23
35
|
/** Cumulative completed tasks counter */
|
|
@@ -32,9 +44,10 @@ export declare class TaskQueue {
|
|
|
32
44
|
* Creates a new TaskQueue.
|
|
33
45
|
*
|
|
34
46
|
* @param concurrency - Maximum concurrent tasks (defaults to Infinity).
|
|
35
|
-
* @
|
|
47
|
+
* @param minIntervalMs - Minimum interval in milliseconds between task dispatches.
|
|
48
|
+
* @throws {AhkoConfigurationError} If concurrency is less than 1 or minIntervalMs is invalid.
|
|
36
49
|
*/
|
|
37
|
-
constructor(concurrency?: number);
|
|
50
|
+
constructor(concurrency?: number, minIntervalMs?: number);
|
|
38
51
|
/**
|
|
39
52
|
* Enqueues a task runner according to the specified schedule options.
|
|
40
53
|
*
|
|
@@ -57,7 +70,7 @@ export declare class TaskQueue {
|
|
|
57
70
|
private scheduleIdle;
|
|
58
71
|
/**
|
|
59
72
|
* Pumps the queue by picking pending tasks and executing them
|
|
60
|
-
* as long as concurrency capacity is available.
|
|
73
|
+
* as long as concurrency capacity is available and minIntervalMs is respected.
|
|
61
74
|
*/
|
|
62
75
|
private pump;
|
|
63
76
|
/**
|
|
@@ -3,7 +3,7 @@ import { ETaskState } from "../models/state.model.js";
|
|
|
3
3
|
import type { ITask } from "../models/task.model.js";
|
|
4
4
|
/**
|
|
5
5
|
* Internal task lifecycle manager responsible for execution, state transitions,
|
|
6
|
-
* AbortSignal coordination, and deterministic resource cleanup.
|
|
6
|
+
* AbortSignal coordination, timeout enforcement, and deterministic resource cleanup.
|
|
7
7
|
*
|
|
8
8
|
* @template T - The return type produced by the underlying task.
|
|
9
9
|
*/
|
|
@@ -13,11 +13,15 @@ export declare class TaskRunner<T> {
|
|
|
13
13
|
/** Current lifecycle state */
|
|
14
14
|
private _state;
|
|
15
15
|
/** Internal AbortController whose signal is passed to the task context */
|
|
16
|
-
private
|
|
16
|
+
private abortController;
|
|
17
17
|
/** The user task function to execute */
|
|
18
18
|
private readonly task;
|
|
19
19
|
/** User-supplied AbortSignal for external cancellation */
|
|
20
|
-
|
|
20
|
+
readonly externalSignal?: AbortSignal;
|
|
21
|
+
/** Maximum execution duration allowed in milliseconds */
|
|
22
|
+
readonly timeoutMs?: number;
|
|
23
|
+
/** Active timeout timer identifier */
|
|
24
|
+
private timeoutTimerId?;
|
|
21
25
|
/** Abort event listener reference for clean detachment */
|
|
22
26
|
private readonly abortListener?;
|
|
23
27
|
/** Promise resolve handler */
|
|
@@ -28,19 +32,20 @@ export declare class TaskRunner<T> {
|
|
|
28
32
|
readonly promise: Promise<T>;
|
|
29
33
|
/** Callback invoked when runner is cancelled while pending */
|
|
30
34
|
onCancel?: (runner: TaskRunner<T>) => void;
|
|
35
|
+
/** Current execution attempt count (1-indexed) */
|
|
36
|
+
attempt: number;
|
|
31
37
|
/**
|
|
32
38
|
* Creates a new TaskRunner instance.
|
|
33
39
|
*
|
|
34
40
|
* @param task - The asynchronous work unit to run.
|
|
35
41
|
* @param externalSignal - Optional external AbortSignal to propagate.
|
|
42
|
+
* @param timeoutMs - Optional maximum execution time in milliseconds.
|
|
36
43
|
*/
|
|
37
|
-
constructor(task: ITask<T>, externalSignal?: AbortSignal);
|
|
44
|
+
constructor(task: ITask<T>, externalSignal?: AbortSignal, timeoutMs?: number);
|
|
38
45
|
/**
|
|
39
46
|
* Gets the current lifecycle state of the task.
|
|
40
47
|
*/
|
|
41
48
|
get state(): ETaskState;
|
|
42
|
-
/** Current execution attempt count (1-indexed) */
|
|
43
|
-
attempt: number;
|
|
44
49
|
/**
|
|
45
50
|
* Resolves the deferred promise.
|
|
46
51
|
*
|
|
@@ -54,7 +59,7 @@ export declare class TaskRunner<T> {
|
|
|
54
59
|
*/
|
|
55
60
|
reject(reason: unknown): void;
|
|
56
61
|
/**
|
|
57
|
-
* Evaluates if the task should be retried following an execution failure.
|
|
62
|
+
* Evaluates if the task should be retried following an execution failure or timeout.
|
|
58
63
|
*
|
|
59
64
|
* @param error - The error encountered during the attempt.
|
|
60
65
|
* @param retryOptions - Configured retry policy.
|
|
@@ -64,9 +69,13 @@ export declare class TaskRunner<T> {
|
|
|
64
69
|
/**
|
|
65
70
|
* Executes the task within an allocated concurrency slot.
|
|
66
71
|
*
|
|
67
|
-
* @returns A promise resolving to the task result or rejecting on failure/cancellation.
|
|
72
|
+
* @returns A promise resolving to the task result or rejecting on failure/cancellation/timeout.
|
|
68
73
|
*/
|
|
69
74
|
run(): Promise<T>;
|
|
75
|
+
/**
|
|
76
|
+
* Clears the active timeout timer.
|
|
77
|
+
*/
|
|
78
|
+
private clearTimeoutTimer;
|
|
70
79
|
/**
|
|
71
80
|
* Cancels the task, aborting pending or running execution.
|
|
72
81
|
*
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { IScheduleOptions } from "../models/options.model.js";
|
|
2
|
+
import type { ITask } from "../models/task.model.js";
|
|
3
|
+
/**
|
|
4
|
+
* Coordinates throttle execution with leading execution, trailing execution,
|
|
5
|
+
* and Promise coalescing by explicit key.
|
|
6
|
+
*
|
|
7
|
+
* Incoming calls with the same key within the throttle period coalesce into a
|
|
8
|
+
* single shared trailing execution, preventing overload while ensuring callers
|
|
9
|
+
* receive the final result.
|
|
10
|
+
*/
|
|
11
|
+
export declare class ThrottleCoordinator {
|
|
12
|
+
private readonly entries;
|
|
13
|
+
/**
|
|
14
|
+
* Schedules a task under the throttle strategy.
|
|
15
|
+
*
|
|
16
|
+
* @param key - Explicit identity key.
|
|
17
|
+
* @param task - Work to execute.
|
|
18
|
+
* @param waitMs - Throttle interval duration in milliseconds.
|
|
19
|
+
* @param options - Scheduling options.
|
|
20
|
+
* @param dispatchFn - Callback invoked to dispatch task execution into the queue.
|
|
21
|
+
* @returns Promise resolving with the leading execution or coalesced trailing result.
|
|
22
|
+
*/
|
|
23
|
+
schedule<T>(key: string | symbol, task: ITask<T>, waitMs: number, options: IScheduleOptions | undefined, dispatchFn: (task: ITask<T>, options?: IScheduleOptions) => Promise<T>): Promise<T>;
|
|
24
|
+
/**
|
|
25
|
+
* Invoked when the throttle interval window timer expires.
|
|
26
|
+
*/
|
|
27
|
+
private onWindowExpire;
|
|
28
|
+
/**
|
|
29
|
+
* Cancels any pending trailing throttled task for a given key.
|
|
30
|
+
*
|
|
31
|
+
* @param key - Identity key to cancel.
|
|
32
|
+
* @param reason - Optional cancellation reason.
|
|
33
|
+
*/
|
|
34
|
+
cancel(key: string | symbol, reason?: unknown): void;
|
|
35
|
+
/**
|
|
36
|
+
* Number of keys currently actively throttled.
|
|
37
|
+
*/
|
|
38
|
+
get size(): number;
|
|
39
|
+
/**
|
|
40
|
+
* Clears all throttled entries and timers.
|
|
41
|
+
*/
|
|
42
|
+
clear(): void;
|
|
43
|
+
}
|
package/dist/version.d.ts
CHANGED