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

Add keepalive option in client.deactivate #928

Merged
merged 4 commits into from
Nov 20, 2024
Merged

Conversation

JOOHOJANG
Copy link
Contributor

@JOOHOJANG JOOHOJANG commented Nov 19, 2024

What this PR does / why we need it?

Since introducing version vectors, we have been using them for GC.
However, if the client deactivate process is not properly completed when a browser in the middle of editing is closed, the version vector table in the database retains version vectors for users whose deactivate process was incomplete.
As a result, unnecessary values remain in the minimum version vector, causing GC to fail to operate.

Therefore, we needed to enable functionality that allows the client to request the user's deactivate process when the browser is refreshed or closed. To address this, we made rpcClient.DeactivateClient callable.

Since the execution of the browser's beforeunload event handler is not guaranteed, I conducted a hit rate test with three comparison methods:

  • navigator.sendBeacon
  • fetch
  • rpcClient.DeactivateClient

Below are the hit rate comparison results. In summary, rpcClient.DeactivateClient demonstrated the highest hit rate.
As a result, without adding extra code, we configured the RPC creation process to use the keepalive option in fetch.

Test Results

  • navigator.sendBeacon

    • No throttle
      • Single refresh: 50/50 = 100%
      • Single browser close: 50/50 = 100%
      • Single refresh + single browser close: 98/100 = 98%
    • Fast 3G
      • Single refresh: 44/50 = 88%
      • Single browser close: 45/50 = 90%
      • Single refresh + single browser close: 79/100 = 79%
  • fetch + keepalive

    • No throttle
      • Single refresh: 50/50 = 100%
      • Single browser close: 50/50 = 100%
      • Single refresh + single browser close: 100/100 = 100%
    • Fast 3G
      • Single refresh: 50/50 = 100%
      • Single browser close: 49/50 = 98%
      • Single refresh + single browser close: 100/100 = 100%
  • rpc.DeactivateClient (client.deactivate({fireImmediately: true}))

    • No throttle
      • Single refresh: 50/50 = 100%
      • Single browser close: 50/50 = 100%
      • Single refresh + single browser close: 100/100 = 100%
    • Fast 3G
      • Single refresh: 50/50 = 100%
      • Single browser close: 50/50 = 100%
      • Single refresh + single browser close: 100/100 = 100%

Any background context you want to provide?

What are the relevant tickets?

Fixes #

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Enhanced deactivate functionality to allow immediate execution based on optional parameters.
    • Improved connection persistence with new transport options.
  • Bug Fixes

    • Adjusted control flow in the deactivate method to ensure correct execution with new parameters.

Copy link

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes in this pull request modify the Client class in client.ts. The deactivate method's signature has been updated to accept an optional options parameter, which includes a keepalive boolean. This allows for immediate execution of the deactivation task when options.keepalive is set to true. Additionally, the fetch function in the createGrpcWebTransport now incorporates the keepalive option, enhancing connection management during unloading. The overall control flow of the deactivate method has been adjusted to support these new functionalities while preserving existing behavior.

Changes

File Change Summary
packages/sdk/src/client/client.ts Updated deactivate method signature to accept an optional options parameter with a keepalive boolean. Added private keepalive property. Modified fetch function in createGrpcWebTransport to include keepalive option based on the Client instance's property.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RPC
    Client->>Client: deactivate(options)
    alt keepalive is true
        Client->>RPC: deactivateClient()
    else keepalive is false
        Client->>Client: enqueue deactivation
    end
Loading

🐇 "In the meadow where bunnies play,
A new method hops in, hip-hip-hooray!
With options to choose, oh what a delight,
Deactivate swiftly, or wait for the night.
Connections now strong, they won't fade away,
Thanks to the changes that brighten our day!" 🌼

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/sdk/src/client/client.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/sdk".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/sdk/.eslintrc.js » ../../.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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 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.

@JOOHOJANG JOOHOJANG self-assigned this Nov 19, 2024
@JOOHOJANG JOOHOJANG marked this pull request as ready for review November 19, 2024 05:07
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/sdk/src/client/client.ts (1)

290-303: Consider implementing a dedicated cleanup handler.

To make the deactivation process more robust, consider:

  1. Implementing a dedicated cleanup handler that manages both immediate and queued deactivation paths
  2. Using window.addEventListener('unload', ...) to automatically trigger immediate deactivation
  3. Ensuring consistent state management and logging across all cleanup scenarios
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d0ba8c3 and 4d9abb0.

📒 Files selected for processing (1)
  • packages/sdk/src/client/client.ts (2 hunks)
🔇 Additional comments (1)
packages/sdk/src/client/client.ts (1)

238-245: LGTM! Well-chosen solution for handling page unload scenarios.

The addition of keepalive: true to the fetch configuration is an excellent choice that ensures deactivation requests can complete even when the page is being unloaded, addressing the core issue of incomplete deactivation processes.

packages/sdk/src/client/client.ts Outdated Show resolved Hide resolved
@hackerwins hackerwins changed the title Set fireImmediately option in client.deactivate Add keepalive option in client.deactivate Nov 20, 2024
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins force-pushed the deactivate-beforeunload branch from 69e21c5 to 7aef309 Compare November 20, 2024 12:13
@hackerwins hackerwins merged commit 966ca89 into main Nov 20, 2024
2 checks passed
@hackerwins hackerwins deleted the deactivate-beforeunload branch November 20, 2024 12:18
Copy link

@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

🧹 Outside diff range and nitpick comments (2)
packages/sdk/src/client/client.ts (2)

239-246: Consider adding type safety for fetch configuration

While the implementation is correct, we can improve type safety by explicitly typing the init parameter.

-        fetch: (input, init) => {
+        fetch: (input: RequestInfo | URL, init?: RequestInit) => {
           const newInit = {
             ...init,
             keepalive: this.keepalive,
-          };
+          } as RequestInit;

316-321: Consider enhancing keepalive path with logging

The keepalive path could benefit from additional logging to aid debugging.

     if (options.keepalive) {
       this.keepalive = true;
+      logger.debug(`[DC] c:"${this.getKey()}" deactivating with keepalive enabled`);
       const resp = task();
       this.keepalive = false;
+      logger.debug(`[DC] c:"${this.getKey()}" keepalive flag reset`);
       return resp;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a7707bf and 7aef309.

📒 Files selected for processing (1)
  • packages/sdk/src/client/client.ts (3 hunks)
🔇 Additional comments (3)
packages/sdk/src/client/client.ts (3)

202-202: LGTM: Well-placed keepalive property

The private keepalive property is appropriately placed and follows TypeScript conventions.


290-294: LGTM: Clear and informative documentation

The documentation clearly explains the purpose and use case of the keepalive option.


301-314: LGTM: Well-structured task implementation

The task implementation is well-organized and handles errors appropriately.

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