All files / utils asyncLimit.ts

92.86% Statements 52/56
91.43% Branches 32/35
100% Functions 9/9
92.86% Lines 52/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152                                                                                            25x                       17x 1x     16x 16x   16x   16x 34x 34x 16x 16x   34x     16x 34x 34x     34x 34x 34x       16x 73x 73x       73x 17x     56x 28x 28x       8x     28x 14x 5x 5x 5x 5x     14x   14x     42x 34x 34x 34x 34x 34x 32x 2x         16x 34x 34x       34x 34x   34x 16x       16x       16x    
export interface AsyncLimitOptions<T extends (...args: any[]) => Promise<any>> {
  /**
   * 并行量。
   *
   * @default 1
   */
  concurrency?: number
 
  /**
   * 每秒最大调用次数,按 1 秒滑动窗口计算。
   *
   * 和 `concurrency` 二选一传入。
   */
  qps?: number
 
  /**
   * 限流滑动窗口长度,仅在传入 `qps` 时生效。
   *
   * 加长窗口可降低实际调用频率、提高容错率,比如设置 `qps: 10, qpsWindow: 1200` 表示 1.2 秒内最多调用 10 次。
   *
   * @default 1000
   */
  qpsWindow?: number
 
  /**
   * 按参数分组,分组之间并行执行,组内按顺序执行。
   *
   * @default 不分组
   */
  groupBy?: (...args: Parameters<T>) => string
}
 
interface QueueItem {
  args: any[]
  resolve: (res: any) => void
}
 
interface GroupState {
  queue: QueueItem[]
  activeCount: number
  /** 滑动窗口内的启动时间戳,仅 qps 模式使用。 */
  startTimes: number[]
  /** 等待限流窗口放行时的定时器,仅 qps 模式使用。 */
  timer: any | null
}
 
const defaultGroupKey = '__DEFAULT__'
 
/**
 * 异步函数并行执行限制。
 *
 * @param asyncFn 异步函数
 * @param options 选项
 */
export function asyncLimit<T extends (...args: any[]) => Promise<any>>(
  asyncFn: T,
  options: AsyncLimitOptions<T> = {},
): T {
  if (options.concurrency != null && options.qps != null) {
    throw new TypeError('只能同时传入 concurrency 和 qps 其中一个')
  }
 
  const { concurrency = 1, qps, qpsWindow = 1000, groupBy } = options
  const limit = qps != null ? Infinity : concurrency
 
  const groups = new Map<string, GroupState>()
 
  const getGroupState = (groupKey: string) => {
    let groupState = groups.get(groupKey)
    if (!groupState) {
      groupState = { queue: [], activeCount: 0, startTimes: [], timer: null }
      groups.set(groupKey, groupState)
    }
    return groupState
  }
 
  const call = (...args: any[]) => {
    return new Promise(resolve => {
      const groupKey = groupBy
        ? groupBy(...(args as Parameters<T>))
        : defaultGroupKey
      const groupState = getGroupState(groupKey)
      groupState.queue.push({ args, resolve })
      run(groupKey)
    })
  }
 
  const run = (groupKey: string) => {
    const groupState = groups.get(groupKey)
    Iif (!groupState) {
      return
    }
 
    if (!groupState.queue.length) {
      return
    }
 
    if (qps != null) {
      const now = Date.now()
      while (
        groupState.startTimes.length &&
        now - groupState.startTimes[0] >= qpsWindow
      ) {
        groupState.startTimes.shift()
      }
 
      if (groupState.startTimes.length >= qps) {
        if (!groupState.timer) {
          const delay = qpsWindow - (now - groupState.startTimes[0]) + 1
          groupState.timer = setTimeout(() => {
            groupState.timer = null
            run(groupKey)
          }, delay)
        }
        return
      }
      groupState.startTimes.push(now)
    }
 
    if (groupState.activeCount < limit) {
      groupState.activeCount++
      const { args, resolve } = groupState.queue.shift()!
      const res = asyncFn(...args)
      resolve(res)
      res.then(
        () => next(groupKey),
        () => next(groupKey),
      )
    }
  }
 
  const next = (groupKey: string) => {
    const groupState = groups.get(groupKey)
    Iif (!groupState) {
      return
    }
 
    groupState.activeCount--
    run(groupKey)
 
    if (!groupState.activeCount && !groupState.queue.length) {
      Iif (groupState.timer) {
        clearTimeout(groupState.timer)
        groupState.timer = null
      }
      groups.delete(groupKey)
    }
  }
 
  return call as any
}