Skip to content

Commit

Permalink
fix: simplify and improve requiredPoints calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinKolarik committed Feb 11, 2024
1 parent 2ccd66e commit 461ede1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/lib/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ export const rateLimit = async (ctx: ExtendedContext, numberOfProbes: number) =>

const consumeCredits = async (userId: string, rateLimiterRes: RateLimiterRes, numberOfProbes: number) => {
const freePoints = config.get<number>('measurement.authenticatedRateLimit');
const alreadyUsedPoints = rateLimiterRes.consumedPoints - numberOfProbes;
const remainingFreePoints = freePoints - alreadyUsedPoints;
const requiredPoints = numberOfProbes - remainingFreePoints;
const requiredPoints = Math.min(rateLimiterRes.consumedPoints - freePoints, numberOfProbes);
const { isConsumed, remainingCredits } = await credits.consume(userId, requiredPoints);

if (isConsumed) {
Expand Down
18 changes: 18 additions & 0 deletions test/tests/integration/ratelimit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,24 @@ describe('rate limiter', () => {
expect(amount).to.equal(1);
});

it('should not consume more paid credits than the cost of the full request', async () => {
await authenticatedRateLimiter.set('89da69bd-a236-4ab7-9c5d-b5f52ce09959', 255, 0);

const response = await requestAgent.post('/v1/measurements')
.set('Authorization', 'Bearer v2lUHEVLtVSskaRKDBabpyp4AkzdMnob')
.send({
type: 'ping',
target: 'jsdelivr.com',
limit: 2,
}).expect(202) as Response;

expect(response.headers['x-ratelimit-remaining']).to.equal('0');
expect(response.headers['x-credits-cost']).to.equal('2');
expect((response.headers['x-credits-remaining'])).to.equal('8');
const [{ amount }] = await client(CREDITS_TABLE).select('amount').where({ user_id: '89da69bd-a236-4ab7-9c5d-b5f52ce09959' });
expect(amount).to.equal(8);
});

it('should not consume free credits if there are not enough to satisfy the request', async () => {
await authenticatedRateLimiter.set('89da69bd-a236-4ab7-9c5d-b5f52ce09959', 249, 0);

Expand Down

0 comments on commit 461ede1

Please sign in to comment.