@tanstack/pacer-lite 0.2.1 → 0.3.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/README.md +29 -14
- package/dist/lite-batcher.d.ts +4 -6
- package/dist/lite-batcher.js +72 -45
- package/dist/lite-debouncer.d.ts +5 -9
- package/dist/lite-debouncer.js +58 -40
- package/dist/lite-queuer.d.ts +5 -7
- package/dist/lite-queuer.js +170 -89
- package/dist/lite-rate-limiter.d.ts +5 -9
- package/dist/lite-rate-limiter.js +89 -63
- package/dist/lite-throttler.d.ts +5 -9
- package/dist/lite-throttler.js +63 -40
- package/dist/pacer/dist/types.d.ts +7 -0
- package/package.json +13 -33
- package/dist/index.cjs +0 -16
- package/dist/index.d.cts +0 -6
- package/dist/lite-batcher.cjs +0 -175
- package/dist/lite-batcher.cjs.map +0 -1
- package/dist/lite-batcher.d.cts +0 -184
- package/dist/lite-batcher.js.map +0 -1
- package/dist/lite-debouncer.cjs +0 -125
- package/dist/lite-debouncer.cjs.map +0 -1
- package/dist/lite-debouncer.d.cts +0 -127
- package/dist/lite-debouncer.js.map +0 -1
- package/dist/lite-queuer.cjs +0 -208
- package/dist/lite-queuer.cjs.map +0 -1
- package/dist/lite-queuer.d.cts +0 -243
- package/dist/lite-queuer.js.map +0 -1
- package/dist/lite-rate-limiter.cjs +0 -149
- package/dist/lite-rate-limiter.cjs.map +0 -1
- package/dist/lite-rate-limiter.d.cts +0 -149
- package/dist/lite-rate-limiter.js.map +0 -1
- package/dist/lite-throttler.cjs +0 -127
- package/dist/lite-throttler.cjs.map +0 -1
- package/dist/lite-throttler.d.cts +0 -134
- package/dist/lite-throttler.js.map +0 -1
- package/src/index.ts +0 -5
- package/src/lite-batcher.ts +0 -267
- package/src/lite-debouncer.ts +0 -184
- package/src/lite-queuer.ts +0 -434
- package/src/lite-rate-limiter.ts +0 -246
- package/src/lite-throttler.ts +0 -195
package/src/lite-queuer.ts
DELETED
|
@@ -1,434 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Position type for addItem and getNextItem operations.
|
|
3
|
-
*
|
|
4
|
-
* - 'front': Operate on the front of the queue (FIFO for getNextItem)
|
|
5
|
-
* - 'back': Operate on the back of the queue (LIFO for getNextItem)
|
|
6
|
-
*/
|
|
7
|
-
export type QueuePosition = 'front' | 'back'
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Options for configuring a lite queuer instance
|
|
11
|
-
*/
|
|
12
|
-
export interface LiteQueuerOptions<TValue> {
|
|
13
|
-
/**
|
|
14
|
-
* Default position to add items to the queue
|
|
15
|
-
* @default 'back'
|
|
16
|
-
*/
|
|
17
|
-
addItemsTo?: QueuePosition
|
|
18
|
-
/**
|
|
19
|
-
* Default position to get items from during processing
|
|
20
|
-
* @default 'front'
|
|
21
|
-
*/
|
|
22
|
-
getItemsFrom?: QueuePosition
|
|
23
|
-
/**
|
|
24
|
-
* Function to determine priority of items in the queue
|
|
25
|
-
* Higher priority items will be processed first
|
|
26
|
-
* Return undefined for items that should use positional ordering
|
|
27
|
-
*/
|
|
28
|
-
getPriority?: (item: TValue) => number | undefined
|
|
29
|
-
/**
|
|
30
|
-
* Initial items to populate the queue with
|
|
31
|
-
*/
|
|
32
|
-
initialItems?: Array<TValue>
|
|
33
|
-
/**
|
|
34
|
-
* Maximum number of items allowed in the queue
|
|
35
|
-
*/
|
|
36
|
-
maxSize?: number
|
|
37
|
-
/**
|
|
38
|
-
* Whether the queuer should start processing items immediately
|
|
39
|
-
* @default true
|
|
40
|
-
*/
|
|
41
|
-
started?: boolean
|
|
42
|
-
/**
|
|
43
|
-
* Time in milliseconds to wait between processing items
|
|
44
|
-
* @default 0
|
|
45
|
-
*/
|
|
46
|
-
wait?: number
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* A lightweight class that creates a queue for processing items.
|
|
51
|
-
*
|
|
52
|
-
* This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
|
|
53
|
-
* suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
|
|
54
|
-
* this version does not use TanStack Store for state management, has no devtools integration,
|
|
55
|
-
* no callbacks, and provides only essential queueing functionality.
|
|
56
|
-
*
|
|
57
|
-
* The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
|
|
58
|
-
* processing of items. Items can be processed automatically with configurable wait times
|
|
59
|
-
* between executions, or processed manually using the execute methods.
|
|
60
|
-
*
|
|
61
|
-
* Features included:
|
|
62
|
-
* - Automatic or manual processing of items
|
|
63
|
-
* - FIFO, LIFO, and priority-based ordering
|
|
64
|
-
* - Queue size limits with item rejection
|
|
65
|
-
* - Configurable wait times between processing
|
|
66
|
-
* - Batch processing capabilities
|
|
67
|
-
* - Start/stop processing control
|
|
68
|
-
* - Callback support for monitoring execution, rejection, and state change events
|
|
69
|
-
*
|
|
70
|
-
* Features NOT included (compared to core Queuer):
|
|
71
|
-
* - No TanStack Store state management
|
|
72
|
-
* - No devtools integration
|
|
73
|
-
* - No item expiration functionality (no onExpire callback)
|
|
74
|
-
* - No dynamic options updates (setOptions)
|
|
75
|
-
* - No detailed state tracking (execution counts, etc.)
|
|
76
|
-
*
|
|
77
|
-
* Queue behavior:
|
|
78
|
-
* - Default: FIFO (add to back, process from front)
|
|
79
|
-
* - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
|
|
80
|
-
* - Priority: Provide getPriority function; higher values processed first
|
|
81
|
-
*
|
|
82
|
-
* @example
|
|
83
|
-
* ```ts
|
|
84
|
-
* // Basic FIFO queue
|
|
85
|
-
* const queue = new LiteQueuer((item: string) => {
|
|
86
|
-
* console.log('Processing:', item);
|
|
87
|
-
* }, { wait: 100 });
|
|
88
|
-
*
|
|
89
|
-
* queue.addItem('task1');
|
|
90
|
-
* queue.addItem('task2');
|
|
91
|
-
* // Processes: task1, then task2 after 100ms delay
|
|
92
|
-
* ```
|
|
93
|
-
*
|
|
94
|
-
* @example
|
|
95
|
-
* ```ts
|
|
96
|
-
* // Priority queue
|
|
97
|
-
* const priorityQueue = new LiteQueuer((item: Task) => {
|
|
98
|
-
* processTask(item);
|
|
99
|
-
* }, {
|
|
100
|
-
* getPriority: task => task.priority,
|
|
101
|
-
* wait: 500
|
|
102
|
-
* });
|
|
103
|
-
*
|
|
104
|
-
* priorityQueue.addItem({ name: 'low', priority: 1 });
|
|
105
|
-
* priorityQueue.addItem({ name: 'high', priority: 10 });
|
|
106
|
-
* // Processes high priority task first
|
|
107
|
-
* ```
|
|
108
|
-
*/
|
|
109
|
-
export class LiteQueuer<TValue> {
|
|
110
|
-
private items: Array<TValue> = []
|
|
111
|
-
private timeoutId: NodeJS.Timeout | null = null
|
|
112
|
-
private isRunning = true
|
|
113
|
-
private pendingTick = false
|
|
114
|
-
|
|
115
|
-
constructor(
|
|
116
|
-
public fn: (item: TValue) => void,
|
|
117
|
-
public options: LiteQueuerOptions<TValue> = {},
|
|
118
|
-
) {
|
|
119
|
-
// Set defaults
|
|
120
|
-
this.options.addItemsTo = this.options.addItemsTo ?? 'back'
|
|
121
|
-
this.options.getItemsFrom = this.options.getItemsFrom ?? 'front'
|
|
122
|
-
this.options.maxSize = this.options.maxSize ?? Infinity
|
|
123
|
-
this.options.started = this.options.started ?? true
|
|
124
|
-
this.options.wait = this.options.wait ?? 0
|
|
125
|
-
|
|
126
|
-
this.isRunning = this.options.started
|
|
127
|
-
|
|
128
|
-
// Add initial items if provided
|
|
129
|
-
if (this.options.initialItems) {
|
|
130
|
-
for (const item of this.options.initialItems) {
|
|
131
|
-
this.addItem(item, this.options.addItemsTo, false)
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// Start processing if enabled and has items
|
|
136
|
-
if (this.isRunning && this.items.length > 0) {
|
|
137
|
-
this.tick()
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Number of items currently in the queue
|
|
143
|
-
*/
|
|
144
|
-
get size(): number {
|
|
145
|
-
return this.items.length
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Whether the queue is empty
|
|
150
|
-
*/
|
|
151
|
-
get isEmpty(): boolean {
|
|
152
|
-
return this.items.length === 0
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Whether the queue is currently running (auto-processing items)
|
|
157
|
-
*/
|
|
158
|
-
get isQueueRunning(): boolean {
|
|
159
|
-
return this.isRunning
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Adds an item to the queue. If the queue is full, the item is rejected.
|
|
164
|
-
* Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.
|
|
165
|
-
*
|
|
166
|
-
* Returns true if the item was added, false if the queue is full.
|
|
167
|
-
*
|
|
168
|
-
* @example
|
|
169
|
-
* ```ts
|
|
170
|
-
* queue.addItem('task1'); // Add to default position (back)
|
|
171
|
-
* queue.addItem('task2', 'front'); // Add to front
|
|
172
|
-
* ```
|
|
173
|
-
*/
|
|
174
|
-
addItem = (
|
|
175
|
-
item: TValue,
|
|
176
|
-
position: QueuePosition = this.options.addItemsTo!,
|
|
177
|
-
startProcessing: boolean = true,
|
|
178
|
-
): boolean => {
|
|
179
|
-
// Check size limit
|
|
180
|
-
if (this.items.length >= this.options.maxSize!) {
|
|
181
|
-
return false
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// Handle priority insertion
|
|
185
|
-
if (this.options.getPriority) {
|
|
186
|
-
const priority = this.options.getPriority(item)
|
|
187
|
-
if (priority !== undefined) {
|
|
188
|
-
// Find insertion point for priority
|
|
189
|
-
const insertIndex = this.items.findIndex((existing) => {
|
|
190
|
-
const existingPriority = this.options.getPriority!(existing)
|
|
191
|
-
// Treat undefined priority as negative infinity for comparison
|
|
192
|
-
const effectivePriority = existingPriority ?? -Infinity
|
|
193
|
-
return effectivePriority < priority
|
|
194
|
-
})
|
|
195
|
-
|
|
196
|
-
if (insertIndex === -1) {
|
|
197
|
-
this.items.push(item)
|
|
198
|
-
} else {
|
|
199
|
-
this.items.splice(insertIndex, 0, item)
|
|
200
|
-
}
|
|
201
|
-
} else {
|
|
202
|
-
// No priority, use position
|
|
203
|
-
this.insertAtPosition(item, position)
|
|
204
|
-
}
|
|
205
|
-
} else {
|
|
206
|
-
// No priority function, use position
|
|
207
|
-
this.insertAtPosition(item, position)
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Start processing if running and not already processing
|
|
211
|
-
if (startProcessing && this.isRunning && !this.pendingTick) {
|
|
212
|
-
this.tick()
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
return true
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
private insertAtPosition = (item: TValue, position: QueuePosition): void => {
|
|
219
|
-
if (position === 'front') {
|
|
220
|
-
this.items.unshift(item)
|
|
221
|
-
} else {
|
|
222
|
-
this.items.push(item)
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Removes and returns the next item from the queue without executing the function.
|
|
228
|
-
* Use for manual queue management. Normally, use execute() to process items.
|
|
229
|
-
*
|
|
230
|
-
* @example
|
|
231
|
-
* ```ts
|
|
232
|
-
* const nextItem = queue.getNextItem(); // Get from default position (front)
|
|
233
|
-
* const lastItem = queue.getNextItem('back'); // Get from back (LIFO)
|
|
234
|
-
* ```
|
|
235
|
-
*/
|
|
236
|
-
getNextItem = (
|
|
237
|
-
position: QueuePosition = this.options.getItemsFrom!,
|
|
238
|
-
): TValue | undefined => {
|
|
239
|
-
if (this.items.length === 0) {
|
|
240
|
-
return undefined
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
let item: TValue | undefined
|
|
244
|
-
|
|
245
|
-
// When priority function is provided, always get from front (highest priority)
|
|
246
|
-
if (this.options.getPriority || position === 'front') {
|
|
247
|
-
item = this.items.shift()
|
|
248
|
-
} else {
|
|
249
|
-
item = this.items.pop()
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
return item
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/**
|
|
256
|
-
* Removes and returns the next item from the queue and processes it using the provided function.
|
|
257
|
-
*
|
|
258
|
-
* @example
|
|
259
|
-
* ```ts
|
|
260
|
-
* queue.execute(); // Execute from default position
|
|
261
|
-
* queue.execute('back'); // Execute from back (LIFO)
|
|
262
|
-
* ```
|
|
263
|
-
*/
|
|
264
|
-
execute = (position?: QueuePosition): TValue | undefined => {
|
|
265
|
-
const item = this.getNextItem(position)
|
|
266
|
-
if (item !== undefined) {
|
|
267
|
-
this.fn(item)
|
|
268
|
-
}
|
|
269
|
-
return item
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/**
|
|
273
|
-
* Internal method that processes items in the queue with wait intervals
|
|
274
|
-
*/
|
|
275
|
-
private tick = (): void => {
|
|
276
|
-
if (!this.isRunning) {
|
|
277
|
-
this.pendingTick = false
|
|
278
|
-
return
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
this.pendingTick = true
|
|
282
|
-
|
|
283
|
-
// Process items while queue is not empty
|
|
284
|
-
while (this.items.length > 0) {
|
|
285
|
-
const item = this.execute(this.options.getItemsFrom)
|
|
286
|
-
if (item === undefined) {
|
|
287
|
-
break
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
const wait = this.options.wait!
|
|
291
|
-
if (wait > 0) {
|
|
292
|
-
// Schedule next processing after wait time
|
|
293
|
-
this.timeoutId = setTimeout(() => this.tick(), wait)
|
|
294
|
-
return
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// No wait time, continue processing immediately
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
this.pendingTick = false
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/**
|
|
304
|
-
* Starts processing items in the queue. If already running, does nothing.
|
|
305
|
-
*/
|
|
306
|
-
start = (): void => {
|
|
307
|
-
this.isRunning = true
|
|
308
|
-
if (!this.pendingTick && this.items.length > 0) {
|
|
309
|
-
this.tick()
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* Stops processing items in the queue. Does not clear the queue.
|
|
315
|
-
*/
|
|
316
|
-
stop = (): void => {
|
|
317
|
-
this.clearTimeout()
|
|
318
|
-
this.isRunning = false
|
|
319
|
-
this.pendingTick = false
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* Clears any pending timeout
|
|
324
|
-
*/
|
|
325
|
-
private clearTimeout = (): void => {
|
|
326
|
-
if (this.timeoutId) {
|
|
327
|
-
clearTimeout(this.timeoutId)
|
|
328
|
-
this.timeoutId = null
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/**
|
|
333
|
-
* Returns the next item in the queue without removing it.
|
|
334
|
-
*
|
|
335
|
-
* @example
|
|
336
|
-
* ```ts
|
|
337
|
-
* const next = queue.peekNextItem(); // Peek at front
|
|
338
|
-
* const last = queue.peekNextItem('back'); // Peek at back
|
|
339
|
-
* ```
|
|
340
|
-
*/
|
|
341
|
-
peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {
|
|
342
|
-
if (this.items.length === 0) {
|
|
343
|
-
return undefined
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
if (this.options.getPriority || position === 'front') {
|
|
347
|
-
return this.items[0]
|
|
348
|
-
} else {
|
|
349
|
-
return this.items[this.items.length - 1]
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
* Returns a copy of all items in the queue.
|
|
355
|
-
*/
|
|
356
|
-
peekAllItems = (): Array<TValue> => {
|
|
357
|
-
return [...this.items]
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
/**
|
|
361
|
-
* Processes a specified number of items immediately with no wait time.
|
|
362
|
-
* If no numberOfItems is provided, all items will be processed.
|
|
363
|
-
*
|
|
364
|
-
* @example
|
|
365
|
-
* ```ts
|
|
366
|
-
* queue.flush(); // Process all items immediately
|
|
367
|
-
* queue.flush(3); // Process next 3 items immediately
|
|
368
|
-
* ```
|
|
369
|
-
*/
|
|
370
|
-
flush = (
|
|
371
|
-
numberOfItems: number = this.items.length,
|
|
372
|
-
position?: QueuePosition,
|
|
373
|
-
): void => {
|
|
374
|
-
this.clearTimeout() // Clear any pending timeout
|
|
375
|
-
for (let i = 0; i < numberOfItems && this.items.length > 0; i++) {
|
|
376
|
-
this.execute(position)
|
|
377
|
-
}
|
|
378
|
-
// Restart normal processing if still running and has items
|
|
379
|
-
if (this.isRunning && this.items.length > 0 && !this.pendingTick) {
|
|
380
|
-
this.tick()
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
/**
|
|
385
|
-
* Processes all items in the queue as a batch using the provided function.
|
|
386
|
-
* The queue is cleared after processing.
|
|
387
|
-
*
|
|
388
|
-
* @example
|
|
389
|
-
* ```ts
|
|
390
|
-
* queue.flushAsBatch((items) => {
|
|
391
|
-
* console.log('Processing batch:', items);
|
|
392
|
-
* // Process all items together
|
|
393
|
-
* });
|
|
394
|
-
* ```
|
|
395
|
-
*/
|
|
396
|
-
flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {
|
|
397
|
-
const items = this.peekAllItems()
|
|
398
|
-
this.clear()
|
|
399
|
-
batchFunction(items)
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Removes all items from the queue. Does not affect items being processed.
|
|
404
|
-
*/
|
|
405
|
-
clear = (): void => {
|
|
406
|
-
this.items = []
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Creates a lightweight queue that processes items using the provided function.
|
|
412
|
-
*
|
|
413
|
-
* This is an alternative to the queue function in the core @tanstack/pacer package, but is more
|
|
414
|
-
* suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
|
|
415
|
-
* this function creates a queuer with no external dependencies, devtools integration, or reactive state.
|
|
416
|
-
*
|
|
417
|
-
* @example
|
|
418
|
-
* ```ts
|
|
419
|
-
* const processItem = liteQueue((item: string) => {
|
|
420
|
-
* console.log('Processing:', item);
|
|
421
|
-
* }, { wait: 1000 });
|
|
422
|
-
*
|
|
423
|
-
* processItem('task1');
|
|
424
|
-
* processItem('task2');
|
|
425
|
-
* // Processes each item with 1 second delay between them
|
|
426
|
-
* ```
|
|
427
|
-
*/
|
|
428
|
-
export function liteQueue<TValue>(
|
|
429
|
-
fn: (item: TValue) => void,
|
|
430
|
-
options: LiteQueuerOptions<TValue> = {},
|
|
431
|
-
): (item: TValue) => boolean {
|
|
432
|
-
const queuer = new LiteQueuer(fn, options)
|
|
433
|
-
return (item: TValue) => queuer.addItem(item)
|
|
434
|
-
}
|
package/src/lite-rate-limiter.ts
DELETED
|
@@ -1,246 +0,0 @@
|
|
|
1
|
-
import type { AnyFunction } from '@tanstack/pacer/types'
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Options for configuring a lite rate-limited function
|
|
5
|
-
*/
|
|
6
|
-
export interface LiteRateLimiterOptions<TFn extends AnyFunction = AnyFunction> {
|
|
7
|
-
/**
|
|
8
|
-
* Maximum number of executions allowed within the time window.
|
|
9
|
-
*/
|
|
10
|
-
limit: number
|
|
11
|
-
/**
|
|
12
|
-
* Callback function that is called after the function is executed
|
|
13
|
-
*/
|
|
14
|
-
onExecute?: (args: Parameters<TFn>, rateLimiter: LiteRateLimiter<TFn>) => void
|
|
15
|
-
/**
|
|
16
|
-
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
17
|
-
*/
|
|
18
|
-
onReject?: (rateLimiter: LiteRateLimiter<TFn>) => void
|
|
19
|
-
/**
|
|
20
|
-
* Time window in milliseconds within which the limit applies.
|
|
21
|
-
*/
|
|
22
|
-
window: number
|
|
23
|
-
/**
|
|
24
|
-
* Type of window to use for rate limiting
|
|
25
|
-
* - 'fixed': Uses a fixed window that resets after the window period
|
|
26
|
-
* - 'sliding': Uses a sliding window that allows executions as old ones expire
|
|
27
|
-
* Defaults to 'fixed'
|
|
28
|
-
*/
|
|
29
|
-
windowType?: 'fixed' | 'sliding'
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* A lightweight class that creates a rate-limited function.
|
|
34
|
-
*
|
|
35
|
-
* This is an alternative to the RateLimiter in the core @tanstack/pacer package, but is more
|
|
36
|
-
* suitable for libraries and npm packages that need minimal overhead. Unlike the core RateLimiter,
|
|
37
|
-
* this version does not use TanStack Store for state management, has no devtools integration,
|
|
38
|
-
* and provides only essential rate limiting functionality.
|
|
39
|
-
*
|
|
40
|
-
* Rate limiting allows a function to execute up to a limit within a time window,
|
|
41
|
-
* then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
|
|
42
|
-
* all executions happen immediately, followed by a complete block.
|
|
43
|
-
*
|
|
44
|
-
* The rate limiter supports two types of windows:
|
|
45
|
-
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
46
|
-
* towards the limit, and the window resets completely after the period.
|
|
47
|
-
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
48
|
-
* consistent rate of execution over time.
|
|
49
|
-
*
|
|
50
|
-
* Features:
|
|
51
|
-
* - Zero dependencies - no external libraries required
|
|
52
|
-
* - Minimal API surface - only essential methods (maybeExecute, getRemainingInWindow, getMsUntilNextWindow, reset)
|
|
53
|
-
* - Simple state management - uses basic private properties instead of reactive stores
|
|
54
|
-
* - Lightweight - designed for use in npm packages where bundle size matters
|
|
55
|
-
*
|
|
56
|
-
* @example
|
|
57
|
-
* ```ts
|
|
58
|
-
* const rateLimiter = new LiteRateLimiter((id: string) => {
|
|
59
|
-
* api.getData(id);
|
|
60
|
-
* }, { limit: 5, window: 1000 });
|
|
61
|
-
*
|
|
62
|
-
* // First 5 calls will execute, then block until window resets
|
|
63
|
-
* if (rateLimiter.maybeExecute('123')) {
|
|
64
|
-
* console.log('API call made');
|
|
65
|
-
* } else {
|
|
66
|
-
* console.log('Rate limited - try again in', rateLimiter.getMsUntilNextWindow(), 'ms');
|
|
67
|
-
* }
|
|
68
|
-
* ```
|
|
69
|
-
*/
|
|
70
|
-
export class LiteRateLimiter<TFn extends AnyFunction> {
|
|
71
|
-
private executionTimes: Array<number> = []
|
|
72
|
-
private timeoutIds: Set<NodeJS.Timeout> = new Set()
|
|
73
|
-
|
|
74
|
-
constructor(
|
|
75
|
-
public fn: TFn,
|
|
76
|
-
public options: LiteRateLimiterOptions<TFn>,
|
|
77
|
-
) {
|
|
78
|
-
// Default windowType to 'fixed' if not specified
|
|
79
|
-
if (this.options.windowType === undefined) {
|
|
80
|
-
this.options.windowType = 'fixed'
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Attempts to execute the rate-limited function if within the configured limits.
|
|
86
|
-
* Returns true if executed, false if rejected due to rate limiting.
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```ts
|
|
90
|
-
* const rateLimiter = new LiteRateLimiter(fn, { limit: 5, window: 1000 });
|
|
91
|
-
*
|
|
92
|
-
* // First 5 calls return true
|
|
93
|
-
* rateLimiter.maybeExecute('arg1', 'arg2'); // true
|
|
94
|
-
*
|
|
95
|
-
* // Additional calls within the window return false
|
|
96
|
-
* rateLimiter.maybeExecute('arg1', 'arg2'); // false
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
maybeExecute = (...args: Parameters<TFn>): boolean => {
|
|
100
|
-
this.cleanupOldExecutions()
|
|
101
|
-
|
|
102
|
-
const relevantExecutionTimes = this.getExecutionTimesInWindow()
|
|
103
|
-
|
|
104
|
-
if (relevantExecutionTimes.length < this.options.limit) {
|
|
105
|
-
this.execute(...args)
|
|
106
|
-
return true
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
this.options.onReject?.(this)
|
|
110
|
-
return false
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
private execute = (...args: Parameters<TFn>): void => {
|
|
114
|
-
const now = Date.now()
|
|
115
|
-
this.fn(...args)
|
|
116
|
-
this.options.onExecute?.(args, this)
|
|
117
|
-
this.executionTimes.push(now)
|
|
118
|
-
this.setCleanupTimeout(now)
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
private getExecutionTimesInWindow = (): Array<number> => {
|
|
122
|
-
if (this.options.windowType === 'sliding') {
|
|
123
|
-
// For sliding window, return all executions within the current window
|
|
124
|
-
return this.executionTimes.filter(
|
|
125
|
-
(time) => time > Date.now() - this.options.window,
|
|
126
|
-
)
|
|
127
|
-
} else {
|
|
128
|
-
// For fixed window, return all executions in the current window
|
|
129
|
-
if (this.executionTimes.length === 0) {
|
|
130
|
-
return []
|
|
131
|
-
}
|
|
132
|
-
const oldestExecution = Math.min(...this.executionTimes)
|
|
133
|
-
const windowStart = oldestExecution
|
|
134
|
-
const windowEnd = windowStart + this.options.window
|
|
135
|
-
const now = Date.now()
|
|
136
|
-
|
|
137
|
-
// If the window has expired, return empty array
|
|
138
|
-
if (now > windowEnd) {
|
|
139
|
-
return []
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
// Otherwise, return all executions in the current window
|
|
143
|
-
return this.executionTimes.filter(
|
|
144
|
-
(time) => time >= windowStart && time <= windowEnd,
|
|
145
|
-
)
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
private setCleanupTimeout = (executionTime: number): void => {
|
|
150
|
-
if (
|
|
151
|
-
this.options.windowType === 'sliding' ||
|
|
152
|
-
this.timeoutIds.size === 0 // new fixed window
|
|
153
|
-
) {
|
|
154
|
-
const now = Date.now()
|
|
155
|
-
const timeUntilExpiration = executionTime - now + this.options.window + 1
|
|
156
|
-
const timeoutId = setTimeout(() => {
|
|
157
|
-
this.cleanupOldExecutions()
|
|
158
|
-
this.clearTimeout(timeoutId)
|
|
159
|
-
}, timeUntilExpiration)
|
|
160
|
-
this.timeoutIds.add(timeoutId)
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
private clearTimeout = (timeoutId: NodeJS.Timeout): void => {
|
|
165
|
-
clearTimeout(timeoutId)
|
|
166
|
-
this.timeoutIds.delete(timeoutId)
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
private clearTimeouts = (): void => {
|
|
170
|
-
this.timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))
|
|
171
|
-
this.timeoutIds.clear()
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
private cleanupOldExecutions = (): void => {
|
|
175
|
-
this.executionTimes = this.getExecutionTimesInWindow()
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Returns the number of remaining executions allowed in the current window.
|
|
180
|
-
*/
|
|
181
|
-
getRemainingInWindow = (): number => {
|
|
182
|
-
const relevantExecutionTimes = this.getExecutionTimesInWindow()
|
|
183
|
-
return Math.max(0, this.options.limit - relevantExecutionTimes.length)
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Returns the number of milliseconds until the next execution will be possible.
|
|
188
|
-
* Returns 0 if executions are currently allowed.
|
|
189
|
-
*/
|
|
190
|
-
getMsUntilNextWindow = (): number => {
|
|
191
|
-
if (this.getRemainingInWindow() > 0) {
|
|
192
|
-
return 0
|
|
193
|
-
}
|
|
194
|
-
const oldestExecution = this.executionTimes[0] ?? Infinity
|
|
195
|
-
return oldestExecution + this.options.window - Date.now()
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Resets the rate limiter state, clearing all execution history.
|
|
200
|
-
*/
|
|
201
|
-
reset = (): void => {
|
|
202
|
-
this.executionTimes = []
|
|
203
|
-
this.clearTimeouts()
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Creates a lightweight rate-limited function that will execute the provided function up to a maximum number of times within a time window.
|
|
209
|
-
*
|
|
210
|
-
* This is an alternative to the rateLimit function in the core @tanstack/pacer package, but is more
|
|
211
|
-
* suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
|
|
212
|
-
* this function creates a rate limiter with no external dependencies, devtools integration, or reactive state.
|
|
213
|
-
*
|
|
214
|
-
* Rate limiting allows all executions until the limit is reached, then blocks all subsequent calls until the window resets.
|
|
215
|
-
* This differs from throttling (which ensures even spacing) and debouncing (which waits for pauses).
|
|
216
|
-
*
|
|
217
|
-
* @example
|
|
218
|
-
* ```ts
|
|
219
|
-
* const rateLimitedApi = liteRateLimit(makeApiCall, {
|
|
220
|
-
* limit: 5,
|
|
221
|
-
* window: 60000, // 1 minute
|
|
222
|
-
* windowType: 'sliding'
|
|
223
|
-
* });
|
|
224
|
-
*
|
|
225
|
-
* // First 5 calls execute immediately
|
|
226
|
-
* // Additional calls are rejected until window allows
|
|
227
|
-
* rateLimitedApi();
|
|
228
|
-
* ```
|
|
229
|
-
*
|
|
230
|
-
* @example
|
|
231
|
-
* ```ts
|
|
232
|
-
* // Fixed window - all 10 calls happen in first second, then 10 second wait
|
|
233
|
-
* const rateLimitedFixed = liteRateLimit(logEvent, {
|
|
234
|
-
* limit: 10,
|
|
235
|
-
* window: 10000,
|
|
236
|
-
* windowType: 'fixed'
|
|
237
|
-
* });
|
|
238
|
-
* ```
|
|
239
|
-
*/
|
|
240
|
-
export function liteRateLimit<TFn extends AnyFunction>(
|
|
241
|
-
fn: TFn,
|
|
242
|
-
options: LiteRateLimiterOptions<TFn>,
|
|
243
|
-
): (...args: Parameters<TFn>) => boolean {
|
|
244
|
-
const rateLimiter = new LiteRateLimiter(fn, options)
|
|
245
|
-
return rateLimiter.maybeExecute
|
|
246
|
-
}
|