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: should not throw when fetch a Request with post #563

Merged
merged 2 commits into from
Dec 11, 2024

Conversation

MadCcc
Copy link
Contributor

@MadCcc MadCcc commented Dec 11, 2024

现象

使用 post method fetch 一个 Request 对象时会出现 Cannot construct a Request with a Request object that has already been used. 错误。

原因

Request 的 constructor 会把入参的 request.body.stream.locked 变为 true,urllib 的 fetch 中已经使用参数 input new 了一个 Request,再调用 undici fetch 时参数还是 input,就会报错。

Summary by CodeRabbit

  • New Features

    • Updated the fetch method to utilize a Request object for improved request handling.
    • Added a new test case to verify POST request functionality using the Request class.
  • Chores

    • Updated .gitignore to exclude the .idea/ directory.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request include the addition of the .idea/ directory to the .gitignore file, ensuring that JetBrains IDE settings are ignored by Git. Additionally, the fetch method in the FetchFactory class within src/fetch.ts has been modified to utilize a Request object instead of raw RequestInfo, enhancing type safety. A new test case has been added to fetch.test.ts to verify POST request functionality using the Request class from the undici library, while existing tests remain unchanged.

Changes

File Change Summary
.gitignore Added entry for .idea/ to ignore JetBrains IDE settings.
src/fetch.ts Modified fetch method to use a Request object instead of raw RequestInfo.
test/fetch.test.ts Added import for Request from undici and a new test case for verifying POST request handling.

Possibly related PRs

  • feat: exports undici #554: The changes in this PR also modify the fetch method in src/fetch.ts, focusing on error handling and diagnostics, which is relevant to the changes made in the main PR regarding the fetch method.
  • fix: fix socket info if fetch failed #556: This PR enhances the fetch method in src/fetch.ts with improved error handling and response processing, directly relating to the modifications made in the main PR concerning the fetch method's internal logic.

Suggested reviewers

  • fengmk2

🐰 In the code, I hop and play,
Ignoring .idea/ every day.
With Request now in hand,
Fetching data is so grand!
New tests to make sure it’s right,
Code's a garden, what a sight! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1019228 and f113c89.

📒 Files selected for processing (1)
  • src/fetch.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/fetch.ts

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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 (1)
test/fetch.test.ts (1)

114-122: Consider enhancing the test coverage

While the test verifies that the error is not thrown, it could be improved to ensure the POST request works correctly.

Consider expanding the test to verify:

  1. The request body is sent correctly
  2. The server receives the POST data
  3. The response is processed correctly

Example enhancement:

 it('fetch request with post should work', async () => {
-  await assert.doesNotReject(async () => {
-    const request = new Request(_url, {
-      method: 'POST',
-      body: 'test-body',
-    });
-    await fetch(request);
-  }, /Cannot construct a Request with a Request object that has already been used/);
+  const request = new Request(_url, {
+    method: 'POST',
+    body: 'test-body',
+  });
+  const response = await fetch(request);
+  assert(response.ok);
+  const responseBody = await response.text();
+  assert.equal(responseBody, 'test-body'); // Assuming echo server
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bf2b5b1 and 1019228.

📒 Files selected for processing (3)
  • .gitignore (1 hunks)
  • src/fetch.ts (1 hunks)
  • test/fetch.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🔇 Additional comments (2)
test/fetch.test.ts (1)

10-10: LGTM: Import added for Request class

The import of Request from 'undici' is correctly placed with other imports.

src/fetch.ts (1)

221-221: LGTM: Fix prevents Request reuse error

The change correctly passes the Request object directly to UndiciFetch instead of creating a new Request object, which resolves the "already used" error for POST requests.

Let's verify there are no other places in the codebase where Request objects might be recreated:

✅ Verification successful

Request object creation is safe in current usage

The codebase shows only two instances of Request object creation:

  1. In test code (test/fetch.test.ts) which is expected and safe as it's creating test fixtures
  2. In src/fetch.ts line 136, which is in a different code path than the fix we're reviewing (line 221)

The current implementation correctly prevents the "already used" error by directly passing the Request object to UndiciFetch at line 221, while the other Request creation at line 136 serves a different purpose in the request initialization flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential Request object creation patterns
ast-grep --pattern 'new Request($_, $_)'

Length of output: 300


Script:

#!/bin/bash
# Let's check the context around these Request creations to understand their usage
rg -B 3 -A 3 "new Request\(" test/fetch.test.ts src/fetch.ts

Length of output: 862

Copy link

pkg-pr-new bot commented Dec 11, 2024

Open in Stackblitz

npm i https://pkg.pr.new/node-modules/urllib@563

commit: f113c89

src/fetch.ts Outdated
@@ -218,7 +218,7 @@ export class FetchFactory {
} as any as RawResponseWithMeta;
try {
await FetchFactory.#opaqueLocalStorage.run(internalOpaque, async () => {
res = await UndiciFetch(input, init);
res = await UndiciFetch(request, init);
Copy link
Member

Choose a reason for hiding this comment

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

init 还需要吗?init 已经传到 request 里了。

Copy link
Contributor Author

Choose a reason for hiding this comment

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

确实应该不用了,我改改

Copy link
Member

Choose a reason for hiding this comment

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

修复了提交一下,然后就可以合并了。

@fengmk2
Copy link
Member

fengmk2 commented Dec 11, 2024

node v16 的报错可以不管,这个我会修复

@fengmk2 fengmk2 added the bug Something isn't working label Dec 11, 2024
Copy link
Member

@killagu killagu left a comment

Choose a reason for hiding this comment

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

LGTM

@killagu killagu enabled auto-merge (squash) December 11, 2024 13:52
@killagu killagu disabled auto-merge December 11, 2024 13:52
@killagu killagu merged commit 6f9f353 into node-modules:master Dec 11, 2024
21 of 24 checks passed
fengmk2 pushed a commit that referenced this pull request Dec 11, 2024
[skip ci]

## [4.6.7](v4.6.6...v4.6.7) (2024-12-11)

### Bug Fixes

* should not throw when fetch a Request with post ([#563](#563)) ([6f9f353](6f9f353))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants