Skip to content

use proxy to download server resourece pack on any server #309

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

Open
wants to merge 3 commits into
base: next
Choose a base branch
from

Conversation

zardoy
Copy link
Owner

@zardoy zardoy commented Mar 14, 2025

User description

…t supporting cors url


PR Type

Enhancement, Bug fix


Description

  • Added a fallback proxy for resource pack downloads.

  • Improved error handling for resource pack fetch failures.

  • Updated the proxy URL to use mcraft-proxy.vercel.app.


Changes walkthrough 📝

Relevant files
Enhancement
resourcePack.ts
Add fallback proxy and improve fetch handling                       

src/resourcePack.ts

  • Added a try-catch block for fetch errors.
  • Implemented a fallback proxy URL for resource pack downloads.
  • Replaced commented-out proxy URL with a new one.
  • +8/-1     

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • Bug Fixes
      • Enhanced the resource pack download process with a fallback mechanism to improve reliability during network issues.

    Copy link

    codesandbox bot commented Mar 14, 2025

    Review or Edit in CodeSandbox

    Open the branch in Web EditorVS CodeInsiders

    Open Preview

    Copy link

    coderabbitai bot commented Mar 14, 2025

    Walkthrough

    The changes improve error resilience in the downloadAndUseResourcePack function by adding a try-catch block around the fetch operation. If the primary fetch to the given URL fails, the function falls back to using a proxy URL to download the resource pack. There are no modifications to the public or exported entities.

    Changes

    File Change Summary
    src/resourcePack.ts Wrapped the fetch call in a try-catch block and implemented a fallback mechanism using a proxy URL if the initial resource pack download fails.

    Sequence Diagram(s)

    Loading
    sequenceDiagram
        participant C as Client
        participant R as downloadAndUseResourcePack
        participant F as fetch(url)
        participant P as fetch(proxy URL)
    
        C->>R: Request resource pack
        R->>F: Attempt primary fetch
        alt Fetch Successful
            F-->>R: Return resource pack data
            R-->>C: Return data
        else Fetch Fails
            F-->>R: Error occurs
            R->>P: Attempt fetch with fallback proxy URL
            alt Fallback Successful
                P-->>R: Return resource pack data
                R-->>C: Return data
            else Fallback Fails
                P-->>R: Error occurs
                R-->>C: Propagate error or handle failure
            end
        end
    

    Poem

    I'm a bunny with a coding flair,
    Hopping through bugs with utmost care.
    I found a snag in fetch's way,
    So I built a fallback to save the day.
    With a twitch of my nose and a joyful leap,
    I'm celebrating smoother code in a cheerful beep!
    🥕🐇✨

    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.

    Scope: all 2 workspace projects
     ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies

    Tip

    ⚡🧪 Multi-step agentic review comment chat (experimental)
    • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
      - To enable this feature, set early_access to true under in the settings.
    ✨ Finishing Touches
    • 📝 Generate Docstrings

    Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

    ❤️ 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.
    • @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.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The code catches fetch errors but doesn't handle the case where the proxy fetch might also fail. Consider adding error handling for the proxy fetch to provide better user feedback.

    // response = await fetch(`https://cors-anywhere.herokuapp.com/${url.replace(/^https?:\/\//, '')}`)
    response = await fetch(`https://mcraft-proxy.vercel.app/0/${url.replace(/^https?:\/\//, '')}`)
    Undefined Variable

    The variable 'response' is declared but might be undefined if both the original fetch and proxy fetch fail, which would cause the subsequent arrayBuffer() call to throw an error.

    const resourcePackData = await response.arrayBuffer()

    Copy link

    qodo-merge-pro-for-open-source bot commented Mar 14, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Handle fallback fetch errors
    Suggestion Impact:The commit implemented error handling for the fallback proxy fetch, but with a more comprehensive approach. Instead of just wrapping the proxy fetch in a try/catch block, the commit completely restructured the resource pack download logic with proper error handling, progress reporting, and a more robust fallback mechanism.

    code diff:

    +    // Try direct URL first
    +    let response = await fetch(url).catch((err) => {
    +      console.log(`Ensure server on ${url} support CORS which is not required for regular client, but is required for the web client`)
    +      console.error(err)
    +      return null
    +    })
    +
    +    // If direct URL fails, try proxy URL
    +    if (!response) {
    +      const urlWithoutProtocol = url.replace(/^https?:\/\//, '')
    +      const proxyUrl = `https://mcraft-proxy.vercel.app/0/${urlWithoutProtocol}`
    +      console.log('Trying fallback proxy URL:', proxyUrl)
    +      response = await fetch(proxyUrl).catch((err) => {
    +        console.error('Proxy fetch also failed:', err)
    +        progressReporter.error('Failed to download resource pack: ' + err.message)
    +        return null
    +      })
    +    }

    The catch block doesn't handle potential errors from the fallback proxy fetch.
    If the fallback fetch also fails, the code will throw an unhandled exception
    since there's no error handling for it.

    src/resourcePack.ts [285-291]

     try {
       response = await fetch(url)
     } catch (err) {
       // use fallback proxy (intended to be used as last resort on prod)
       // response = await fetch(`https://cors-anywhere.herokuapp.com/${url.replace(/^https?:\/\//, '')}`)
    -  response = await fetch(`https://mcraft-proxy.vercel.app/0/${url.replace(/^https?:\/\//, '')}`)
    +  try {
    +    response = await fetch(`https://mcraft-proxy.vercel.app/0/${url.replace(/^https?:\/\//, '')}`)
    +  } catch (proxyErr) {
    +    console.error('Failed to download resource pack using both direct and proxy methods', proxyErr)
    +    throw proxyErr
    +  }
     }

    [Suggestion has been applied]

    Suggestion importance[1-10]: 9

    __

    Why: The suggestion addresses a critical error handling issue where failures in the fallback proxy fetch would result in unhandled exceptions. Adding proper error handling for the fallback mechanism significantly improves the robustness of the resource pack download functionality.

    High
    • Update

    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 (1)
    src/resourcePack.ts (1)

    284-291: Great addition of error handling with proxy fallback!

    This change improves resilience by adding a fallback mechanism when the direct fetch fails. The proxy URL allows downloading resource packs from servers that don't support CORS, which aligns well with the PR objectives.

    Consider enhancing this implementation with:

      try {
        response = await fetch(url)
    +   if (!response.ok) {
    +     throw new Error(`Failed to fetch resource pack: ${response.status} ${response.statusText}`)
    +   }
      } catch (err) {
    +   console.error('Error fetching resource pack directly:', err)
        // use fallback proxy (intended to be used as last resort on prod)
        // response = await fetch(`https://cors-anywhere.herokuapp.com/${url.replace(/^https?:\/\//, '')}`)
        response = await fetch(`https://mcraft-proxy.vercel.app/0/${url.replace(/^https?:\/\//, '')}`)
    +   if (!response.ok) {
    +     throw new Error(`Proxy fetch failed: ${response.status} ${response.statusText}`)
    +   }
      }
    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between 09cd2c3 and a7bf484.

    📒 Files selected for processing (1)
    • src/resourcePack.ts (1 hunks)

    Copy link
    Owner Author

    @zardoy zardoy left a comment

    Choose a reason for hiding this comment

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

    /deploy

    @zardoy zardoy changed the title use proxy to download server resourece pack on any server from any no… use proxy to download server resourece pack on any server Mar 14, 2025
    @zardoy
    Copy link
    Owner Author

    zardoy commented Mar 14, 2025

    /deploy

    Copy link

    Deployed to Vercel Preview: https://prismarine-zcyjuuw2n-zaro.vercel.app
    Playground
    Storybook

    // If direct URL fails, try proxy URL
    if (!response) {
    const urlWithoutProtocol = url.replace(/^https?:\/\//, '')
    const proxyUrl = `https://mcraft-proxy.vercel.app/0/${urlWithoutProtocol}`
    Copy link

    @Phoenix616 Phoenix616 Mar 14, 2025

    Choose a reason for hiding this comment

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

    Wouldn't it make more sense to use the proxy that is already used for the packets for the resource pack too? That way this centralised failure point could be prevented. Also you could prevent abuse of the proxy server as right now one can query other arbitrary files through that url (which might expose you to some legal issues too). If the webclient proxy would handle the pack proxying as well then it could cache which server resource packs actually got sent from the server and only allow proxying those.

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants