-
Notifications
You must be signed in to change notification settings - Fork 4
Add rate limiting functionality using @upstash/ratelimit and integrate with TRPC procedures #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8bba260
Add rate limiting functionality using @upstash/ratelimit and integrat…
jakejarvis 400f35d
Enhance rate limit error handling and client feedback in TRPC integra…
jakejarvis eea02c6
Enable analytics for rate limiting and allow background processing of…
jakejarvis 101f422
Add icon to rate limit error toast for improved user feedback
jakejarvis e613036
Update rate limit response to include reset time for enhanced client …
jakejarvis 5dee0d8
Refactor error handling for rate limit responses in TRPC integration
jakejarvis 2245130
Refactor TRPC error handling to utilize formatted data for rate limit…
jakejarvis c55ec5c
Improve error handling for background analytics shutdown in server fu…
jakejarvis 307bcc1
Refactor TRPC error handling to use a dedicated errorToastLink for ra…
jakejarvis 9b46f16
Update trpc/client.tsx
jakejarvis b7573e0
Remove unnecessary closing parentheses
jakejarvis fc268a3
Merge branch 'main' into feat/rate-limit
jakejarvis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,7 @@ | ||
| import { z } from "zod"; | ||
|
|
||
| export const StorageKindSchema = z.enum(["favicon", "screenshot", "social"]); | ||
| export const StorageUrlSchema = z.object({ url: z.string().url().nullable() }); | ||
|
|
||
| export type StorageKind = z.infer<typeof StorageKindSchema>; | ||
| export type StorageUrl = z.infer<typeof StorageUrlSchema>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import "server-only"; | ||
|
|
||
| import { TRPCError } from "@trpc/server"; | ||
| import { Ratelimit } from "@upstash/ratelimit"; | ||
| import { waitUntil } from "@vercel/functions"; | ||
| import { redis } from "@/lib/redis"; | ||
| import { t } from "@/trpc/init"; | ||
|
|
||
| export const SERVICE_LIMITS = { | ||
| dns: { points: 60, window: "1 m" }, | ||
| headers: { points: 60, window: "1 m" }, | ||
| certs: { points: 30, window: "1 m" }, | ||
| registration: { points: 4, window: "1 m" }, | ||
| screenshot: { points: 3, window: "1 m" }, | ||
| favicon: { points: 120, window: "1 h" }, | ||
| seo: { points: 30, window: "1 m" }, | ||
| hosting: { points: 30, window: "1 m" }, | ||
| pricing: { points: 30, window: "1 m" }, | ||
| } as const; | ||
|
|
||
| export type ServiceName = keyof typeof SERVICE_LIMITS; | ||
|
|
||
| const limiters = Object.fromEntries( | ||
| Object.entries(SERVICE_LIMITS).map(([service, cfg]) => [ | ||
| service, | ||
| new Ratelimit({ | ||
| redis, | ||
| limiter: Ratelimit.slidingWindow( | ||
| cfg.points, | ||
| cfg.window as `${number} ${"s" | "m" | "h"}`, | ||
| ), | ||
| prefix: `@upstash/ratelimit:${service}`, | ||
| analytics: true, | ||
| }), | ||
| ]), | ||
| ) as Record<ServiceName, Ratelimit>; | ||
|
|
||
| export async function assertRateLimit(service: ServiceName, ip: string) { | ||
| const res = await limiters[service].limit(ip); | ||
|
|
||
| if (!res.success) { | ||
| const retryAfterSec = Math.max( | ||
| 1, | ||
| Math.ceil((res.reset - Date.now()) / 1000), | ||
| ); | ||
|
|
||
| throw new TRPCError({ | ||
| code: "TOO_MANY_REQUESTS", | ||
| message: `Rate limit exceeded for ${service}. Try again in ${retryAfterSec}s.`, | ||
| cause: { | ||
| retryAfter: retryAfterSec, | ||
| service, | ||
| limit: res.limit, | ||
| remaining: res.remaining, | ||
| reset: res.reset, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| // allow ratelimit analytics to be sent in background | ||
| try { | ||
| waitUntil?.(res.pending); | ||
| } catch { | ||
| // no-op | ||
| } | ||
|
|
||
| return { limit: res.limit, remaining: res.remaining, reset: res.reset }; | ||
| } | ||
|
|
||
| export const rateLimitMiddleware = t.middleware(async ({ ctx, next, meta }) => { | ||
| const service = (meta?.service ?? "") as ServiceName; | ||
| if (!service || !(service in SERVICE_LIMITS) || !ctx.ip) return next(); | ||
| await assertRateLimit(service, ctx.ip); | ||
| return next(); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| "use client"; | ||
|
|
||
| import { TRPCClientError, type TRPCLink } from "@trpc/client"; | ||
| import type { AnyRouter } from "@trpc/server"; | ||
| import { observable } from "@trpc/server/observable"; | ||
| import { Siren } from "lucide-react"; | ||
| import { toast } from "sonner"; | ||
|
|
||
| function formatWait(seconds: number): string { | ||
| if (!Number.isFinite(seconds) || seconds <= 1) return "a moment"; | ||
| const s = Math.round(seconds); | ||
| const m = Math.floor(s / 60); | ||
| const sec = s % 60; | ||
| if (m <= 0) return `${sec}s`; | ||
| if (m < 60) return sec ? `${m}m ${sec}s` : `${m}m`; | ||
| const h = Math.floor(m / 60); | ||
| const rm = m % 60; | ||
| return rm ? `${h}h ${rm}m` : `${h}h`; | ||
| } | ||
|
|
||
| export function errorToastLink< | ||
| TRouter extends AnyRouter = AnyRouter, | ||
| >(): TRPCLink<TRouter> { | ||
| return () => | ||
| ({ next, op }) => | ||
| observable((observer) => { | ||
| const sub = next(op).subscribe({ | ||
| next(value) { | ||
| observer.next(value); | ||
| }, | ||
| error(err) { | ||
| if (err instanceof TRPCClientError) { | ||
| const code = err.data?.code; | ||
| if (code === "TOO_MANY_REQUESTS") { | ||
| const retryAfterSec = Math.max( | ||
| 1, | ||
| Math.round(Number(err.data?.retryAfter ?? 1)), | ||
| ); | ||
| const service = err.data?.service as string | undefined; | ||
| const friendly = formatWait(retryAfterSec); | ||
| const title = service | ||
| ? `Too many ${service} requests` | ||
| : "You're doing that too much"; | ||
| toast.error(title, { | ||
| id: "rate-limit", | ||
| description: `Try again in ${friendly}.`, | ||
| icon: <Siren className="h-4 w-4" />, | ||
| position: "top-center", | ||
| }); | ||
| } | ||
| } | ||
| observer.error(err); | ||
| }, | ||
| complete() { | ||
| observer.complete(); | ||
| }, | ||
| }); | ||
| return () => sub.unsubscribe(); | ||
| }); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.