Skip to content

Commit

Permalink
add rate limiting
Browse files Browse the repository at this point in the history
  • Loading branch information
hideckies committed Dec 23, 2023
1 parent 406a686 commit 2ea82e5
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,42 @@ import { sleep } from "https://deno.land/x/[email protected]/mod.ts";
// throw new Error("Function not implemented.");
// }

const kv = await Deno.openKv();

const server = new Server({
port: 8000,
root: `${Deno.cwd()}/_site`,
});

// Rate limiting
server.use(async (request, next) => {
// Rate limiting (max 10 requests per 10 seconds)
const maxRequests = 10;
const interval = 10000;
const rateLimitter = {
requestCount: 0,
lastResetTime: Date.now(),
};

server.use(async (request, next, _conn) => {
const response = await next(request);

await sleep(2);

// const remoteAddr = conn.remoteAddr;

const currentTime = Date.now();

// Reset rateLimitter after elapsing interval
if (currentTime - rateLimitter.lastResetTime > interval) {
rateLimitter.requestCount = 0;
rateLimitter.lastResetTime = currentTime;
}

// Rate limiting
if (rateLimitter.requestCount < maxRequests) {
rateLimitter.requestCount += 1;
} else {
console.log("Rate limiting: Sleep 30 seconds.");
await sleep(30);
}

await sleep(1);

return response;
})

Expand Down

0 comments on commit 2ea82e5

Please sign in to comment.