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

feat(node-fetch): improve file access #2009

Merged
merged 4 commits into from
Feb 13, 2025
Merged

feat(node-fetch): improve file access #2009

merged 4 commits into from
Feb 13, 2025

Conversation

ardatan
Copy link
Owner

@ardatan ardatan commented Jan 24, 2025

When fetch('file:///...') is used to read files;

  • 404 is returned if the file is missing
  • 403 is returned if the file is not accessible

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling for local file fetching: requests for missing files now return a 404 status, while those with restricted access return a 403 status.
  • Tests
    • Introduced a new test suite for the file protocol, verifying successful file reads, handling of missing files, and access restrictions.

Copy link
Contributor

github-actions bot commented Jan 24, 2025

🚀 Snapshot Release (alpha)

The latest changes of this PR are available as alpha on npm (based on the declared changesets):

Package Version Info
@whatwg-node/node-fetch 0.7.8-alpha-20250213114221-41f15f5b3e3d5a93f45b2475a299e0ca22f9f791 npm ↗︎ unpkg ↗︎

Copy link
Contributor

github-actions bot commented Jan 24, 2025

@benchmarks/server results (undici)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 193908      ✗ 0    
     data_received..................: 20 MB   650 kB/s
     data_sent......................: 7.8 MB  259 kB/s
     http_req_blocked...............: avg=1.42µs   min=902ns    med=1.21µs   max=198.98µs p(90)=1.93µs   p(95)=2.11µs  
     http_req_connecting............: avg=1ns      min=0s       med=0s       max=140.38µs p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=245.46µs min=186.61µs med=232.3µs  max=29.68ms  p(90)=262.15µs p(95)=274.65µs
       { expected_response:true }...: avg=245.46µs min=186.61µs med=232.3µs  max=29.68ms  p(90)=262.15µs p(95)=274.65µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 96954
     http_req_receiving.............: avg=25.62µs  min=13.65µs  med=23.42µs  max=2.44ms   p(90)=31.36µs  p(95)=34.76µs 
     http_req_sending...............: avg=6.49µs   min=4.11µs   med=5.75µs   max=255.48µs p(90)=8.25µs   p(95)=9.05µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=213.34µs min=159.88µs med=200.42µs max=29.58ms  p(90)=226.88µs p(95)=237.6µs 
     http_reqs......................: 96954   3231.700782/s
     iteration_duration.............: avg=304.84µs min=231.03µs med=290.99µs max=29.8ms   p(90)=324.33µs p(95)=338.97µs
     iterations.....................: 96954   3231.700782/s
     vus............................: 1       min=1         max=1  
     vus_max........................: 1       min=1         max=1  

Copy link
Contributor

github-actions bot commented Jan 24, 2025

@benchmarks/server results (ponyfill)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 299504      ✗ 0     
     data_received..................: 30 MB   983 kB/s
     data_sent......................: 12 MB   399 kB/s
     http_req_blocked...............: avg=1.38µs   min=881ns    med=1.17µs   max=1.73ms   p(90)=1.83µs   p(95)=1.99µs  
     http_req_connecting............: avg=11ns     min=0s       med=0s       max=1.67ms   p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=138.49µs min=93.24µs  med=134.09µs max=5.81ms   p(90)=156.3µs  p(95)=163.59µs
       { expected_response:true }...: avg=138.49µs min=93.24µs  med=134.09µs max=5.81ms   p(90)=156.3µs  p(95)=163.59µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 149752
     http_req_receiving.............: avg=24.34µs  min=12.39µs  med=22.8µs   max=2.59ms   p(90)=30.05µs  p(95)=32.84µs 
     http_req_sending...............: avg=6.21µs   min=4.05µs   med=5.36µs   max=371.48µs p(90)=8.02µs   p(95)=8.64µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=107.93µs min=66.99µs  med=103.22µs max=5.67ms   p(90)=122.38µs p(95)=128.29µs
     http_reqs......................: 149752  4991.522155/s
     iteration_duration.............: avg=195.95µs min=141.25µs med=190.82µs max=6.15ms   p(90)=216.5µs  p(95)=225.61µs
     iterations.....................: 149752  4991.522155/s
     vus............................: 1       min=1         max=1   
     vus_max........................: 1       min=1         max=1   

Copy link
Contributor

github-actions bot commented Jan 24, 2025

@benchmarks/node-fetch results (consumeBody)

   ✓ active_handles.................: avg=140.784245 min=13      med=141     max=175     p(90)=159     p(95)=163    
     data_received..................: 19 MB  624 kB/s
     data_sent......................: 12 MB  400 kB/s
     http_req_blocked...............: avg=4.38µs     min=612ns   med=1.41µs  max=9.84ms  p(90)=2.16µs  p(95)=2.56µs 
     http_req_connecting............: avg=2.52µs     min=0s      med=0s      max=9.79ms  p(90)=0s      p(95)=0s     
     http_req_duration..............: avg=24.42ms    min=3.66ms  med=23.72ms max=1.25s   p(90)=30.39ms p(95)=32.46ms
       { expected_response:true }...: avg=24.42ms    min=3.66ms  med=23.72ms max=1.25s   p(90)=30.39ms p(95)=32.46ms
     http_req_failed................: 0.00%  ✓ 0           ✗ 122403
     http_req_receiving.............: avg=38.38µs    min=11.13µs med=27.67µs max=23.07ms p(90)=41.79µs p(95)=49.17µs
     http_req_sending...............: avg=14.68µs    min=3.85µs  med=7.45µs  max=14.77ms p(90)=11.1µs  p(95)=15.57µs
     http_req_tls_handshaking.......: avg=0s         min=0s      med=0s      max=0s      p(90)=0s      p(95)=0s     
     http_req_waiting...............: avg=24.36ms    min=3.62ms  med=23.68ms max=1.25s   p(90)=30.35ms p(95)=32.38ms
     http_reqs......................: 122403 4079.569136/s
     iteration_duration.............: avg=48.96ms    min=11.53ms med=47.16ms max=1.28s   p(90)=53.55ms p(95)=58.48ms
     iterations.....................: 61185  2039.23464/s
     vus............................: 12     min=12        max=100 
     vus_max........................: 100    min=100       max=100 

Copy link
Contributor

github-actions bot commented Jan 24, 2025

@benchmarks/node-fetch results (noConsumeBody)

   ✓ active_handles.................: avg=140.106637 min=12      med=141     max=199     p(90)=160     p(95)=166    
     data_received..................: 21 MB  701 kB/s
     data_sent......................: 14 MB  454 kB/s
     http_req_blocked...............: avg=2.66µs     min=641ns   med=1.35µs  max=17.96ms p(90)=2.05µs  p(95)=2.33µs 
     http_req_connecting............: avg=667ns      min=0s      med=0s      max=4.42ms  p(90)=0s      p(95)=0s     
     http_req_duration..............: avg=21.74ms    min=4.17ms  med=21.1ms  max=1.17s   p(90)=27.49ms p(95)=29.32ms
       { expected_response:true }...: avg=21.74ms    min=4.17ms  med=21.1ms  max=1.17s   p(90)=27.49ms p(95)=29.32ms
     http_req_failed................: 0.00%  ✓ 0           ✗ 137477
     http_req_receiving.............: avg=33.42µs    min=9.55µs  med=23.13µs max=17.68ms p(90)=37.99µs p(95)=44.94µs
     http_req_sending...............: avg=12.1µs     min=3.49µs  med=6.4µs   max=12.12ms p(90)=9.89µs  p(95)=13.77µs
     http_req_tls_handshaking.......: avg=0s         min=0s      med=0s      max=0s      p(90)=0s      p(95)=0s     
     http_req_waiting...............: avg=21.7ms     min=4.12ms  med=21.06ms max=1.17s   p(90)=27.45ms p(95)=29.26ms
     http_reqs......................: 137477 4581.863265/s
     iteration_duration.............: avg=43.6ms     min=13.53ms med=42.11ms max=1.19s   p(90)=47.36ms p(95)=52.66ms
     iterations.....................: 68719  2290.281732/s
     vus............................: 81     min=81        max=100 
     vus_max........................: 100    min=100       max=100 

Copy link
Contributor

github-actions bot commented Jan 24, 2025

@benchmarks/server results (native)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 211044      ✗ 0     
     data_received..................: 21 MB   707 kB/s
     data_sent......................: 8.4 MB  281 kB/s
     http_req_blocked...............: avg=1.35µs   min=852ns    med=1.15µs   max=189.27µs p(90)=1.85µs   p(95)=2.01µs  
     http_req_connecting............: avg=1ns      min=0s       med=0s       max=124.85µs p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=222.35µs min=166.89µs med=212.22µs max=7.67ms   p(90)=239.38µs p(95)=249.43µs
       { expected_response:true }...: avg=222.35µs min=166.89µs med=212.22µs max=7.67ms   p(90)=239.38µs p(95)=249.43µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 105522
     http_req_receiving.............: avg=25.13µs  min=13.14µs  med=23.52µs  max=2.56ms   p(90)=30.33µs  p(95)=33.03µs 
     http_req_sending...............: avg=6.2µs    min=3.97µs   med=5.34µs   max=1.09ms   p(90)=8.05µs   p(95)=8.66µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=191µs    min=145.22µs med=180.87µs max=6.97ms   p(90)=205.25µs p(95)=214.64µs
     http_reqs......................: 105522  3517.239452/s
     iteration_duration.............: avg=279.83µs min=208.41µs med=269.03µs max=8.05ms   p(90)=299.38µs p(95)=311.71µs
     iterations.....................: 105522  3517.239452/s
     vus............................: 1       min=1         max=1   
     vus_max........................: 1       min=1         max=1   

@ardatan
Copy link
Owner Author

ardatan commented Jan 29, 2025

What do you think @coderabbitai

Copy link

coderabbitai bot commented Jan 29, 2025

@ardatan The changes look great! I particularly like:

  1. Proper error handling with specific status codes (404 for missing files, 403 for access denied)
  2. Addition of useful response headers (content-type, last-modified)
  3. Making the file handling properly async
  4. Comprehensive test coverage for all scenarios

The implementation is clean and achieves the PR objectives perfectly. I recommend merging these changes.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Fetch PR details and diff
gh pr view 2009 --json files
gh pr diff 2009

# Search for relevant test files
fd -e test.ts -e spec.ts node-fetch

Length of output: 4236

✅ Actions performed

Comments resolved.

@ardatan ardatan marked this pull request as ready for review February 11, 2025 14:12
Copy link

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request updates the @whatwg-node/node-fetch package to improve error handling when accessing local files via the file:/// protocol. The changes convert the getResponseForFile function to an asynchronous method, allowing it to await file system operations. The function now returns a 404 status for missing files and a 403 status for files that cannot be accessed. Additionally, new tests have been added to verify these behaviors under different scenarios.

Changes

File(s) Change Summary
.changeset/tough-moles-arrive.md Documentation update detailing the patch for improved error responses (404 for missing files and 403 for restricted access) in local file fetching.
packages/node-fetch/src/fetch.ts Converted getResponseForFile to an asynchronous function. Enhanced error handling by using fsPromises.access and fsPromises.stat, removed fakePromise logic.
packages/node-fetch/tests/non-http-fetch.spec.ts Introduced a new test suite for the file protocol. Added tests to verify 200 (successful read), 404 (non-existent file), and 403 (restricted file access) responses.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant F as getResponseForFile
    participant A as fsPromises.access
    participant S as fsPromises.stat
    participant R as Response

    C->>F: Request file URL
    F->>A: Check file access
    A-->>F: Access result (success/error)
    alt File Not Found
        F-->>C: Return 404 Response ("Not Found")
    else Permission Denied
        F-->>C: Return 403 Response ("Forbidden")
    else File Accessible
        F->>S: Retrieve file stats
        S-->>F: Return file statistics
        F->>R: Create stream and 200 Response with headers
        R-->>C: Return 200 Response ("OK")
    end
Loading

Poem

I'm a rabbit with a joyful hop,
Code paths now clear, no bug can stop.
With 404s and 403s on guard at the door,
Async trails pave the way to explore.
Happy hops in every line I pen,
Celebrating changes again and again!

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/node-fetch/tests/non-http-fetch.spec.ts

Oops! Something went wrong! :(

ESLint: 9.18.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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

🧹 Nitpick comments (2)
packages/node-fetch/tests/non-http-fetch.spec.ts (1)

24-34: Consider improving cleanup in the forbidden file test.

While the test correctly verifies the 403 status code, the cleanup could be more robust.

Consider wrapping the file operations in a try-catch:

 const tmpDir = tmpdir();
 const path = join(tmpDir, 'forbidden.json');
-writeFileSync(path, '{ "test": 1 }', { mode: 0o000 });
-try {
-  const response = await fetchPonyfill(pathToFileURL(path));
-  expect(response.status).toBe(403);
-} finally {
-  unlinkSync(path);
-}
+try {
+  writeFileSync(path, '{ "test": 1 }', { mode: 0o000 });
+  try {
+    const response = await fetchPonyfill(pathToFileURL(path));
+    expect(response.status).toBe(403);
+  } finally {
+    try {
+      unlinkSync(path);
+    } catch (err) {
+      // Ignore cleanup errors
+    }
+  }
+} catch (err) {
+  throw new Error(`Failed to set up test: ${err.message}`);
+}
packages/node-fetch/src/fetch.ts (1)

13-43: Consider improving content-type detection.

While the error handling is excellent, the content-type header could be more accurate.

Consider using a content-type detection library:

+import mime from 'mime-types';
 async function getResponseForFile(url: string) {
   const path = fileURLToPath(url);
   try {
     await fsPromises.access(path, fsPromises.constants.R_OK);
     const stats = await fsPromises.stat(path, {
       bigint: true,
     });
     const readable = createReadStream(path);
     return new PonyfillResponse(readable, {
       status: 200,
       statusText: 'OK',
       headers: {
-        'content-type': 'application/octet-stream',
+        'content-type': mime.lookup(path) || 'application/octet-stream',
         'last-modified': stats.mtime.toUTCString(),
       },
     });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 337e605 and f223f8e.

📒 Files selected for processing (3)
  • .changeset/tough-moles-arrive.md (1 hunks)
  • packages/node-fetch/src/fetch.ts (3 hunks)
  • packages/node-fetch/tests/non-http-fetch.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: unit / deno
  • GitHub Check: unit / bun
  • GitHub Check: esm
  • GitHub Check: unit / node 23
  • GitHub Check: alpha / snapshot
  • GitHub Check: unit / node 22
  • GitHub Check: unit / node 20
  • GitHub Check: server (undici)
  • GitHub Check: unit / node 18
  • GitHub Check: server (ponyfill)
  • GitHub Check: e2e / cloudflare-modules
  • GitHub Check: type check
  • GitHub Check: node-fetch (consumeBody)
  • GitHub Check: e2e / cloudflare-workers
  • GitHub Check: server (native)
  • GitHub Check: e2e / azure-function
  • GitHub Check: lint
  • GitHub Check: node-fetch (noConsumeBody)
  • GitHub Check: e2e / aws-lambda
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/node-fetch/tests/non-http-fetch.spec.ts (2)

9-17: LGTM! Well-structured test for successful file read.

The test case properly verifies both the status code and the response body.


18-23: LGTM! Good test for missing file scenario.

The test case correctly verifies the 404 status code for non-existent files.

packages/node-fetch/src/fetch.ts (1)

100-102: LGTM! Proper async handling.

The removal of fakePromise and direct return of the async response is correct.

.changeset/tough-moles-arrive.md (1)

1-7: LGTM! Clear and concise changeset.

The changeset accurately documents the changes and their impact on the package.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f223f8e and 41f15f5.

📒 Files selected for processing (1)
  • packages/node-fetch/tests/non-http-fetch.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: unit / deno
  • GitHub Check: unit / node 23
  • GitHub Check: unit / node 22
  • GitHub Check: unit / bun
  • GitHub Check: unit / node 20
  • GitHub Check: alpha / snapshot
  • GitHub Check: unit / node 18
  • GitHub Check: server (undici)
  • GitHub Check: e2e / cloudflare-modules
  • GitHub Check: server (ponyfill)
  • GitHub Check: e2e / cloudflare-workers
  • GitHub Check: node-fetch (consumeBody)
  • GitHub Check: e2e / azure-function
  • GitHub Check: server (native)
  • GitHub Check: e2e / aws-lambda
  • GitHub Check: lint
  • GitHub Check: node-fetch (noConsumeBody)
🔇 Additional comments (1)
packages/node-fetch/tests/non-http-fetch.spec.ts (1)

8-21: LGTM! Well-structured test cases for successful read and missing file scenarios.

The test cases effectively verify:

  • Successful file read with 200 status
  • Missing file with 404 status

@ardatan ardatan merged commit 5b5ae5f into master Feb 13, 2025
25 checks passed
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