@tanstack/pacer 0.15.4 → 0.16.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/dist/cjs/async-batcher.cjs +66 -4
- package/dist/cjs/async-batcher.cjs.map +1 -1
- package/dist/cjs/async-batcher.d.cts +97 -16
- package/dist/cjs/async-debouncer.cjs +53 -18
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +79 -9
- package/dist/cjs/async-queuer.cjs +58 -1
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +103 -9
- package/dist/cjs/async-rate-limiter.cjs +51 -1
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +94 -27
- package/dist/cjs/async-retryer.cjs +286 -0
- package/dist/cjs/async-retryer.cjs.map +1 -0
- package/dist/cjs/async-retryer.d.cts +312 -0
- package/dist/cjs/async-throttler.cjs +101 -52
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +85 -9
- package/dist/cjs/batcher.cjs +5 -0
- package/dist/cjs/batcher.cjs.map +1 -1
- package/dist/cjs/batcher.d.cts +13 -1
- package/dist/cjs/debouncer.cjs +5 -0
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -2
- package/dist/cjs/event-client.cjs.map +1 -1
- package/dist/cjs/event-client.d.cts +3 -0
- package/dist/cjs/index.cjs +13 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/queuer.cjs +5 -0
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +11 -3
- package/dist/cjs/rate-limiter.cjs +5 -0
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +11 -0
- package/dist/cjs/throttler.cjs +5 -0
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +11 -0
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/esm/async-batcher.d.ts +97 -16
- package/dist/esm/async-batcher.js +67 -5
- package/dist/esm/async-batcher.js.map +1 -1
- package/dist/esm/async-debouncer.d.ts +79 -9
- package/dist/esm/async-debouncer.js +54 -19
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +103 -9
- package/dist/esm/async-queuer.js +59 -2
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +94 -27
- package/dist/esm/async-rate-limiter.js +52 -2
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-retryer.d.ts +312 -0
- package/dist/esm/async-retryer.js +286 -0
- package/dist/esm/async-retryer.js.map +1 -0
- package/dist/esm/async-throttler.d.ts +85 -9
- package/dist/esm/async-throttler.js +102 -53
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +13 -1
- package/dist/esm/batcher.js +5 -0
- package/dist/esm/batcher.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -2
- package/dist/esm/debouncer.js +6 -1
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/event-client.d.ts +3 -0
- package/dist/esm/event-client.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +23 -10
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +11 -3
- package/dist/esm/queuer.js +6 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +11 -0
- package/dist/esm/rate-limiter.js +6 -1
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +11 -0
- package/dist/esm/throttler.js +6 -1
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +12 -2
- package/src/async-batcher.ts +146 -19
- package/src/async-debouncer.ts +120 -30
- package/src/async-queuer.ts +149 -11
- package/src/async-rate-limiter.ts +131 -30
- package/src/async-retryer.ts +669 -0
- package/src/async-throttler.ts +198 -72
- package/src/batcher.ts +18 -1
- package/src/debouncer.ts +19 -2
- package/src/event-client.ts +3 -0
- package/src/index.ts +2 -0
- package/src/queuer.ts +21 -3
- package/src/rate-limiter.ts +20 -0
- package/src/throttler.ts +20 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.js","sources":["../../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { createKey, parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = createKey(initialOptions.key)\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"names":[],"mappings":";;;AAoCA,SAAS,2BAEgB;AACvB,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,QAAQ;AAAA,IACR,mBAAmB;AAAA,EAAA;AAEvB;AA2CA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAqCO,MAAM,UAAmC;AAAA,EAQ9C,YACS,IACP,gBACA;AAFO,SAAA,KAAA;AART,SAAS,QAA8C,IAAI;AAAA,MACzD,yBAAA;AAAA,IAAyB;AA2B3B,SAAA,aAAa,CAAC,eAAqD;AACjE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAGrC,UAAI,CAAC,KAAK,eAAe;AACvB,aAAK,OAA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UAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,WAAK,UAAU,MAAM,QAAQ,MAAM,KAA4B;AAC/D,WAAK,WAAW,MAAM,QAAQ,OAAO;AAAA,IAAA,CACtC;AAAA,EAAA;AAAA,EAjBH;AAAA,EAgCA;AAAA,EAmBA;AAAA,EAIA;AAAA,EA6DA;AAAA,EA8BA;AA8BF;AAoCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
|
|
1
|
+
{"version":3,"file":"throttler.js","sources":["../../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { createKey, parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = createKey(initialOptions.key)\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\n }\n\n /**\n * Emits a change event for the throttler instance. Mostly useful for devtools.\n */\n _emit = () => emitChange('Throttler', this)\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"names":[],"mappings":";;;AAoCA,SAAS,2BAEgB;AACvB,SAAO;AAAA,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AAC3D,aAAK,SAAS,GAAG,KAAK,MAAM,MAAM,QAAQ;AAAA,MAC5C;AAAA,IACF;AAEA,SAAA,gBAAgB,MAAY;AAC1B,UAAI,KAAK,YAAY;AACnB,qBAAa,KAAK,UAAU;AAC5B,aAAK,aAAa;AAAA,MACpB;AAAA,IACF;AAWA,SAAA,SAAS,MAAY;AACnB,WAAK,cAAA;AACL,WAAK,UAAU;AAAA,QACb,UAAU;AAAA,QACV,WAAW;AAAA,MAAA,CACZ;AAAA,IACH;AAKA,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,0BAA+B;AAAA,IAChD;AA9KE,SAAK,MAAM,UAAU,eAAe,GAAG;AACvC,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAE9C,qBAAiB,GAAG,eAAe,CAAC,UAAU;AAC5C,UAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,WAAK,UAAU,MAAM,QAAQ,MAAM,KAA4B;AAC/D,WAAK,WAAW,MAAM,QAAQ,OAAO;AAAA,IACvC,CAAC;AAAA,EACH;AAAA,EAlBA;AAAA,EAqCA;AAAA,EAmBA;AAAA,EAIA;AAAA,EA6DA;AAAA,EA8BA;AA8BF;AAsCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
|
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n\nexport function createKey(key?: string): string {\n if (key) {\n return key\n }\n\n if (\n typeof crypto !== 'undefined' &&\n typeof crypto.randomUUID === 'function'\n ) {\n return crypto.randomUUID()\n }\n\n return ''\n}\n"],"names":[],"mappings":"AAEO,SAAS,WAAkC,OAAwB;AACxE,SAAO,OAAO,UAAU;AAC1B;AAEO,SAAS,qBACd,UACG,MACA;AACH,SAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C;AAEO,SAAS,UAAU,KAAsB;AAC9C,MAAI,KAAK;AACP,WAAO;AAAA,
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n\nexport function createKey(key?: string): string {\n if (key) {\n return key\n }\n\n if (\n typeof crypto !== 'undefined' &&\n typeof crypto.randomUUID === 'function'\n ) {\n return crypto.randomUUID()\n }\n\n return ''\n}\n"],"names":[],"mappings":"AAEO,SAAS,WAAkC,OAAwB;AACxE,SAAO,OAAO,UAAU;AAC1B;AAEO,SAAS,qBACd,UACG,MACA;AACH,SAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C;AAEO,SAAS,UAAU,KAAsB;AAC9C,MAAI,KAAK;AACP,WAAO;AAAA,EACT;AAEA,MACE,OAAO,WAAW,eAClB,OAAO,OAAO,eAAe,YAC7B;AACA,WAAO,OAAO,WAAA;AAAA,EAChB;AAEA,SAAO;AACT;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/pacer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -77,6 +77,16 @@
|
|
|
77
77
|
"default": "./dist/cjs/async-rate-limiter.cjs"
|
|
78
78
|
}
|
|
79
79
|
},
|
|
80
|
+
"./async-retryer": {
|
|
81
|
+
"import": {
|
|
82
|
+
"types": "./dist/esm/async-retryer.d.ts",
|
|
83
|
+
"default": "./dist/esm/async-retryer.js"
|
|
84
|
+
},
|
|
85
|
+
"require": {
|
|
86
|
+
"types": "./dist/cjs/async-retryer.d.cts",
|
|
87
|
+
"default": "./dist/cjs/async-retryer.cjs"
|
|
88
|
+
}
|
|
89
|
+
},
|
|
80
90
|
"./async-throttler": {
|
|
81
91
|
"import": {
|
|
82
92
|
"types": "./dist/esm/async-throttler.d.ts",
|
|
@@ -172,7 +182,7 @@
|
|
|
172
182
|
],
|
|
173
183
|
"dependencies": {
|
|
174
184
|
"@tanstack/devtools-event-client": "^0.3.2",
|
|
175
|
-
"@tanstack/store": "^0.7.
|
|
185
|
+
"@tanstack/store": "^0.7.7"
|
|
176
186
|
},
|
|
177
187
|
"scripts": {
|
|
178
188
|
"clean": "premove ./build ./dist",
|
package/src/async-batcher.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { Store } from '@tanstack/store'
|
|
2
|
+
import { AsyncRetryer } from './async-retryer'
|
|
2
3
|
import { createKey, parseFunctionOrValue } from './utils'
|
|
3
4
|
import { emitChange, pacerEventClient } from './event-client'
|
|
5
|
+
import type { AsyncRetryerOptions } from './async-retryer'
|
|
4
6
|
import type { OptionalKeys } from './types'
|
|
5
7
|
|
|
6
8
|
export interface AsyncBatcherState<TValue> {
|
|
@@ -8,6 +10,10 @@ export interface AsyncBatcherState<TValue> {
|
|
|
8
10
|
* Number of batch executions that have resulted in errors
|
|
9
11
|
*/
|
|
10
12
|
errorCount: number
|
|
13
|
+
/**
|
|
14
|
+
* Number of batch executions that have been executed
|
|
15
|
+
*/
|
|
16
|
+
executeCount: number
|
|
11
17
|
/**
|
|
12
18
|
* Array of items that failed during batch processing
|
|
13
19
|
*/
|
|
@@ -61,6 +67,7 @@ export interface AsyncBatcherState<TValue> {
|
|
|
61
67
|
function getDefaultAsyncBatcherState<TValue>(): AsyncBatcherState<TValue> {
|
|
62
68
|
return {
|
|
63
69
|
errorCount: 0,
|
|
70
|
+
executeCount: 0,
|
|
64
71
|
failedItems: [],
|
|
65
72
|
isEmpty: true,
|
|
66
73
|
isExecuting: false,
|
|
@@ -80,6 +87,12 @@ function getDefaultAsyncBatcherState<TValue>(): AsyncBatcherState<TValue> {
|
|
|
80
87
|
* Options for configuring an AsyncBatcher instance
|
|
81
88
|
*/
|
|
82
89
|
export interface AsyncBatcherOptions<TValue> {
|
|
90
|
+
/**
|
|
91
|
+
* Options for configuring the underlying async retryer
|
|
92
|
+
*/
|
|
93
|
+
asyncRetryerOptions?: AsyncRetryerOptions<
|
|
94
|
+
(items: Array<TValue>) => Promise<any>
|
|
95
|
+
>
|
|
83
96
|
/**
|
|
84
97
|
* Custom function to determine if a batch should be processed
|
|
85
98
|
* Return true to process the batch immediately
|
|
@@ -108,7 +121,7 @@ export interface AsyncBatcherOptions<TValue> {
|
|
|
108
121
|
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
109
122
|
*/
|
|
110
123
|
onError?: (
|
|
111
|
-
error:
|
|
124
|
+
error: Error,
|
|
112
125
|
batch: Array<TValue>,
|
|
113
126
|
batcher: AsyncBatcher<TValue>,
|
|
114
127
|
) => void
|
|
@@ -148,6 +161,19 @@ export interface AsyncBatcherOptions<TValue> {
|
|
|
148
161
|
wait?: number | ((asyncBatcher: AsyncBatcher<TValue>) => number)
|
|
149
162
|
}
|
|
150
163
|
|
|
164
|
+
/**
|
|
165
|
+
* Utility function for sharing common `AsyncBatcherOptions` options between different `AsyncBatcher` instances.
|
|
166
|
+
*
|
|
167
|
+
*/
|
|
168
|
+
export function asyncBatcherOptions<
|
|
169
|
+
TValue = any,
|
|
170
|
+
TOptions extends Partial<AsyncBatcherOptions<TValue>> = Partial<
|
|
171
|
+
AsyncBatcherOptions<TValue>
|
|
172
|
+
>,
|
|
173
|
+
>(options: TOptions): TOptions {
|
|
174
|
+
return options
|
|
175
|
+
}
|
|
176
|
+
|
|
151
177
|
type AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<
|
|
152
178
|
Required<AsyncBatcherOptions<TValue>>,
|
|
153
179
|
| 'initialState'
|
|
@@ -159,6 +185,9 @@ type AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<
|
|
|
159
185
|
>
|
|
160
186
|
|
|
161
187
|
const defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {
|
|
188
|
+
asyncRetryerOptions: {
|
|
189
|
+
maxAttempts: 1,
|
|
190
|
+
},
|
|
162
191
|
getShouldExecute: () => false,
|
|
163
192
|
maxSize: Infinity,
|
|
164
193
|
started: true,
|
|
@@ -169,13 +198,19 @@ const defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {
|
|
|
169
198
|
/**
|
|
170
199
|
* A class that collects items and processes them in batches asynchronously.
|
|
171
200
|
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
* -
|
|
175
|
-
* -
|
|
176
|
-
* -
|
|
177
|
-
* -
|
|
201
|
+
* Async vs Sync Versions:
|
|
202
|
+
* The async version provides advanced features over the sync Batcher:
|
|
203
|
+
* - Returns promises that can be awaited for batch results
|
|
204
|
+
* - Built-in retry support via AsyncRetryer integration
|
|
205
|
+
* - Abort support to cancel in-flight batch executions
|
|
206
|
+
* - Cancel support to prevent pending batches from starting
|
|
207
|
+
* - Comprehensive error handling with onError callbacks and throwOnError control
|
|
208
|
+
* - Detailed execution tracking (success/error/settle counts)
|
|
209
|
+
*
|
|
210
|
+
* The sync Batcher is lighter weight and simpler when you don't need async features,
|
|
211
|
+
* return values, or execution control.
|
|
178
212
|
*
|
|
213
|
+
* What is Batching?
|
|
179
214
|
* Batching is a technique for grouping multiple operations together to be processed as a single unit.
|
|
180
215
|
*
|
|
181
216
|
* The AsyncBatcher provides a flexible way to implement async batching with configurable:
|
|
@@ -233,6 +268,10 @@ export class AsyncBatcher<TValue> {
|
|
|
233
268
|
)
|
|
234
269
|
key: string
|
|
235
270
|
options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>
|
|
271
|
+
asyncRetryers = new Map<
|
|
272
|
+
number,
|
|
273
|
+
AsyncRetryer<(items: Array<TValue>) => Promise<any>>
|
|
274
|
+
>()
|
|
236
275
|
#timeoutId: NodeJS.Timeout | null = null
|
|
237
276
|
|
|
238
277
|
constructor(
|
|
@@ -254,6 +293,11 @@ export class AsyncBatcher<TValue> {
|
|
|
254
293
|
})
|
|
255
294
|
}
|
|
256
295
|
|
|
296
|
+
/**
|
|
297
|
+
* Emits a change event for the async batcher instance. Mostly useful for devtools.
|
|
298
|
+
*/
|
|
299
|
+
_emit = () => emitChange('AsyncBatcher', this)
|
|
300
|
+
|
|
257
301
|
/**
|
|
258
302
|
* Updates the async batcher options
|
|
259
303
|
*/
|
|
@@ -293,8 +337,12 @@ export class AsyncBatcher<TValue> {
|
|
|
293
337
|
/**
|
|
294
338
|
* Adds an item to the async batcher
|
|
295
339
|
* If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
|
|
340
|
+
*
|
|
341
|
+
* @returns The result from the batch function, or undefined if an error occurred and was handled by onError
|
|
342
|
+
*
|
|
343
|
+
* @throws The error from the batch function if no onError handler is configured or throwOnError is true
|
|
296
344
|
*/
|
|
297
|
-
addItem = (item: TValue):
|
|
345
|
+
addItem = async (item: TValue): Promise<any> => {
|
|
298
346
|
this.#setState({
|
|
299
347
|
items: [...this.store.state.items, item],
|
|
300
348
|
isPending: this.options.wait !== Infinity,
|
|
@@ -306,10 +354,11 @@ export class AsyncBatcher<TValue> {
|
|
|
306
354
|
this.options.getShouldExecute(this.store.state.items, this)
|
|
307
355
|
|
|
308
356
|
if (shouldProcess) {
|
|
309
|
-
this.#execute()
|
|
357
|
+
return await this.#execute()
|
|
310
358
|
} else if (this.options.wait !== Infinity) {
|
|
311
359
|
this.#clearTimeout() // clear any pending timeout to replace it with a new one
|
|
312
360
|
this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())
|
|
361
|
+
await new Promise((resolve) => setTimeout(resolve, this.#getWait()))
|
|
313
362
|
}
|
|
314
363
|
}
|
|
315
364
|
|
|
@@ -330,14 +379,20 @@ export class AsyncBatcher<TValue> {
|
|
|
330
379
|
return undefined
|
|
331
380
|
}
|
|
332
381
|
|
|
382
|
+
const currentExecuteCount = this.store.state.executeCount + 1
|
|
333
383
|
const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)
|
|
334
384
|
this.clear() // Clear items before processing to prevent race conditions
|
|
335
385
|
this.options.onItemsChange?.(this)
|
|
336
386
|
|
|
337
|
-
this.#setState({ isExecuting: true })
|
|
387
|
+
this.#setState({ isExecuting: true, executeCount: currentExecuteCount })
|
|
338
388
|
|
|
339
389
|
try {
|
|
340
|
-
const
|
|
390
|
+
const currentAsyncRetryer = new AsyncRetryer(
|
|
391
|
+
this.fn,
|
|
392
|
+
this.options.asyncRetryerOptions,
|
|
393
|
+
)
|
|
394
|
+
this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)
|
|
395
|
+
const result = await currentAsyncRetryer.execute(batch) // EXECUTE
|
|
341
396
|
this.#setState({
|
|
342
397
|
totalItemsProcessed:
|
|
343
398
|
this.store.state.totalItemsProcessed + batch.length,
|
|
@@ -352,12 +407,13 @@ export class AsyncBatcher<TValue> {
|
|
|
352
407
|
failedItems: [...this.store.state.failedItems, ...batch],
|
|
353
408
|
totalItemsFailed: this.store.state.totalItemsFailed + batch.length,
|
|
354
409
|
})
|
|
355
|
-
this.options.onError?.(error, batch, this)
|
|
410
|
+
this.options.onError?.(error as Error, batch, this)
|
|
356
411
|
if (this.options.throwOnError) {
|
|
357
412
|
throw error
|
|
358
413
|
}
|
|
359
414
|
return undefined
|
|
360
415
|
} finally {
|
|
416
|
+
this.asyncRetryers.delete(currentExecuteCount) // dispose retryer
|
|
361
417
|
this.#setState({
|
|
362
418
|
isExecuting: false,
|
|
363
419
|
settleCount: this.store.state.settleCount + 1,
|
|
@@ -399,23 +455,95 @@ export class AsyncBatcher<TValue> {
|
|
|
399
455
|
this.#setState({ items: [], failedItems: [], isPending: false })
|
|
400
456
|
}
|
|
401
457
|
|
|
458
|
+
/**
|
|
459
|
+
* Returns the AbortSignal for a specific execution.
|
|
460
|
+
* If no executeCount is provided, returns the signal for the most recent execution.
|
|
461
|
+
* Returns null if no execution is found or not currently executing.
|
|
462
|
+
*
|
|
463
|
+
* @param executeCount - Optional specific execution to get signal for
|
|
464
|
+
* @example
|
|
465
|
+
* ```typescript
|
|
466
|
+
* const batcher = new AsyncBatcher(
|
|
467
|
+
* async (items: string[]) => {
|
|
468
|
+
* const signal = batcher.getAbortSignal()
|
|
469
|
+
* if (signal) {
|
|
470
|
+
* const response = await fetch('/api/batch', {
|
|
471
|
+
* method: 'POST',
|
|
472
|
+
* body: JSON.stringify(items),
|
|
473
|
+
* signal
|
|
474
|
+
* })
|
|
475
|
+
* return response.json()
|
|
476
|
+
* }
|
|
477
|
+
* },
|
|
478
|
+
* { maxSize: 10, wait: 100 }
|
|
479
|
+
* )
|
|
480
|
+
* ```
|
|
481
|
+
*/
|
|
482
|
+
getAbortSignal(executeCount?: number): AbortSignal | null {
|
|
483
|
+
const count = executeCount ?? this.store.state.executeCount
|
|
484
|
+
const retryer = this.asyncRetryers.get(count)
|
|
485
|
+
return retryer?.getAbortSignal() ?? null
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Aborts all ongoing executions with the internal abort controllers.
|
|
490
|
+
* Does NOT cancel any pending execution that have not started yet.
|
|
491
|
+
* Does NOT clear out the items.
|
|
492
|
+
*/
|
|
493
|
+
abort = (): void => {
|
|
494
|
+
this.asyncRetryers.forEach((retryer) => retryer.abort())
|
|
495
|
+
this.asyncRetryers.clear()
|
|
496
|
+
this.#setState({
|
|
497
|
+
isExecuting: false,
|
|
498
|
+
})
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Cancels any pending execution that have not started yet.
|
|
503
|
+
* Does NOT abort any execution already in progress.
|
|
504
|
+
* Does NOT clear out the items.
|
|
505
|
+
*/
|
|
506
|
+
cancel = (): void => {
|
|
507
|
+
this.#clearTimeout()
|
|
508
|
+
this.#setState({
|
|
509
|
+
isPending: false,
|
|
510
|
+
})
|
|
511
|
+
}
|
|
512
|
+
|
|
402
513
|
/**
|
|
403
514
|
* Resets the async batcher state to its default values
|
|
404
515
|
*/
|
|
405
516
|
reset = (): void => {
|
|
406
517
|
this.#setState(getDefaultAsyncBatcherState<TValue>())
|
|
407
518
|
this.options.onItemsChange?.(this)
|
|
519
|
+
this.asyncRetryers.forEach((retryer) => retryer.reset())
|
|
408
520
|
}
|
|
409
521
|
}
|
|
410
522
|
|
|
411
523
|
/**
|
|
412
|
-
* Creates an async batcher that processes items in batches
|
|
524
|
+
* Creates an async batcher that processes items in batches.
|
|
525
|
+
*
|
|
526
|
+
* Async vs Sync Versions:
|
|
527
|
+
* The async version provides advanced features over the sync batch function:
|
|
528
|
+
* - Returns promises that can be awaited for batch results
|
|
529
|
+
* - Built-in retry support via AsyncRetryer integration
|
|
530
|
+
* - Abort support to cancel in-flight batch executions
|
|
531
|
+
* - Cancel support to prevent pending batches from starting
|
|
532
|
+
* - Comprehensive error handling with onError callbacks and throwOnError control
|
|
533
|
+
* - Detailed execution tracking (success/error/settle counts)
|
|
413
534
|
*
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
535
|
+
* The sync batch function is lighter weight and simpler when you don't need async features,
|
|
536
|
+
* return values, or execution control.
|
|
537
|
+
*
|
|
538
|
+
* What is Batching?
|
|
539
|
+
* Batching is a technique for grouping multiple operations together to be processed as a single unit.
|
|
540
|
+
*
|
|
541
|
+
* Configuration Options:
|
|
542
|
+
* - `maxSize`: Maximum number of items per batch (default: Infinity)
|
|
543
|
+
* - `wait`: Time to wait before processing batch (default: Infinity)
|
|
544
|
+
* - `getShouldExecute`: Custom logic to trigger batch processing
|
|
545
|
+
* - `asyncRetryerOptions`: Configure retry behavior for batch executions
|
|
546
|
+
* - `started`: Whether to start processing immediately (default: true)
|
|
419
547
|
*
|
|
420
548
|
* Error Handling:
|
|
421
549
|
* - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
|
|
@@ -430,7 +558,6 @@ export class AsyncBatcher<TValue> {
|
|
|
430
558
|
* - Use `onSuccess` callback to react to successful batch execution and implement custom logic
|
|
431
559
|
* - Use `onError` callback to react to batch execution errors and implement custom error handling
|
|
432
560
|
* - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
|
|
433
|
-
* - Use `onExecute` callback to react to batch execution and implement custom logic
|
|
434
561
|
* - Use `onItemsChange` callback to react to items being added or removed from the batcher
|
|
435
562
|
* - The state includes total items processed, success/error counts, and execution status
|
|
436
563
|
* - State can be accessed via the underlying AsyncBatcher instance's `store.state` property
|