Skip to content

Commit

Permalink
Prevent rate limiting from delaying response
Browse files Browse the repository at this point in the history
  • Loading branch information
prasmussen committed Jul 24, 2024
1 parent ef8470e commit 2e05ce6
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions glot_cloudflare/functions/api/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,22 @@ export const onRequestPost: PagesFunction<Env & StringRecord> = async (context)
return errorResponse(403, "Forbidden");
}

const requestBody = context.request.clone().body;
const runResponse = run(envVars, requestBody);

try {
const ip = getRequestIp(context.request);
const requestStats = await incrementRequestCount(context.env, context.request.clone(), ip);
const requestStats = await incrementRequestCount(context.env, context.request, ip);

if (isRateLimited(envVars, requestStats)) {
return errorResponse(429, "Rate limit exceeded");
} else {
return runResponse;
}
} catch (e) {
console.error("Failed to increment request count", e.message);
return runResponse;
}

return run(envVars, context.request.body);
};

function getRequestIp(request: Request): string {
Expand Down

0 comments on commit 2e05ce6

Please sign in to comment.