From f83ebd0e3faa5a8acc5d714660223e4b0fdeafb9 Mon Sep 17 00:00:00 2001 From: Xi Xu Date: Wed, 11 Mar 2026 14:10:49 +0800 Subject: [PATCH] Await proxy endpoints and simplify delayRequest Make getDynamicRateLimits async and await getProxyEndpoints to ensure proxy endpoints are resolved before calculating limits; update checkRateLimit to await the dynamic limits. Replace the custom microtask-based delay loop with a simple setTimeout-based Promise in delayRequest, normalizing and clamping the delay to milliseconds. These changes fix async behavior and simplify the request-delay implementation. --- src/lib/rateLimit.ts | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/src/lib/rateLimit.ts b/src/lib/rateLimit.ts index 477dc22..cbd5d17 100644 --- a/src/lib/rateLimit.ts +++ b/src/lib/rateLimit.ts @@ -33,8 +33,8 @@ export interface RateLimitResult { * @param env Environment bindings containing proxy configuration * @returns Object containing calculated rate limits */ -function getDynamicRateLimits(env: Env) { - const proxyEndpoints = getProxyEndpoints(env); +async function getDynamicRateLimits(env: Env) { + const proxyEndpoints = await getProxyEndpoints(env); return calculateDynamicRateLimits(proxyEndpoints.length); } @@ -81,7 +81,7 @@ async function checkRateLimit(clientIP: string, env: Env): Promise { const now = Date.now(); try { - const rateLimits = getDynamicRateLimits(env); + const rateLimits = await getDynamicRateLimits(env); const maxTokens = rateLimits.TOKENS_PER_MINUTE; // Check in-memory cache @@ -167,19 +167,8 @@ async function checkRateLimit(clientIP: string, env: Env): Promise { * @returns Promise that resolves after the specified delay */ export async function delayRequest(seconds: number): Promise { - return new Promise((resolve) => { - // Use a simple delay implementation for Workers environment - const start = Date.now(); - const checkTime = () => { - if (Date.now() - start >= seconds * 1000) { - resolve(); - } else { - // Use minimal delay to prevent blocking - Promise.resolve().then(checkTime); - } - }; - checkTime(); - }); + const delayMs = Math.max(0, Math.round(seconds * 1000)); + await new Promise((resolve) => setTimeout(resolve, delayMs)); } /**