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

fix: use setTimeout Promise #58

Merged
merged 5 commits into from
Dec 8, 2024
Merged

fix: use setTimeout Promise #58

merged 5 commits into from
Dec 8, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 8, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a custom sleep function for handling delays.
    • Added a new GitHub Actions workflow for continuous integration with Node.js 14.
  • Bug Fixes

    • Maintained existing error handling for retry logic in the waitPort function.

Copy link

coderabbitai bot commented Dec 8, 2024

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 44 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 3e2eefc and 93ee000.

📒 Files selected for processing (1)
  • .github/workflows/nodejs-14.yml (1 hunks)

Walkthrough

The changes in this pull request involve the introduction of a custom sleep function in src/wait-port.ts, which replaces the previous import of setTimeout from the node:timers/promises module. This new function returns a Promise that resolves after a specified delay, allowing the waitPort function to pause execution based on the retryInterval specified in the options. The overall logic of waitPort remains unchanged, including its error handling.

Changes

File Change Summary
src/wait-port.ts Added custom sleep(ms: number) function; modified waitPort to use the new sleep function while keeping its logic unchanged. Error handling remains the same.
.github/workflows/nodejs-14.yml Introduced a new CI workflow for Node.js 14, including steps for checking out code, setting up Node.js, installing dependencies, and running a detection script.

Possibly related PRs

Poem

In the burrow deep, where the timers sleep,
A new function hops, with promises to keep.
No more delays from afar, oh so bright,
Just a cozy sleep to make things right.
With every retry, the port shall wait,
In the world of code, we celebrate! 🐇✨


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.

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)
src/wait-port.ts (2)

6-10: Consider using built-in setTimeout from node:timers/promises

The custom sleep implementation, while functional, appears to be replacing the built-in setTimeout from node:timers/promises which is a stable API since Node.js 15.0.0. What's the rationale for this change?

If we must keep the custom implementation, consider adding input validation:

 function sleep(ms: number) {
+  if (ms < 0) throw new Error('Sleep duration must be non-negative');
   return new Promise(resolve => {
     setTimeout(resolve, ms);
   });
 }

Line range hint 39-44: Consider potential race condition in port verification

There's a potential race condition in the retry logic. After detecting a free port and sleeping, the port's status might change before the next iteration. Consider verifying the port status both before and after the sleep:

   const freePort = await detectPort(port);
   if (freePort === port) {
     await sleep(retryInterval);
+    // Re-verify port status after sleep
+    const currentPort = await detectPort(port);
+    if (currentPort !== port) {
+      return true;
+    }
     return loop();
   }
   return true;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b2cf1bb and 413d799.

📒 Files selected for processing (1)
  • src/wait-port.ts (1 hunks)

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: 3

🧹 Outside diff range and nitpick comments (3)
.github/workflows/nodejs-14.yml (3)

5-5: Consider using main instead of master

GitHub now recommends using main as the default branch name instead of master for inclusive language.

-    branches: [ master ]
+    branches: [ main ]

Also applies to: 7-7


19-20: Add npm dependency caching

Adding cache for npm dependencies will speed up the workflow execution.

Add this step before npm install:

- name: Cache node modules
  uses: actions/cache@v3
  with:
    path: ~/.npm
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-node-

21-23: Simplify Node.js version verification

The current approach of checking Node.js version before and after switching seems redundant. Consider combining these steps.

-      - run: node -v
-      - run: nvm install 14 && nvm use 14
-      - run: node -v
+      - name: Switch to Node.js 14
+        run: |
+          nvm install 14 && nvm use 14
+          echo "Using Node.js $(node -v)"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 413d799 and 3e2eefc.

📒 Files selected for processing (1)
  • .github/workflows/nodejs-14.yml (1 hunks)
🔇 Additional comments (1)
.github/workflows/nodejs-14.yml (1)

1-24: Verify setTimeout Promise compatibility with Node.js 14

Since this workflow tests Node.js 14 compatibility and the PR changes involve Promise-based setTimeout, we should verify the implementation works correctly.

✅ Verification successful

Let me check the implementation details of the setTimeout usage to ensure it's Node.js 14 compatible.


Node.js 14 compatibility is properly maintained

The setTimeout implementation in the codebase is using the standard callback-based approach which is fully compatible with Node.js 14:

  • Uses traditional Promise constructor with callback-based setTimeout in sleep function
  • No usage of node:timers/promises or Promise-based setTimeout
  • Test cases also use standard setTimeout with callbacks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the codebase uses node:timers/promises which is not available in Node.js 14
rg -l "node:timers/promises" || echo "No direct usage of node:timers/promises found"

# Check for setTimeout Promise usage
ast-grep --pattern 'setTimeout($$$)'

Length of output: 359


Script:

#!/bin/bash
# Check the implementation of wait-port.ts
cat src/wait-port.ts

# Check the test file
cat test/wait-port.test.ts

Length of output: 2426

Comment on lines 19 to 24
- run: npm install
- run: npm run prepublishOnly
- run: node -v
- run: nvm install 14 && nvm use 14
- run: node -v
- run: node dist/commonjs/bin/detect-port.js
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add explicit test step

The workflow is missing an explicit test step. While prepublishOnly might run tests, it's better to have a dedicated test step for clarity.

Add this step after prepublishOnly:

      - name: Run tests
        run: npm test

- run: node -v
- run: nvm install 14 && nvm use 14
- run: node -v
- run: node dist/commonjs/bin/detect-port.js
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for detect-port binary execution

The workflow should handle potential failures when running the detect-port binary and provide meaningful error output.

-      - run: node dist/commonjs/bin/detect-port.js
+      - name: Test detect-port binary
+        run: |
+          set -e
+          if ! output=$(node dist/commonjs/bin/detect-port.js 2>&1); then
+            echo "Error running detect-port: $output"
+            exit 1
+          fi
📝 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.

Suggested change
- run: node dist/commonjs/bin/detect-port.js
- name: Test detect-port binary
run: |
set -e
if ! output=$(node dist/commonjs/bin/detect-port.js 2>&1); then
echo "Error running detect-port: $output"
exit 1
fi

Comment on lines +16 to +18
uses: irby/setup-node-nvm@master
with:
node-version: '16.x'
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using the official Node.js setup action

The workflow uses irby/setup-node-nvm@master which is a third-party action. For better security and reliability, consider using the official actions/setup-node action which also supports multiple Node.js versions.

-        uses: irby/setup-node-nvm@master
+        uses: actions/setup-node@v4
         with:
-          node-version: '16.x'
+          node-version: ['14.x', '16.x']

Committable suggestion skipped: line range outside the PR's diff.

@fengmk2 fengmk2 merged commit db3ce1b into master Dec 8, 2024
8 checks passed
@fengmk2 fengmk2 deleted the allow-run-on-node-14 branch December 8, 2024 15:57
fengmk2 pushed a commit that referenced this pull request Dec 8, 2024
[skip ci]

## [2.0.1](v2.0.0...v2.0.1) (2024-12-08)

### Bug Fixes

* use setTimeout Promise ([#58](#58)) ([db3ce1b](db3ce1b))
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