Skip to content

Commit 1e63b54

Browse files
committed
another fix for rate limits - wrap createMatch in a wrapper that throttles runs based on the retryAfter sent by discord api
1 parent e6f2e25 commit 1e63b54

1 file changed

Lines changed: 52 additions & 1 deletion

File tree

src/utils/queueHelpers.ts

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -487,10 +487,61 @@ function getCombinations<T>(arr: T[], k: number): T[][] {
487487
return results
488488
}
489489

490-
// Queues players together and creates a match channel for them
490+
// route match creation through this wrapper, which will queue it up based on rate limits
491+
492+
type MatchRequest = {
493+
resolve: (result: any) => void
494+
reject: (err: any) => void
495+
userIds: string[]
496+
queueId: number
497+
}
498+
499+
const matchQueue: MatchRequest[] = []
500+
let processingMatch = false
501+
let nextDelay = 1500
502+
503+
client.rest.on('rateLimited', (info) => {
504+
if (info.retryAfter > nextDelay) {
505+
nextDelay = info.retryAfter + 500
506+
}
507+
})
508+
491509
export async function createMatch(
492510
userIds: string[],
493511
queueId: number,
512+
): Promise<any> {
513+
return new Promise((resolve, reject) => {
514+
matchQueue.push({ resolve, reject, userIds, queueId })
515+
processMatchQueue()
516+
})
517+
}
518+
519+
async function processMatchQueue() {
520+
if (processingMatch || matchQueue.length === 0) return
521+
processingMatch = true
522+
523+
const { resolve, reject, userIds, queueId } = matchQueue.shift()!
524+
525+
try {
526+
const result = await createMatchResolved(userIds, queueId)
527+
resolve(result)
528+
} catch (err) {
529+
reject(err)
530+
}
531+
532+
const delay = nextDelay
533+
nextDelay = 1500 // reset for next run
534+
535+
setTimeout(() => {
536+
processingMatch = false
537+
processMatchQueue()
538+
}, delay)
539+
}
540+
541+
// Queues players together and creates a match channel for them
542+
export async function createMatchResolved(
543+
userIds: string[],
544+
queueId: number,
494545
): Promise<any> {
495546
// putting this here for now todo: replace with api cronjob
496547
await checkBans()

0 commit comments

Comments
 (0)