@@ -4,6 +4,58 @@ import valueIs from "../../valueIs";
44import TasksQueue from "./TasksQueue" ;
55import { AdaptiveTaskQueueOptions , AddTasksBaseOptions , BaseQueueTask } from "./docs" ;
66
7+ /**
8+ * AdaptiveTaskQueue extends the base TasksQueue by dynamically adjusting
9+ * its concurrency limit based on the observed task addition rate (RPS).
10+ *
11+ * This class tracks the rate of tasks being added over a rolling time window,
12+ * then periodically recalculates and adjusts the concurrency limit to optimize
13+ * throughput and resource usage.
14+ *
15+ * It is especially useful in environments with variable workload, where
16+ * adapting concurrency based on real-time demand can improve performance and
17+ * efficiency without manual tuning.
18+ *
19+ * Key features:
20+ * - Tracks requests per second (RPS) using a sliding time window.
21+ * - Automatically increases or decreases concurrency limit based on RPS.
22+ * - Emits concurrency update events to allow external monitoring.
23+ * - Configurable time window for rate tracking and debounce delay for recalculations.
24+ *
25+ * @extends TasksQueue
26+ *
27+ * @param {AdaptiveTaskQueueOptions } [options] - Configuration options for adaptive behavior.
28+ * @param {number } [options.windowDurationMs=1000] - Duration of the rolling window in milliseconds for RPS calculation.
29+ * @param {number } [options.recalcDebounce=200] - Debounce delay in milliseconds before concurrency is recalculated.
30+ * @param {boolean } [options.autoRun] - Whether to automatically run the queue when tasks are added (inherited from TasksQueue).
31+ * @param {number } [options.concurrencyLimit] - Initial concurrency limit (inherited from TasksQueue).
32+ *
33+ * @example
34+ * ```ts
35+ * import { AdaptiveTaskQueue } from '@nasriya/atomix/tools';
36+ *
37+ * const queue = new AdaptiveTaskQueue({
38+ * windowDurationMs: 500,
39+ * recalcDebounce: 100,
40+ * autoRun: true,
41+ * });
42+ *
43+ * queue.onConcurrencyUpdate(newLimit => {
44+ * console.log(`Concurrency updated to: ${newLimit}`);
45+ * });
46+ *
47+ * queue.addTask({
48+ * type: 'task',
49+ * action: async () => {
50+ * // Your async work here
51+ * }
52+ * });
53+ *
54+ * await queue.untilComplete();
55+ * ```
56+ *
57+ * @since 1.0.23
58+ */
759export class AdaptiveTaskQueue extends TasksQueue {
860 #_addedSinceLast = 0 ;
961 readonly #_rateWindow: number [ ] = [ ] ;
0 commit comments