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: ignore npm registry 404 status response on sync process #740

Merged
merged 3 commits into from
Dec 9, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 9, 2024

closes #739

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for package synchronization, including specific logging for package not found scenarios.
    • Simplified criteria for identifying removed packages.
  • Bug Fixes

    • Corrected documentation for the syncMode property.
  • Chores

    • Updated dependency versions in package.json.
  • Tests

    • Added new test cases and refined existing assertions to improve logging and error handling verification.

Copy link
Contributor

coderabbitai bot commented Dec 9, 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 24 minutes and 54 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 2285320 and a761058.

📒 Files selected for processing (2)
  • app/core/service/PackageSyncerService.ts (7 hunks)
  • test/core/service/PackageSyncerService/executeTask.test.ts (4 hunks)

Walkthrough

The changes in this pull request focus on enhancing error handling and refining logic within the PackageSyncerService.ts file, particularly in the executeTask method. Modifications include improved handling of 404 and 451 status codes, adjustments to the determination of security holder packages, and updates to logging and error handling in the syncDeletePkg method. Additionally, documentation corrections were made in app/port/config.ts, and dependency versions were updated in package.json. The test suite for PackageSyncerService was also enhanced with new test cases and refined assertions.

Changes

File Change Summary
app/core/service/PackageSyncerService.ts - Enhanced error handling for 404 and 451 status codes in executeTask method.
- Updated logic for identifying security holder packages.
- Improved logging and error handling in syncDeletePkg method.
app/port/config.ts - Corrected documentation comment for syncMode property in CnpmcoreConfig type.
package.json - Updated validate-npm-package-name from ^3.0.0 to ^6.0.0.
- Updated @types/validate-npm-package-name from ^4.0.0 to ^4.0.2.
test/core/service/PackageSyncerService/executeTask.test.ts - Renamed test case from "mock 404" to "mock 451".
- Added new test case for syncing a deprecated package while ignoring a 404 error.
- Modified assertions for log messages and conditions.

Assessment against linked issues

Objective Addressed Explanation
Handle 404 responses during npm registry maintenance (#739)

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • elrrrrrrr

Poem

🐰 In the code where packages roam,
Errors handled, they find their home.
With logs that tell of tasks gone awry,
Syncing smoothly, oh my, oh my!
A hop, a skip, through versions we glide,
In the world of code, we take great pride! 🌟


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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
app/core/service/PackageSyncerService.ts (2)

580-580: Avoid early task failure for invalid maintainers

When no maintainers are found, the task is marked as failed immediately. Considering intermittent issues during maintenance, it might be better to log the error and retry instead of failing immediately.

Consider modifying the code to retry the task:

          await this.taskService.finishTask(task, TaskState.Fail, logs.join('\n'));
+         // Optionally, you could choose to retry the task instead
+         // await this.taskService.retryTask(task, logs.join('\n'));
          return;

799-799: Handle complete sync failure gracefully

When all version syncs fail and the package does not exist locally, the task is marked as failed with the last error message. Consider providing more context in the logs to aid debugging and potentially implementing retry logic if appropriate.

Enhance the logs for clarity:

          task.error = lastErrorMessage;
          logs.push(`[${isoNow()}] ❌ All versions failed to sync for ${fullname}, no local package found.`);
          logs.push(`[${isoNow()}] ❌ Last error: ${task.error}, log: ${logUrl}`);
          logs.push(`[${isoNow()}] ${failEnd}`);
test/core/service/PackageSyncerService/executeTask.test.ts (2)

212-214: Clarify test case for handling 451 status code

The test case mocks a 451 status but is described as "mock 404". Update the description to accurately reflect that this test is for handling a 451 status code when syncing a deprecated package.

Apply this change:

-     it('should sync cnpmcore-test-sync-deprecated and mock 404', async () => {
+     it('should sync cnpmcore-test-sync-deprecated and mock 451', async () => {

321-322: Remove unnecessary console.log in tests

The console.log(log); statement on line 321 is not necessary and can clutter test output. Consider removing it to keep the test output clean.

Apply this diff to remove the log statement:

-       console.log(log);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 167e37c and 2285320.

📒 Files selected for processing (4)
  • app/core/service/PackageSyncerService.ts (7 hunks)
  • app/port/config.ts (1 hunks)
  • package.json (2 hunks)
  • test/core/service/PackageSyncerService/executeTask.test.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • app/port/config.ts
🔇 Additional comments (4)
package.json (2)

141-141: LGTM: Type definitions update

The minor version bump of @types/validate-npm-package-name (4.0.0 → 4.0.2) aligns with the main package update and includes only backward-compatible changes.


122-122: Verify compatibility with validate-npm-package-name v6.0.0

The major version bump (3.x → 6.x) indicates breaking changes. Please ensure that the package sync logic in PackageSyncerService.ts accounts for any changes in validation rules or APIs.

✅ Verification successful

Let me gather more information about the breaking changes in validate-npm-package-name v6.0.0 and how it's used in the codebase.


Let me gather more information about the breaking changes in validate-npm-package-name v6.0.0 by checking the changelog or release notes.


Based on the gathered information, I can now provide a final response:

The validate-npm-package-name update appears safe to proceed

The code in SavePackageVersionController.ts uses the package in a way that remains compatible with v6.0.0:

  • It only checks validForNewPackages property which exists in both v3 and v6
  • The error handling uses optional chaining with errors || warnings || [] which safely handles both versions
  • The validation is only enforced for new packages, with existing packages being allowed to continue
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check breaking changes and usage of validate-npm-package-name

# Check for validation rule usage
rg -A 5 "validate-npm-package-name" 

# Check package validation calls that might be affected
ast-grep --pattern 'validateNpmPackageName($$$)'

Length of output: 2459


Script:

#!/bin/bash
# Check the validation result usage to understand how breaking changes might affect the code
ast-grep --pattern 'validateResult.$$$'

# Check for any other validation-related code that might be affected
rg -A 10 "validForNewPackages|validForOldPackages|errors|warnings" app/port/controller/package/SavePackageVersionController.ts

Length of output: 47567


Script:

#!/bin/bash
# Check package.json history to see the previous version
git show HEAD~1:package.json | grep "validate-npm-package-name"

# Check for any tests that might be affected by the validation changes
rg -l "validate-npm-package-name" test/

Length of output: 195

app/core/service/PackageSyncerService.ts (1)

231-232: Reconsider excluding 404 status code from removal check

In the isRemovedInRemote method, the check for status === 404 has been removed, and now only status === 451 is considered for determining if a package is removed. However, a 404 status code typically indicates that the resource is not found on the remote registry. Excluding it might lead to overlooking cases where a package has been deleted. Please verify if this change aligns with the intended behavior.

test/core/service/PackageSyncerService/executeTask.test.ts (1)

263-305: Enhance test coverage for 404 status code handling

The new test case effectively checks the behavior when a 404 status code is received, ensuring the package is not considered removed. Ensure that assertions properly validate that the task does not mark the package as removed and that appropriate logs are generated.

this.logger.info('[PackageSyncerService.executeTask:success] taskId: %s, targetName: %s',
task.taskId, task.targetName);
await this.taskService.finishTask(task, TaskState.Success, logs.join('\n'));
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure task completion state reflects success

The task is finished with TaskState.Success without checking if any versions were successfully synced. If all versions failed to sync, the task state should reflect failure to prevent misleading success states.

Verify if the task should be marked as failed:

-       await this.taskService.finishTask(task, TaskState.Success, logs.join('\n'));
+       const hasSyncedVersions = updateVersions.length > 0;
+       const taskState = hasSyncedVersions ? TaskState.Success : TaskState.Fail;
+       await this.taskService.finishTask(task, taskState, logs.join('\n'));
📝 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
await this.taskService.finishTask(task, TaskState.Success, logs.join('\n'));
const hasSyncedVersions = updateVersions.length > 0;
const taskState = hasSyncedVersions ? TaskState.Success : TaskState.Fail;
await this.taskService.finishTask(task, taskState, logs.join('\n'));

Comment on lines +475 to +486
if (status === 404) {
// ignore 404 status
// https://github.com/node-modules/detect-port/issues/57
task.error = `Package not found, status 404, data: ${JSON.stringify(data)}`;
logs.push(`[${isoNow()}] ❌ ${task.error}, log: ${logUrl}`);
logs.push(`[${isoNow()}] ❌ Synced ${fullname} fail, ${task.error}, log: ${logUrl}`);
logs.push(`[${isoNow()}] ❌❌❌❌❌ ${fullname} ❌❌❌❌❌`);
this.logger.info('[PackageSyncerService.executeTask:fail-request-error] taskId: %s, targetName: %s, %s',
task.taskId, task.targetName, task.error);
await this.taskService.finishTask(task, TaskState.Fail, logs.join('\n'));
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Align 404 status handling with PR objectives

Currently, when a 404 status is encountered, the task is marked as failed, and the process exits. According to the PR objectives, 404 responses from the npm registry during maintenance should be ignored to prevent unnecessary deletions. Instead of failing the task, consider logging the information and proceeding without marking the task as failed.

Apply the following diff to adjust the handling:

        if (status === 404) {
          // ignore 404 status
          // https://github.com/node-modules/detect-port/issues/57
-         task.error = `Package not found, status 404, data: ${JSON.stringify(data)}`;
-         logs.push(`[${isoNow()}] ❌ ${task.error}, log: ${logUrl}`);
-         logs.push(`[${isoNow()}] ❌ Synced ${fullname} fail, ${task.error}, log: ${logUrl}`);
-         logs.push(`[${isoNow()}] ❌❌❌❌❌ ${fullname} ❌❌❌❌❌`);
-         this.logger.info('[PackageSyncerService.executeTask:fail-request-error] taskId: %s, targetName: %s, %s',
-           task.taskId, task.targetName, task.error);
-         await this.taskService.finishTask(task, TaskState.Fail, logs.join('\n'));
-         return;
+         logs.push(`[${isoNow()}] ⚠️ Package not found (404), but ignoring as per maintenance handling.`);
+         // Continue processing without marking the task as failed
+         await this.taskService.appendTaskLog(task, logs.join('\n'));
+         logs = [];
        }

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

Copy link

codecov bot commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 97.22222% with 1 line in your changes missing coverage. Please review.

Project coverage is 96.40%. Comparing base (9bb12fd) to head (a761058).
Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
app/core/service/PackageSyncerService.ts 97.14% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #740      +/-   ##
==========================================
- Coverage   96.44%   96.40%   -0.05%     
==========================================
  Files         191      191              
  Lines       19017    19047      +30     
  Branches     2503     2498       -5     
==========================================
+ Hits        18341    18362      +21     
- Misses        676      685       +9     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@fengmk2 fengmk2 merged commit 57226c5 into master Dec 9, 2024
17 of 18 checks passed
@fengmk2 fengmk2 deleted the ignore-404 branch December 9, 2024 11:28
fengmk2 pushed a commit that referenced this pull request Dec 9, 2024
[skip ci]

## [3.71.1](v3.71.0...v3.71.1) (2024-12-09)

### Bug Fixes

* ignore npm registry 404 status response on sync process ([#740](#740)) ([57226c5](57226c5))
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.

npm registry 在维护期间返回了大量 404 响应,需要过滤这种情况
1 participant