File size: 596 Bytes
7d9309d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import pLimit from 'p-limit'

const MAX_CONCURRENT = 10
const MAX_QUEUE_DEPTH = 50
const queueLimit = pLimit(MAX_CONCURRENT)

let queueLength = 0

export function getQueueLength(): number {
  return queueLength
}

export async function enqueueTask<T>(
  fn: () => Promise<T>
): Promise<{queued: boolean; result?: T; error?: string}> {
  if (queueLength >= MAX_QUEUE_DEPTH) {
    return {queued: false, error: 'too_many_requests'}
  }
  queueLength++
  try {
    const result = await queueLimit(fn)
    return {queued: true, result}
  } finally {
    queueLength--
  }
}