Skip to content

#2223 - elderberry #2363

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

Closed
wants to merge 1 commit into from
Closed

Conversation

swyxio
Copy link

@swyxio swyxio commented Aug 7, 2025

special pr for eric

Adding a small SWR middleware utility to log if a fetcher is present (indicating a potential global fetcher), and wiring it into our realtime hooks' useSWR calls to validate the assumption without changing behavior. I'll implement the utility and update useRealtime.ts accordingly.
Ran tool
Ran tool
Ran tool

  • Looked through packages/react-hooks for our internal realtime hooks and how they use SWR. Found that our realtime hooks intentionally use SWR as a local store by passing null as the fetcher (so they shouldn’t use any global SWRConfig fetcher).
  • Identified potential risks where a global SWRConfig fetcher might still impact us:
    • Some future internal calls could forget to pass a fetcher or null, inadvertently falling back to the global fetcher.
    • SWR revalidation/middleware or consumer-side usage might inject a fetcher unexpectedly into our calls.
    • Key collision with consumer SWR usage (less likely because our keys include a per-instance useId()).

What I’m doing now:

  • I added lightweight logging middleware to our realtime useSWR calls to detect if a fetcher (likely from global SWRConfig) is present. This adheres to your “add logs to validate assumptions before fixing” direction, without changing behavior.

Edits made:

  • Added logIfFetcherPresent middleware:
    • packages/react-hooks/src/utils/swrMiddleware.ts
  • Wired the middleware into all realtime useSWR store instances:
    • packages/react-hooks/src/hooks/useRealtime.ts (for run, streams, error, complete, runs)

These logs only fire in development and won’t break anything. If a global fetcher is being used by our realtime hooks, you’ll see warnings like:
[trigger.dev][realtime:run] Detected a fetcher for SWR key. This hook is intended to manage its own data; an inherited global SWR fetcher may cause unintended requests.

Proposed most likely root causes to validate with these logs:

  • Most likely: One or more internal useSWR calls that should pass null accidentally omit it (or regressions in future changes).
  • Also likely: A consumer app wraps everything with <SWRConfig value={{ fetcher: ... }}>, and SWR ends up injecting that fetcher into our hooks if we’d ever forget the null guard.

Next steps (after we confirm via logs):

  • Harden prevention:

    • Add a blocking middleware variant that overrides any injected fetcher to null and disables revalidation options for our realtime store calls.
    • Optionally namespace our SWR cache keys (e.g., ['@trigger.dev/realtime', idKey, 'run']) to reduce any chance of collision with consumer keys.
  • Keep current behavior for SWR-based fetching hooks (like useRun) that intentionally provide a fetcher.

  • Changes:

    • Added logIfFetcherPresent middleware in packages/react-hooks/src/utils/swrMiddleware.ts.
    • Applied middleware in packages/react-hooks/src/hooks/useRealtime.ts to every internal useSWR store usage to log if a fetcher is present (potential global fetcher injection).
  • Impact:

    • Non-invasive development-only logs to validate whether global SWRConfig fetchers are ever invoked by our realtime hooks.
    • No behavioral changes to fetching or performance.

Copy link

changeset-bot bot commented Aug 7, 2025

⚠️ No Changeset found

Latest commit: 61a3f6f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

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

Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

Walkthrough

A middleware function named logIfFetcherPresent has been introduced in the SWR middleware utilities. This middleware logs a warning in development mode if a fetcher function is present when using SWR hooks, helping to identify potential misconfigurations. The middleware is parameterized with a label for contextual logging. In the useRealtime.ts file, this middleware is now applied to all SWR hook usages related to realtime run data, errors, completion flags, streams, and runs arrays. No changes were made to exported function signatures or the overall logic of the hooks.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e46e9bd and 61a3f6f.

📒 Files selected for processing (2)
  • packages/react-hooks/src/hooks/useRealtime.ts (8 hunks)
  • packages/react-hooks/src/utils/swrMiddleware.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code
For TypeScript, we usually use types over interfaces
Avoid enums
No default exports, use function declarations

Files:

  • packages/react-hooks/src/utils/swrMiddleware.ts
  • packages/react-hooks/src/hooks/useRealtime.ts
🧠 Learnings (8)
📓 Common learnings
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When logging in tasks, use the `logger` API (`logger.debug`, `logger.log`, `logger.info`, `logger.warn`, `logger.error`) as shown.
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using Realtime features, use the `runs.subscribeToRun`, `runs.subscribeToRunsWithTag`, and `runs.subscribeToBatch` APIs as shown.
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T17:49:24.468Z
Learning: Applies to **/*.{ts,tsx} : Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when logging in tasks, use the `logger` api (`logger.de...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When logging in tasks, use the `logger` API (`logger.debug`, `logger.log`, `logger.info`, `logger.warn`, `logger.error`) as shown.

Applied to files:

  • packages/react-hooks/src/utils/swrMiddleware.ts
  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/*.{ts,tsx} : always prefer using isomorphic code like fetch, readablestream, etc. inst...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T17:49:24.468Z
Learning: Applies to **/*.{ts,tsx} : Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code

Applied to files:

  • packages/react-hooks/src/utils/swrMiddleware.ts
  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using realtime features, use the `runs.subscribeto...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using Realtime features, use the `runs.subscribeToRun`, `runs.subscribeToRunsWithTag`, and `runs.subscribeToBatch` APIs as shown.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using metadata in tasks, use the `metadata` api as...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using metadata in tasks, use the `metadata` API as shown, and only inside run functions or task lifecycle hooks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : you must use `@trigger.dev/sdk/v3` when writing trigger...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : You MUST use `trigger.dev/sdk/v3` when writing Trigger.dev tasks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using idempotency, use the `idempotencykeys` api a...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using idempotency, use the `idempotencyKeys` API and `idempotencyKey`/`idempotencyKeyTTL` options as shown.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: in apps/webapp/app/services/runsrepository.server.ts, the in-memory status filtering after fetching ...
Learnt from: matt-aitken
PR: triggerdotdev/trigger.dev#2264
File: apps/webapp/app/services/runsRepository.server.ts:172-174
Timestamp: 2025-07-12T18:06:04.133Z
Learning: In apps/webapp/app/services/runsRepository.server.ts, the in-memory status filtering after fetching runs from Prisma is intentionally used as a workaround for ClickHouse data delays. This approach is acceptable because the result set is limited to a maximum of 100 runs due to pagination, making the performance impact negligible.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
🔇 Additional comments (7)
packages/react-hooks/src/utils/swrMiddleware.ts (1)

11-25: LGTM! Implementation is appropriate for the context.

The middleware function is well-implemented for its intended purpose of detecting unintended fetcher injection in realtime hooks. The use of process.env.NODE_ENV and console.warn is appropriate for client-side React hooks, even though the organization generally prefers isomorphic code and the logger API for server-side tasks.

packages/react-hooks/src/hooks/useRealtime.ts (6)

12-12: LGTM! Clean import addition.

The import correctly brings in the middleware function from the utils module.


82-99: LGTM! Consistent middleware application.

The middleware has been properly applied to all SWR calls in useRealtimeRun with appropriate contextual labels. The implementation follows SWR middleware patterns correctly.


234-267: LGTM! Comprehensive middleware integration.

All SWR calls in useRealtimeRunWithStreams have been consistently updated with the logging middleware while preserving existing configurations like fallbackData. The contextual labels clearly identify each data type.


418-433: LGTM! Proper middleware integration with preserved configurations.

The middleware has been correctly applied to both SWR calls in useRealtimeRunsWithTag, maintaining existing fallbackData settings while adding the diagnostic logging capability.


518-533: LGTM! Final middleware applications complete the integration.

The last set of SWR calls in useRealtimeBatch have been properly updated with the logging middleware, completing the comprehensive integration across all realtime hooks. The labeling remains consistent with other hooks.


12-533: Excellent systematic implementation of the diagnostic middleware.

The integration of logIfFetcherPresent middleware across all realtime hooks is comprehensive and well-executed. Key strengths:

  • Systematic coverage: All useSWR calls across 4 hook functions are consistently updated
  • Contextual labeling: Each middleware usage has appropriate labels for easy identification
  • Non-invasive: No existing logic is modified, only diagnostic capabilities added
  • Consistent patterns: Follows SWR middleware conventions throughout

This implementation successfully achieves the PR objective of adding development-only logging to detect unintended global fetcher usage without impacting runtime behavior.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @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 closed this Aug 13, 2025
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.

2 participants