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

Handle errors thrown by requests in Realtime react hooks #1599

Merged
merged 1 commit into from
Jan 10, 2025
Merged

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Jan 10, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for real-time React hooks
    • Enhanced reliability of useRealtimeRun hook's onComplete callback
    • Fixed error display conditions in run details component
  • New Features

    • Added custom error handling callbacks for API client methods
    • Introduced more flexible error management in stream operations
  • Chores

    • Updated dependencies for @trigger.dev/react-hooks and @trigger.dev/core

Copy link

changeset-bot bot commented Jan 10, 2025

🦋 Changeset detected

Latest commit: f6cb399

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
@trigger.dev/react-hooks Patch
@trigger.dev/core Patch
references-nextjs-realtime Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/sdk Patch
@internal/redis-worker Patch
@internal/zod-worker Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
@internal/testcontainers Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Warning

Rate limit exceeded

@ericallam has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 0 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 6e58a21 and f6cb399.

📒 Files selected for processing (8)
  • .changeset/many-panthers-relax.md (1 hunks)
  • .changeset/silent-dragons-chew.md (1 hunks)
  • packages/core/src/v3/apiClient/index.ts (2 hunks)
  • packages/core/src/v3/apiClient/runStream.ts (2 hunks)
  • packages/core/src/v3/apiClient/stream.ts (2 hunks)
  • packages/react-hooks/src/hooks/useRealtime.ts (10 hunks)
  • references/nextjs-realtime/src/app/actions.ts (2 hunks)
  • references/nextjs-realtime/src/app/runs/[id]/ClientRunDetails.tsx (1 hunks)

Walkthrough

This pull request introduces comprehensive error handling and improved state management for real-time hooks in the Trigger.dev React library. The changes focus on enhancing the useRealtimeRun hook and related API client methods by adding optional error handling callbacks, improving the reliability of real-time run tracking. The modifications span multiple packages, including @trigger.dev/react-hooks, @trigger.dev/core, and some reference implementations, with a primary goal of making error management more flexible and robust.

Changes

File Change Summary
.changeset/ Added patch changesets for @trigger.dev/react-hooks and @trigger.dev/core
packages/core/src/v3/apiClient/index.ts Added optional onFetchError callback to subscribeToRun, subscribeToRunsWithTag, and subscribeToBatch methods
packages/core/src/v3/apiClient/runStream.ts Introduced onFetchError option in RunShapeStreamOptions for custom error handling
packages/core/src/v3/apiClient/stream.ts Added onError callback to ZodShapeStreamOptions
packages/react-hooks/src/hooks/useRealtime.ts Enhanced error handling in realtime processing functions, added completion state tracking
references/nextjs-realtime/src/app/actions.ts Updated public access token generation using auth.createPublicToken
references/nextjs-realtime/src/app/runs/[id]/ClientRunDetails.tsx Modified error rendering condition

Sequence Diagram

sequenceDiagram
    participant User as User Code
    participant Hook as useRealtimeRun
    participant ApiClient as API Client
    participant ErrorHandler as Error Callback

    User->>Hook: Trigger realtime run
    Hook->>ApiClient: Subscribe to run
    ApiClient-->>Hook: Stream run data
    alt Error occurs
        ApiClient->>ErrorHandler: Invoke onFetchError
        ErrorHandler->>User: Handle error
    end
    Hook->>Hook: Update run completion state
Loading

Possibly related PRs

Poem

🐰 Realtime Rabbit's Error Dance

Hooks that stream with grace and might,
Errors caught in rabbit's light,
Callbacks dancing, state so clear,
Trigger's magic drawing near!

🚀 Robust and swift, our code takes flight! 🌟


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.

@ericallam ericallam merged commit e13edd3 into main Jan 10, 2025
2 checks passed
@ericallam ericallam deleted the ea-branch-5 branch January 10, 2025 19:40
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
references/nextjs-realtime/src/app/actions.ts (1)

Line range hint 31-52: Maintain consistency in token generation approach

The batchTriggerExampleTask function still uses the old token generation approach (handle.publicAccessToken), while triggerExampleTask has been updated to use auth.createPublicToken. This inconsistency could lead to different security models between single and batch operations.

Apply the same token generation pattern to maintain consistency:

  console.log("Batch trigger example task");

  const handle = await tasks.batchTrigger<typeof exampleTask>("example", [
    { payload: { id: randomUUID() } },
    // ... other entries ...
  ]);

-  console.log("Setting the run JWT in a cookie", handle.publicAccessToken);
+  const publicToken = await auth.createPublicToken({
+    scopes: {
+      read: {
+        runs: handle.runIds, // Assuming handle provides runIds for batch operations
+      },
+    },
+    expirationTime: "2s",
+  });
+
+  console.log("Setting the run JWT in a cookie", publicToken);

  // Set JWT in a secure, HTTP-only cookie
-  cookies().set("run_token", handle.publicAccessToken);
+  cookies().set("run_token", publicToken, {
+    httpOnly: true,
+    secure: true,
+    sameSite: "strict"
+  });
🧹 Nitpick comments (1)
.changeset/many-panthers-relax.md (1)

1-5: Expand the changeset description to cover all changes.

While the current description mentions fixing the onComplete hook timing, it doesn't reflect the significant error handling improvements that are part of this patch. Consider expanding the description to include:

  • Addition of onError callbacks for improved error handling
  • Updates to processRealtimeBatch, processRealtimeRunsWithTag, etc.
  • Integration with apiClient error handling capabilities

This will help users better understand the full scope of changes in this patch.

Here's a suggested expanded description:

---
"@trigger.dev/react-hooks": patch
---

-Make sure useRealtimeRun onComplete hook fires at the correct time
+Improve real-time hooks reliability:
+- Fix useRealtimeRun onComplete hook timing
+- Add comprehensive error handling with onError callbacks
+- Enhance error management in real-time batch processing
+- Integrate with apiClient error handling capabilities
🛑 Comments failed to post (2)
references/nextjs-realtime/src/app/actions.ts (2)

26-26: 🛠️ Refactor suggestion

Enhance cookie security attributes

While using HTTP-only cookies is good, consider adding additional security attributes:

-  cookies().set("run_token", publicToken);
+  cookies().set("run_token", publicToken, {
+    httpOnly: true,
+    secure: true,
+    sameSite: "strict"
+  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  cookies().set("run_token", publicToken, {
    httpOnly: true,
    secure: true,
    sameSite: "strict"
  });

14-21: 💡 Codebase verification

Increase token expiration time to 30 seconds

The current 2-second expiration is too aggressive for real-time subscriptions. A 30-second window provides:

  • Sufficient time for connection setup (DNS, TCP, TLS, WebSocket/SSE)
  • Better tolerance for network latency and clock skew
  • Still maintains security with a reasonably short lifetime
🔗 Analysis chain

Consider increasing the token expiration time

The 2-second expiration time might be too short for slower network conditions or when the client and server have clock differences. Consider increasing it to provide a better buffer while maintaining security.

To help determine an appropriate expiration time, we can analyze the typical request patterns:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Look for timing patterns in network requests
rg -A 5 "useRealtimeRun|subscribeToRun" --type ts

Length of output: 20071

Copy link

pkg-pr-new bot commented Jan 10, 2025

@trigger.dev/build

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1599

@trigger.dev/react-hooks

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/react-hooks@1599

@trigger.dev/rsc

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/rsc@1599

@trigger.dev/sdk

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1599

@trigger.dev/core

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1599

trigger.dev

npm i https://pkg.pr.new/triggerdotdev/trigger.dev@1599

commit: f6cb399

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