Skip to content
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

♻️ Clean up trpc code and add global client error handling #1549

Merged
merged 4 commits into from
Feb 9, 2025

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Feb 8, 2025

Summary by CodeRabbit

  • New Features

    • Introduced flexible rate limiting configurations for various user procedures, enhancing control over request handling.
    • Added new error messages for handling excessive requests.
  • Bug Fixes

    • Improved error handling for missing client IP addresses in rate limiting logic.
  • Refactor

    • Streamlined the rate limiting setup by centralizing its configuration, allowing for different request limits across multiple procedures.
    • Transitioned to a new TRPC client setup, enhancing integration with React Query.
  • Chores

    • Updated SMTP configuration for development environment.
    • Removed unnecessary dependencies from the project.

Copy link

vercel bot commented Feb 8, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 9, 2025 7:08am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Feb 9, 2025 7:08am

Copy link
Contributor

coderabbitai bot commented Feb 8, 2025

Warning

Rate limit exceeded

@lukevella has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2271d44 and 3c3dab7.

📒 Files selected for processing (4)
  • apps/web/src/trpc/routers/auth.ts (2 hunks)
  • apps/web/src/trpc/routers/polls/comments.ts (2 hunks)
  • apps/web/src/trpc/routers/polls/participants.ts (5 hunks)
  • apps/web/src/trpc/trpc.ts (1 hunks)

Walkthrough

The changes refactor the rateLimitMiddleware into a factory function named createRateLimitMiddleware in apps/web/src/trpc/trpc.ts, allowing for flexible rate limiting configurations. The middleware checks for the KV_REST_API_URL environment variable and retrieves the client IP address. The user router in apps/web/src/trpc/routers/user.ts has been updated to utilize the new factory function for various procedures, applying specific rate limits for each. Additionally, the SMTP configuration in the .env.development file has been modified, and the project has transitioned from using @trpc/next to @trpc/react.

Changes

File Path Change Summary
apps/web/.../trpc/trpc.ts Refactored rateLimitMiddleware into createRateLimitMiddleware, which accepts parameters for request limits and durations. Removed inline implementation.
apps/web/.../routers/user.ts Updated multiple mutation procedures to use createRateLimitMiddleware with specific request limits and durations for each procedure.
.env.development Changed SMTP_HOST from localhost to 0.0.0.0.
apps/web/.../package.json Removed dependency on @trpc/next.
apps/web/.../client.ts Transitioned from createTRPCNext to createTRPCReact for setting up the TRPC client.
apps/web/.../client/config.ts Deleted file containing TRPC client configuration and error handling logic.
apps/web/.../client/provider.tsx Introduced TRPCProvider component for integrating TRPC client with React Query.
apps/web/.../routers/polls.ts Updated procedures to use createRateLimitMiddleware with specific limits for create, update, and delete operations.
apps/web/.../app/[locale]/poll/[urlId]/duplicate-dialog.tsx Updated import path for trpc from @/app/providers to @/trpc/client.
apps/web/.../components/poll/manage-poll.tsx Updated import path for trpc from @/app/providers to @/trpc/client.
apps/web/.../components/poll/manage-poll/finalize-poll-dialog.tsx Updated import path for trpc from @/app/providers to @/trpc/client.

Possibly related PRs

Poem

I'm a little rabbit with code to share,
Hopping through changes with agile flair,
A factory for limits, so clever and neat,
Each procedure now knows how to keep the beat!
In this garden of code, I cheer with delight 🥕✨
Celebrate each hop and every updated byte!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/web/src/trpc/trpc.ts (1)

92-97: Consider extracting rate limit configuration to environment variables.

The rate limit values (5 requests per minute) are hardcoded. Consider making these configurable through environment variables for better flexibility across different environments.

+const RATE_LIMIT_REQUESTS = process.env.RATE_LIMIT_REQUESTS ? parseInt(process.env.RATE_LIMIT_REQUESTS) : 5;
+const RATE_LIMIT_WINDOW = process.env.RATE_LIMIT_WINDOW || "1 m";
 const ratelimit = process.env.KV_REST_API_URL
   ? new Ratelimit({
       redis: kv,
-      limiter: Ratelimit.slidingWindow(5, "1 m"),
+      limiter: Ratelimit.slidingWindow(RATE_LIMIT_REQUESTS, RATE_LIMIT_WINDOW),
     })
   : null;

Also, consider adding type safety:

-const ratelimit = process.env.KV_REST_API_URL
+const ratelimit: Ratelimit | null = process.env.KV_REST_API_URL
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ffafcbd and e1d91a7.

📒 Files selected for processing (1)
  • apps/web/src/trpc/trpc.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Integration tests
  • GitHub Check: Type check
  • GitHub Check: Linting
🔇 Additional comments (1)
apps/web/src/trpc/trpc.ts (1)

99-121: LGTM! Clean refactor of the rate limit middleware.

The changes effectively use the shared rate limit instance while maintaining the existing error handling and rate limiting logic.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
apps/web/src/trpc/trpc.ts (2)

92-95: Add validation for the requests parameter.

The requests parameter should be validated to ensure it's a positive number.

 export const createRateLimitMiddleware = (
-  requests: number,
+  requests: number & { __brand: "PositiveNumber" },
   duration: "1 m" | "1 h",
 ) => {
+  if (requests <= 0) {
+    throw new Error("Number of requests must be positive");
+  }

97-99: Consider logging when rate limiting is disabled.

When KV_REST_API_URL is not set, the middleware silently bypasses rate limiting. Consider logging this behavior to help with debugging.

   if (!process.env.KV_REST_API_URL) {
+    console.warn("Rate limiting is disabled: KV_REST_API_URL is not set");
     return next();
   }
apps/web/src/trpc/routers/user.ts (2)

56-71: Document rate limit configurations.

Consider adding comments explaining the rationale behind each rate limit configuration to help future maintainers understand the choices.

+  // Limit to 5 requests per hour due to destructive nature
   delete: privateProcedure
     .use(createRateLimitMiddleware(5, "1 h"))

+  // Limit to 20 requests per hour for profile updates
   changeName: privateProcedure
     .use(createRateLimitMiddleware(20, "1 h"))

+  // Limit to 30 requests per hour for preference updates
   updatePreferences: privateProcedure
     .use(createRateLimitMiddleware(30, "1 h"))

+  // Limit to 10 requests per hour due to email sending
   requestEmailChange: privateProcedure
     .use(createRateLimitMiddleware(10, "1 h"))

+  // Limit to 20 requests per hour for S3 signed URL generation
   getAvatarUploadUrl: privateProcedure
     .use(createRateLimitMiddleware(20, "1 h"))

+  // Limit to 10 requests per hour due to S3 operations
   updateAvatar: privateProcedure
     .input(z.object({ imageKey: z.string().max(255) }))
     .use(createRateLimitMiddleware(10, "1 h"))

Also applies to: 84-86, 101-103, 128-130, 180-182, 225-228


225-228: Maintain consistent middleware ordering.

The rate limit middleware is placed after the input validation in updateAvatar, while in other routes it's placed before. Consider maintaining a consistent order across all routes.

   updateAvatar: privateProcedure
-    .input(z.object({ imageKey: z.string().max(255) }))
     .use(createRateLimitMiddleware(10, "1 h"))
+    .input(z.object({ imageKey: z.string().max(255) }))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1d91a7 and 26d088b.

📒 Files selected for processing (2)
  • apps/web/src/trpc/routers/user.ts (7 hunks)
  • apps/web/src/trpc/trpc.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Integration tests
  • GitHub Check: Type check
  • GitHub Check: Linting

apps/web/src/trpc/trpc.ts Show resolved Hide resolved
@lukevella lukevella changed the title ⚡️ Share rate limit instance ♻️ Clean up trpc code and add global client error handling Feb 9, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
apps/web/src/trpc/client.ts (1)

5-14: Consider selective query invalidation
Invalidating all queries on every successful mutation can be unnecessarily broad, leading to extra network requests and potential performance costs. Consider selectively invalidating only the queries relevant to the mutated data.

apps/web/src/app/api/trpc/[trpc]/route.ts (1)

34-35: Reevaluate forcing 127.0.0.1 in development
Using "127.0.0.1" during development may mask the real IP address in local testing scenarios. If you need accurate IP-based logic (e.g. rate limiting per IP), consider making the dev IP configurable or preserving the actual IP for more realistic testing.

apps/web/src/trpc/client/provider.tsx (2)

22-28: Consider adjusting query client configuration for better performance.

The current configuration disables retries and sets infinite cache time which might not be optimal for all scenarios.

Consider these adjustments:

 defaultOptions: {
   queries: {
     retry: false,
-    cacheTime: Infinity,
+    cacheTime: 1000 * 60 * 30, // 30 minutes
     staleTime: 1000 * 60,
   },
 },

29-50: Enhance error handling with more specific error messages.

The error handling could be more informative for users, especially for the TOO_MANY_REQUESTS case.

 case "TOO_MANY_REQUESTS":
   toast({
     title: t("tooManyRequests", {
       defaultValue: "Too many requests",
     }),
-    description: error.message,
+    description: t("tooManyRequestsDescription", {
+      defaultValue: "Please wait a moment before trying again.",
+    }),
   });
   break;
apps/web/src/trpc/trpc.ts (1)

125-126: Consider documenting rate limit configuration.

The example usage would benefit from a comment explaining the rate limit values.

-// Usage example:
+// Example: Limit to 5 requests per minute per IP address
 export const rateLimitMiddleware = createRateLimitMiddleware(5, "1 m");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26d088b and d076e91.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (13)
  • .env.development (1 hunks)
  • apps/web/package.json (0 hunks)
  • apps/web/src/app/[locale]/poll/[urlId]/duplicate-dialog.tsx (1 hunks)
  • apps/web/src/app/api/trpc/[trpc]/route.ts (1 hunks)
  • apps/web/src/app/providers.tsx (1 hunks)
  • apps/web/src/components/poll/manage-poll.tsx (1 hunks)
  • apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx (1 hunks)
  • apps/web/src/trpc/client.ts (1 hunks)
  • apps/web/src/trpc/client/config.ts (0 hunks)
  • apps/web/src/trpc/client/provider.tsx (1 hunks)
  • apps/web/src/trpc/routers/polls.ts (4 hunks)
  • apps/web/src/trpc/routers/user.ts (7 hunks)
  • apps/web/src/trpc/trpc.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/web/package.json
  • apps/web/src/trpc/client/config.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/trpc/routers/user.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Linting
  • GitHub Check: Type check
  • GitHub Check: Integration tests
🔇 Additional comments (11)
.env.development (1)

27-27: Review the updated SMTP host setting.
Changing SMTP_HOST from "localhost" to "0.0.0.0" now binds the SMTP service to all interfaces in development. Please verify that this is the intended behavior for your dev environment and that it won’t inadvertently expose the service outside of the trusted network.

apps/web/src/app/providers.tsx (2)

8-8: Welcome the introduction of TRPCProvider
The addition of TRPCProvider is a solid approach that aligns with the new TRPC client integration.


16-29: Verify provider layering
Currently, TRPCProvider is nested within PostHogProvider and I18nProvider. If TRPC procedures rely on locale or user data from these providers, this order is correct. Otherwise, consider moving TRPCProvider above them if the TRPC context needs to initialize earlier or remain unaffected by changes in user or locale state.

apps/web/src/app/[locale]/poll/[urlId]/duplicate-dialog.tsx (1)

18-18: LGTM!

The import path change aligns with the centralized TRPC client configuration.

apps/web/src/trpc/trpc.ts (1)

92-123: Share rate limit instances to improve performance.

Creating a new Ratelimit instance for each middleware call is inefficient.

apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx (1)

32-32: LGTM!

The import path change aligns with the centralized TRPC client configuration.

apps/web/src/components/poll/manage-poll.tsx (1)

37-37: LGTM!

The import path change aligns with the transition from @trpc/next to @trpc/react.

apps/web/src/trpc/routers/polls.ts (4)

15-15: LGTM!

The import of createRateLimitMiddleware aligns with the refactoring to share rate limit instances.


133-133: LGTM!

The rate limit of 20 requests per hour for poll creation is reasonable to prevent abuse while allowing legitimate use.


236-236: LGTM!

The rate limit of 60 requests per hour for poll updates provides flexibility for frequent modifications while maintaining protection.


309-309: LGTM!

The rate limit of 30 requests per hour for poll deletion strikes a good balance between allowing cleanup and preventing mass deletions.

@vercel vercel bot temporarily deployed to Preview – landing February 9, 2025 07:05 Inactive
@lukevella lukevella merged commit 5437b91 into main Feb 9, 2025
10 checks passed
@lukevella lukevella deleted the rate-limit branch February 9, 2025 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant