Skip to content

Commit

Permalink
Merge pull request #811 from filipedeschamps/upstash-timeout
Browse files Browse the repository at this point in the history
feat(rate-limit): added 4s upstash service timeout
  • Loading branch information
filipedeschamps authored Nov 18, 2022
2 parents a2cdef5 + bd2fc82 commit 46905f0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
11 changes: 10 additions & 1 deletion infra/rate-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,21 @@ async function check(request) {
const method = request.method;
const path = request.nextUrl.pathname;
const limit = getLimit(method, path, ip);
let timeout;

try {
const generalRateLimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(limit.requests, limit.window),
});

return await generalRateLimit.limit(limit.identifier);
const timeoutPromise = new Promise((_, reject) => {
timeout = setTimeout(() => {
reject({ message: 'Upstash não respondeu dentro de 4s.' });
}, 4000);
});

return await Promise.race([generalRateLimit.limit(limit.identifier), timeoutPromise]);
} catch (error) {
throw new ServiceError({
message: error.message,
Expand All @@ -45,6 +52,8 @@ async function check(request) {
},
errorLocationCode: 'MIDDLEWARE:RATE_LIMIT:CHECK',
});
} finally {
clearTimeout(timeout);
}
}

Expand Down
8 changes: 0 additions & 8 deletions middleware.public.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,6 @@ import { NextResponse } from 'next/server';
import rateLimit from 'infra/rate-limit.js';
import snakeize from 'snakeize';

// TODO: Next.js still didn't fix this bug:
// https://github.com/vercel/next.js/issues/39262
// But this bug doesn't affect Preview and Production environments.
// So it's time enable the middleware on all routes, but then
// we need to skip these two tests for now as a collateral effect:
// https://github.com/filipedeschamps/tabnews.com.br/blob/35bd984db122f30ae3ed7a3b5d7baf830669a345/tests/integration/api/v1/contents/post.test.js#L268
// https://github.com/filipedeschamps/tabnews.com.br/blob/35bd984db122f30ae3ed7a3b5d7baf830669a345/tests/integration/api/v1/contents/%5Busername%5D/%5Bslug%5D/patch.test.js#L500

export const config = {
matcher: ['/api/:path*'],
};
Expand Down

1 comment on commit 46905f0

@vercel
Copy link

@vercel vercel bot commented on 46905f0 Nov 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

tabnews – ./

tabnews-tabnews.vercel.app
tabnews.com.br
www.tabnews.com.br
tabnews-git-main-tabnews.vercel.app

Please sign in to comment.