Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 31 additions & 42 deletions packages/bun/src/redis-ratelimit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => {
})
}

it(
'accepts weighted requests',
async () => {
const limiter = await createTestingRateLimiter()
const key = 'weighted'

await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({
success: true,
limit: 3,
remaining: 1,
})
},
{ timeout: 20_000 },
)

it(
'tracks counters independently for each key',
async () => {
Expand Down Expand Up @@ -135,24 +120,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => {
{ timeout: 20_000 },
)

it(
'uses an empty prefix when none is provided',
async () => {
const limiter = await createTestingRateLimiter({
prefix: undefined,
maxRequests: 3,
window: 10_000,
})

await expect(limiter.limit(`no-prefix-${crypto.randomUUID()}`)).resolves.toMatchObject({
success: true,
limit: 3,
remaining: 2,
})
},
{ timeout: 20_000 },
)

it(
'rejects invalid weights',
async () => {
Expand All @@ -171,7 +138,7 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => {
)

it(
'consumes quota across multiple requests',
'consumes quota, then rejects requests that exceed the limit',
async () => {
const limiter = await createTestingRateLimiter()
const key = 'quota'
Expand All @@ -190,23 +157,46 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => {
success: true,
remaining: 0,
})

await expect(limiter.limit(key)).resolves.toMatchObject({
success: false,
limit: 3,
remaining: 0,
})
},
{ timeout: 20_000 },
)

it(
'rejects requests that exceed the limit',
'does not count rejected requests',
async () => {
const limiter = await createTestingRateLimiter()
const key = 'exceeded'
const key = 'rejected-not-counted'

await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({
success: true,
remaining: 1,
})

await limiter.limit(key)
await limiter.limit(key)
await limiter.limit(key)
for (let i = 0; i < 5; i++) {
await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({
success: false,
limit: 3,
remaining: 1,
})
}

await expect(limiter.limit(key)).resolves.toMatchObject({
success: false,
limit: 3,
success: true,
remaining: 0,
})

// a request that can never fit does not start a window for a new key
const oversized = await limiter.limit('oversized', { weight: 4 })
expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 })
expect(oversized.reset).toBeGreaterThan(Date.now())
await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({
success: true,
remaining: 0,
})
},
Expand Down Expand Up @@ -288,7 +278,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => {
await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({
success: false,
limit: 2,
remaining: 0,
})
},
{ timeout: 20_000 },
Expand Down
72 changes: 72 additions & 0 deletions packages/ratelimit/src/adapters/base-redis.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { BaseRedisRateLimiter } from './base-redis'

class TestingRateLimiter extends BaseRedisRateLimiter {
evalScript = vi.fn<(script: string, keys: string[], args: string[]) => Promise<unknown>>()
}

describe('baseRedisRateLimiter', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(10_000)
})

afterEach(() => {
vi.useRealTimers()
})

it('sends the weight, window and limit, so the script can check before it consumes', async () => {
const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000, prefix: 'app:' })
limiter.evalScript.mockResolvedValueOnce([1, 2, 1000])

await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({
success: true,
limit: 5,
remaining: 3,
reset: 11_000,
})

expect(limiter.evalScript).toHaveBeenCalledTimes(1)
expect(limiter.evalScript).toHaveBeenCalledWith(
expect.any(String),
['app:key'],
['2', '1000', '5'],
)
})

it('reports a rejection from the script with the untouched counter', async () => {
const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 })
limiter.evalScript.mockResolvedValueOnce([0, 4, 300])

await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({
success: false,
limit: 5,
remaining: 1,
reset: 10_300,
})
})

it('uses an empty prefix when none is provided', async () => {
const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 })
limiter.evalScript.mockResolvedValueOnce([1, 1, 1000])

await limiter.limit('key')

expect(limiter.evalScript).toHaveBeenCalledWith(expect.any(String), ['key'], expect.any(Array))
})

it('retries after the window resets when a timeout is set', async () => {
const limiter = new TestingRateLimiter({ maxRequests: 1, window: 500, timeout: 1000 })
limiter.evalScript.mockResolvedValueOnce([0, 1, 200]).mockResolvedValueOnce([1, 1, 500])

const pending = limiter.limit('key')
await vi.advanceTimersByTimeAsync(200)

await expect(pending).resolves.toEqual({
success: true,
limit: 1,
remaining: 0,
reset: 10_700,
})
expect(limiter.evalScript).toHaveBeenCalledTimes(2)
})
})
17 changes: 10 additions & 7 deletions packages/ratelimit/src/adapters/base-redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import type { RateLimiter, RateLimitOptions, RateLimitResult } from '../types'
import { blockUntilReady, resolveWeight } from '../utils'

/**
* Consumes `ARGV[1]` points from the counter at `KEYS[1]`, starts a window of
* `ARGV[2]` milliseconds when the counter is new, and replies with `[used, ttl]`.
* Consumes `ARGV[1]` points from the counter at `KEYS[1]` if it stays within the
* limit `ARGV[3]`, starts a window of `ARGV[2]` milliseconds when the counter is
* new, and replies with `[success, used, ttl]`.
* Kept on one line because `EVAL` sends it with every call.
*/
const FIXED_WINDOW_SCRIPT = `local c=redis.call('INCRBY',KEYS[1],ARGV[1]) if c==tonumber(ARGV[1]) then redis.call('PEXPIRE',KEYS[1],ARGV[2]) end return {c,redis.call('PTTL',KEYS[1])}`
const FIXED_WINDOW_SCRIPT = `local w=tonumber(ARGV[1]) local c=tonumber(redis.call('GET',KEYS[1]) or 0) local t=redis.call('PTTL',KEYS[1]) local s=0 if c+w<=tonumber(ARGV[3]) then c=redis.call('INCRBY',KEYS[1],w) s=1 end if t<0 then t=tonumber(ARGV[2]) if c>0 then redis.call('PEXPIRE',KEYS[1],t) end end return {s,c,t}`

/**
* Options shared by every Redis-backed rate limiter adapter.
Expand Down Expand Up @@ -45,6 +46,8 @@ export interface BaseRedisRateLimiterOptions {
* the fixed-window script, and the blocking logic, so every adapter built on
* it shares counters with the others regardless of the Redis client in use.
*
* Windows are per key, and rejected requests do not consume quota.
*
* Extend it and implement `evalScript` to support another Redis client.
*
* @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters}
Expand Down Expand Up @@ -75,14 +78,14 @@ export abstract class BaseRedisRateLimiter implements RateLimiter {
}

private async checkLimit(key: string, weight: number): Promise<Required<RateLimitResult>> {
const [used, ttl] = (await this.evalScript(
const [success, used, ttl] = (await this.evalScript(
FIXED_WINDOW_SCRIPT,
[key],
[String(weight), String(this.window)],
)) as [used: number, ttl: number]
[String(weight), String(this.window), String(this.maxRequests)],
)) as [success: number, used: number, ttl: number]

return {
success: used <= this.maxRequests,
success: success === 1,
limit: this.maxRequests,
remaining: Math.max(0, this.maxRequests - used),
reset: Date.now() + ttl,
Expand Down
Loading
Loading