Skip to content

Commit

Permalink
feat: fork ratelimit to log instead of blocking wih 429
Browse files Browse the repository at this point in the history
  • Loading branch information
WcaleNieWolny committed Jan 12, 2025
1 parent c83b19c commit 0c3ea69
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
61 changes: 61 additions & 0 deletions supabase/functions/_backend/utils/cfRateLimiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { Context, Next } from '@hono/hono'
import { createMiddleware } from 'hono/factory'

const RATE_LIMIT_CONTEXT_KEY = '.rateLimited'
// const STATUS_TOO_MANY_REQUESTS = 429

export interface RateLimitBinding {
limit: LimitFunc
}

export interface LimitFunc {
(options: LimitOptions): Promise<RateLimitResult>
}

interface RateLimitResult {
success: boolean
}

export interface LimitOptions {
key: string
}

export interface RateLimitResponse {
key: string
success: boolean
}

export interface RateLimitOptions {
continueOnRateLimit: boolean
}

export interface RateLimitKeyFunc {
(c: Context): string
}

export function rateLimit(rateLimitBinding: RateLimitBinding, keyFunc: RateLimitKeyFunc, rateLimit: string = '') {
return createMiddleware(async (c: Context, next: Next) => {
const key = keyFunc(c)
if (!key) {
console.warn('the provided keyFunc returned an empty rate limiting key: bypassing rate limits')
}
if (key) {
const { success } = await rateLimitBinding.limit({ key })
c.set(RATE_LIMIT_CONTEXT_KEY, success)

if (!success) {
// throw new HTTPException(STATUS_TOO_MANY_REQUESTS, {
// res: c.text("rate limited", { status: STATUS_TOO_MANY_REQUESTS }),
// });
console.warn(`The rate limit has been reached for key: ${key} and rate limit binding: ${rateLimit}`)
}
}

// Call the next handler/middleware in the stack on success
await next()
})
}

export function wasRateLimited(c: Context): boolean {
return c.get(RATE_LIMIT_CONTEXT_KEY) as boolean
}
1 change: 1 addition & 0 deletions supabase/functions/import_map.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"hono/request-id": "jsr:@hono/hono@^4.6.13/request-id",
"hono/cors": "jsr:@hono/hono@^4.6.13/cors",
"hono/tiny": "jsr:@hono/hono@^4.6.13/tiny",
"hono/factory": "jsr:@hono/hono@^4.6.13/factory",
"hono/http-exception": "jsr:@hono/hono@^4.6.13/http-exception",
"hono/adapter": "jsr:@hono/hono@^4.6.13/adapter",
"hono/utils/buffer": "jsr:@hono/hono@^4.6.13/utils/buffer",
Expand Down

0 comments on commit 0c3ea69

Please sign in to comment.