|
| 1 | +import fs from 'fs' |
| 2 | +import path from 'path' |
| 3 | + |
| 4 | +interface QueueItem<T> { |
| 5 | + requestFunc: () => Promise<T> |
| 6 | + resolve: (value: T) => void |
| 7 | + reject: (err: any) => void |
| 8 | +} |
| 9 | + |
| 10 | +export class RateLimiter { |
| 11 | + private queue: QueueItem<any>[] = [] |
| 12 | + private inflight = new Set<string>() |
| 13 | + private isProcessing = false |
| 14 | + private lastRequestTime = 0 |
| 15 | + private requestCount = 0 |
| 16 | + private windowStart = Date.now() |
| 17 | + |
| 18 | + constructor( |
| 19 | + private maxRequestsPerMinute = 200, |
| 20 | + private lockFilePath?: string |
| 21 | + ) { } |
| 22 | + |
| 23 | + private async acquireLock() { |
| 24 | + if (!this.lockFilePath) return |
| 25 | + // 如果锁文件存在且创建时间过久(比如 >5分钟),认为是陈旧锁,直接删除 |
| 26 | + if (fs.existsSync(this.lockFilePath)) { |
| 27 | + const stats = fs.statSync(this.lockFilePath) |
| 28 | + const age = Date.now() - stats.ctimeMs |
| 29 | + if (age > 30 * 1000) { // 30秒 |
| 30 | + try { |
| 31 | + fs.unlinkSync(this.lockFilePath) |
| 32 | + console.warn('[限流] 删除陈旧锁文件:', this.lockFilePath) |
| 33 | + } catch (err) { |
| 34 | + console.error('[限流] 删除陈旧锁失败:', err) |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + while (true) { |
| 39 | + try { |
| 40 | + fs.writeFileSync(this.lockFilePath, process.pid.toString(), { flag: 'wx' }) |
| 41 | + return |
| 42 | + } catch (err: any) { |
| 43 | + if (err.code === 'EEXIST') await new Promise(res => setTimeout(res, 100)) |
| 44 | + else throw err |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private releaseLock() { |
| 50 | + if (!this.lockFilePath) return |
| 51 | + try { if (fs.existsSync(this.lockFilePath)) fs.unlinkSync(this.lockFilePath) } |
| 52 | + catch (err) { console.error('释放锁失败', err) } |
| 53 | + } |
| 54 | + |
| 55 | + public enqueue<T>(key: string, requestFunc: () => Promise<T>): Promise<T> { |
| 56 | + if (this.inflight.has(key)) { |
| 57 | + return new Promise((resolve, reject) => { |
| 58 | + const interval = setInterval(() => { |
| 59 | + if (!this.inflight.has(key)) { |
| 60 | + clearInterval(interval) |
| 61 | + this.enqueue(key, requestFunc).then(resolve).catch(reject) |
| 62 | + } |
| 63 | + }, 50) |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + return new Promise((resolve, reject) => { |
| 68 | + this.queue.push({ requestFunc, resolve, reject }) |
| 69 | + if (!this.isProcessing) this.processQueue() |
| 70 | + }) |
| 71 | + } |
| 72 | + |
| 73 | + private async processQueue() { |
| 74 | + if (this.queue.length === 0) { this.isProcessing = false; return } |
| 75 | + this.isProcessing = true |
| 76 | + |
| 77 | + try { |
| 78 | + await this.acquireLock() |
| 79 | + const now = Date.now() |
| 80 | + const elapsed = now - this.windowStart |
| 81 | + |
| 82 | + if (elapsed > 60_000) { this.requestCount = 0; this.windowStart = now } |
| 83 | + if (this.requestCount >= this.maxRequestsPerMinute) { |
| 84 | + const waitTime = 60_000 - elapsed + 100 |
| 85 | + await new Promise(res => setTimeout(res, waitTime)) |
| 86 | + this.requestCount = 0 |
| 87 | + this.windowStart = Date.now() |
| 88 | + } |
| 89 | + |
| 90 | + const minInterval = 300 |
| 91 | + const waitTime = Math.max(0, minInterval - (now - this.lastRequestTime)) |
| 92 | + if (waitTime > 0) await new Promise(res => setTimeout(res, waitTime)) |
| 93 | + |
| 94 | + const { requestFunc, resolve, reject } = this.queue.shift()! |
| 95 | + const key = crypto.randomUUID() |
| 96 | + this.inflight.add(key) |
| 97 | + |
| 98 | + try { |
| 99 | + const result = await requestFunc() |
| 100 | + this.lastRequestTime = Date.now() |
| 101 | + this.requestCount++ |
| 102 | + resolve(result) |
| 103 | + } catch (err) { reject(err) } |
| 104 | + finally { this.inflight.delete(key) } |
| 105 | + |
| 106 | + } catch (err) { |
| 107 | + console.error('限流队列异常', err) |
| 108 | + } finally { |
| 109 | + this.releaseLock() |
| 110 | + setTimeout(() => this.processQueue(), 0) |
| 111 | + } |
| 112 | + } |
| 113 | +} |
0 commit comments