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( fn: () => Promise ): 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-- } }