Skip to content

feat(client): add retryDelayMs-option to retryLink - #6694

Merged
KATT merged 5 commits into
trpc:mainfrom
rynobax:rynobax/retry-delay
Apr 11, 2025
Merged

KATT merged 5 commits into
trpc:mainfrom
rynobax:rynobax/retry-delay

Conversation

@rynobax

@rynobax rynobax commented Apr 10, 2025 •

Copy link
Copy Markdown
Contributor

Addresses #6425

🎯 Changes

Add a retryDelay option to RetryLink. Right now it defaults to immediately retrying on failure, this allows introducing a delay.

IMO this should have a reasonable default (what i provided in the docs is the tanstack query default). Since that would be a breaking change, I think it makes sense to do it in a follow up pr.

✅ Checklist

  • I have followed the steps listed in the Contributing guide.
  • If necessary, I have added documentation related to the changes made.
  • I have added or updated the tests related to the changes made.

Summary by CodeRabbit

  • New Features

    • Enabled customizable retry delays between attempts, allowing users to define specific wait times based on the retry iteration.
    • Introduced a new function for simulating operation links that can fail a specified number of times before succeeding.
  • Bug Fixes

    • Enhanced testing capabilities for the retry mechanism with additional test cases covering various scenarios.
  • Documentation

    • Updated help materials to guide users on configuring the new customizable retry delay option.

@rynobax
rynobax requested review from a team as code owners April 10, 2025 19:25
@vercel

vercel Bot commented Apr 10, 2025 •

Copy link
Copy Markdown

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

Name Status Preview Comments Updated (UTC)
www ❌ Failed (Inspect) Apr 11, 2025 11:51am

@coderabbitai

coderabbitai Bot commented Apr 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request introduces an optional property retryDelayMs to the RetryLinkOptions interface, allowing users to define a custom delay in milliseconds between retry attempts based on the current attempt number. The retry logic has been modified to utilize this delay, defaulting to 0 if not specified. Additionally, the documentation has been updated to reflect this new functionality. In the server tests, a new property runAllTimers has been added to enhance timer management capabilities.

Changes

File(s) Summary
packages/client/src/links/retryLink.ts Added optional property retryDelayMs?: (attempt: number) => number to RetryLinkOptions and modified retry logic to use setTimeout with the computed delay.
www/docs/client/links/retryLink.md Updated documentation to include the new retryDelay property, explaining its use for computing delay between retries (doubling per attempt, capped at 30s).
packages/server/src/tests/fakeTimersResource.ts Added runAllTimers property to the object returned by makeResource in fakeTimersResource, providing access to the vi.runAllTimers method.
packages/tests/server/links.test.ts Introduced createEndingLink function for simulating retry operations, added multiple tests for retry behavior, including delay and unsubscribe scenarios.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant R as RetryLink
  participant T as Timer

  C->>R: Execute operation
  R-->>C: Operation fails
  R->>R: Compute delay using retryDelayMs(attempt) or default 0
  R->>T: setTimeout(delay)
  T-->>R: Timeout complete
  R->>C: Retry operation
Loading

Poem

I'm a little code rabbit on a joyful spree,
Hopping through retries, wild and free.
With a delay to ponder, each attempt takes its time,
Doubling my efforts, oh what a climb!
New features are here, let’s give them a cheer,
For every retry, I’ll hop without fear! 🐇

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 5a2c0e1 and af40925.

📒 Files selected for processing (3)
  • packages/client/src/links/retryLink.ts (4 hunks)
  • packages/server/src/__tests__/fakeTimersResource.ts (1 hunks)
  • packages/tests/server/links.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/tests/server/links.test.ts (5)
packages/server/src/unstable-core-do-not-import/clientish/inferrable.ts (1)
  • InferrableClientTypes (31-35)
packages/client/src/links/types.ts (1)
  • OperationLink (95-104)
packages/server/src/observable/index.ts (2)
  • observable (3-3)
  • observableToPromise (5-5)
packages/client/src/links/retryLink.ts (1)
  • retryLink (39-117)
packages/server/src/__tests__/fakeTimersResource.ts (1)
  • fakeTimersResource (3-16)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: E2E-tests (vercel-edge-runtime)
  • GitHub Check: E2E-tests (next-prisma-starter)
  • GitHub Check: E2E-tests (next-prisma-websockets-starter)
  • GitHub Check: E2E-tests (next-prisma-todomvc)
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: Lint and auto-fix
  • GitHub Check: test
🔇 Additional comments (11)
packages/server/src/__tests__/fakeTimersResource.ts (1)

10-10: Good addition for handling timers in tests

Adding runAllTimers is an appropriate extension to the test utilities, making it possible to control timer behavior in the new retry delay tests.

packages/client/src/links/retryLink.ts (4)

15-18: Good documentation and implementation of retry delay option

The added property is well-documented with a clear description of its purpose and default behavior.


49-50: Proper timeout tracking

Good addition of a timeout tracking variable to manage the delay between retry attempts.


78-91: Well-implemented retry logic with delay support

The retry logic has been enhanced with delay support, maintaining backward compatibility by defaulting to 0 when no delay is specified. The code correctly handles both immediate retries and delayed retries.


112-112: Essential cleanup to prevent memory leaks

Clearing the timeout during unsubscription is crucial to prevent memory leaks, especially for long-running applications.

packages/tests/server/links.test.ts (6)

2-3: Appropriate imports for the new test functionality

The added imports support the new test functionality, including timer management and typing for the mock link implementation.

Also applies to: 17-18


862-884: Well-designed test helper function

The createEndingLink helper is well-designed and reusable, making it easy to test different retry scenarios by configuring the number of failures before success.


886-915: Good baseline test case for retry functionality

This happy path test establishes a baseline for the retry functionality, ensuring that the link works correctly when no retries are needed.


917-946: Comprehensive test for retry behavior

This test effectively verifies that the retry link correctly attempts the operation multiple times before succeeding, confirming the core retry functionality.


948-987: Thorough test for the delay functionality

This test verifies that the retry link correctly handles delays between retry attempts, using fake timers to control the timing behavior.

The use of process.nextTick() to trigger timer advancement is a clean approach to ensure timers run in a controlled manner during testing.


989-1021: Important edge case test for cleanup behavior

This test validates that unsubscribing during a delay properly cancels future retry attempts, which is important for preventing unexpected behavior and resource leaks.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@vercel

vercel Bot commented Apr 10, 2025

Copy link
Copy Markdown

@rynobax is attempting to deploy a commit to the trpc Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/client/src/links/retryLink.ts (1)

77-84: Retry delay implementation looks good but has a minor optimization opportunity.

The implementation correctly handles the optional retry delay with a good fallback to 0 when not provided. However, there's a small opportunity to make the code more DRY by avoiding the duplication of attempt(attempts + 1).

- const delay = opts.retryDelay?.(attempts) ?? 0;
- if (delay) {
-   setTimeout(() => {
-     attempt(attempts + 1);
-   }, delay);
- } else {
-   attempt(attempts + 1);
- }
+ const delay = opts.retryDelay?.(attempts) ?? 0;
+ if (delay) {
+   setTimeout(() => attempt(attempts + 1), delay);
+ } else {
+   attempt(attempts + 1);
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd28640 and dcee44f.

📒 Files selected for processing (2)
  • packages/client/src/links/retryLink.ts (2 hunks)
  • www/docs/client/links/retryLink.md (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (next-minimal-starter)
  • GitHub Check: E2E-tests (vercel-edge-runtime)
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: E2E-tests (minimal-react)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: test
  • GitHub Check: Lint and auto-fix
🔇 Additional comments (3)
packages/client/src/links/retryLink.ts (1)

15-18: Well-documented addition to RetryLinkOptions interface.

The retryDelay property is properly typed as an optional function with clear documentation explaining its purpose and default behavior.

www/docs/client/links/retryLink.md (2)

40-41: Great example of exponential backoff with a sensible maximum cap.

The provided example demonstrates an excellent implementation of an exponential backoff strategy, which is a best practice for retries. The maximum cap of 30 seconds prevents excessive wait times for users while still allowing for proper backing off.


65-68: Documentation matches implementation and is clear.

The documentation for the retryDelay property is consistent with the implementation in the source code and clearly explains its purpose and default behavior.

@pkg-pr-new

pkg-pr-new Bot commented Apr 10, 2025 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/trpc/trpc/@trpc/client@6694

@trpc/next

npm i https://pkg.pr.new/trpc/trpc/@trpc/next@6694

@trpc/server

npm i https://pkg.pr.new/trpc/trpc/@trpc/server@6694

@trpc/react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/react-query@6694

@trpc/tanstack-react-query

npm i https://pkg.pr.new/trpc/trpc/@trpc/tanstack-react-query@6694

@trpc/upgrade

npm i https://pkg.pr.new/trpc/trpc/@trpc/upgrade@6694

commit: af40925

@rynobax rynobax changed the title add docs feat: add retryDelay option to RetryLink Apr 10, 2025
@rynobax rynobax reopened this Apr 10, 2025
@rynobax
rynobax marked this pull request as ready for review April 10, 2025 19:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
www/docs/client/links/retryLink.md (1)

65-68: Review the new retryDelay property in the interface.
The addition of the optional property retryDelay?: (attempt: number) => number is well documented, explaining that it defaults to 0 if not provided. For improved clarity, consider including a brief note or example in the documentation to illustrate its usage and behavior.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dcee44f and 5a2c0e1.

📒 Files selected for processing (1)
  • www/docs/client/links/retryLink.md (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Lint and auto-fix
🔇 Additional comments (1)
www/docs/client/links/retryLink.md (1)

40-41: Verify the retryDelay function behavior in the usage example.
The function correctly employs exponential backoff by doubling delay per attempt and capping at 30 seconds. Please verify that the initial delay (when attempt index is 0) meets developer expectations (1 second).

@KATT KATT left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Added tests and fixed an edge-case when unsubscribing during the delay

@KATT KATT changed the title feat: add retryDelay option to RetryLink feat(client): add retryDelayMs-option to retryLink (#6694) Apr 11, 2025
@KATT KATT changed the title feat(client): add retryDelayMs-option to retryLink (#6694) feat(client): add retryDelayMs-option to retryLink Apr 11, 2025
@KATT
KATT merged commit 129addc into trpc:main Apr 11, 2025
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Apr 12, 2025

This branch was successfully deployed

2 active deployments
Preview – www — af409255 Deployed Apr 11, 2025 by vercel[bot]
Preview – trpc-next-app-dir — af409255 Deployed Apr 11, 2025 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants