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.
This commit is contained in:
1 parent
32578e95ee
commit
f83ebd0e3f
1 file changed
+5
-16
+5
-16
@@ -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<boolean> {
|
||||
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<boolean> {
|
||||
* @returns Promise that resolves after the specified delay
|
||||
*/
|
||||
export async function delayRequest(seconds: number): Promise<void> {
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user