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 assetserver_webview.go request cancelation on MacOS #3632

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

kopotp
Copy link

@kopotp kopotp commented Jul 24, 2024

Description

I am using custom Middleware with go-chi router for IPC between ui & go (need this to pass large amounts of data), and sometimes wish to cancel the request from UI before it is completed. It works for remote dev server (opening from browser via http://localhost:34115/ ) - canceling fetch request from javascript will cancel the request.Context. But this does not work from Webview - http.Request is created with empty Context.

This is my fix / proposal for MacOS
Current solution only uses request.URL() for RequestID, thinking about replacing it by extending type Request interface with something like RequestID() method that will return a pointer to WKURLSchemeTask

@leaanthony what do you think about this approach ?

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration using wails doctor.

  • macOS
  • Windows
  • Linux

Test Configuration

# Wails
Version | v2.8.2

# System
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
| OS           | MacOS                                                                                                                       |
| Version      | 14.5                                                                                                                        |
| ID           | 23F79                                                                                                                       |
| Go Version   | go1.22.2                                                                                                                    |
| Platform     | darwin                                                                                                                      |
| Architecture | arm64                                                                                                                       |
| CPU          | Apple M1 Pro                                                                                                                |
| GPU          | Chipset Model: Apple M1 Pro Type: GPU Bus: Built-In Total Number of Cores: 16 Vendor: Apple (0x106b) Metal Support: Metal 3 |
| Memory       | 16GB                                                                                                                        |
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

# Dependencies
┌──────────────────────────────────────────────────────────────────────┐
| Dependency                | Package Name | Status    | Version       |
| Xcode command line tools  | N/A          | Installed | 2408          |
| Nodejs                    | N/A          | Installed | 20.13.1       |
| npm                       | N/A          | Installed | 10.5.2        |
| *Xcode                    | N/A          | Installed | 15.4 (15F31d) |
| *upx                      | N/A          | Available |               |
| *nsis                     | N/A          | Available |               |
└────────────────────── * - Optional Dependency ───────────────────────┘

# Diagnosis
Optional package(s) installation details: 
  - upx : Available at https://upx.github.io/
  - nsis : More info at https://wails.io/docs/guides/windows-installer/

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Enhanced request handling with the introduction of a mechanism to stop ongoing URL requests, improving resource management.
    • Added a cancellation functionality to manage long-running HTTP requests effectively.
  • Improvements

    • Robust handling of URL scheme tasks, allowing for better cleanup and processing when stopping tasks.
    • Integrated cancellation context for HTTP requests, enhancing the responsiveness of the application.

Copy link
Contributor

coderabbitai bot commented Jul 24, 2024

Walkthrough

The recent updates enhance the handling of URL requests within the application. Key changes include the introduction of a new function to manage the stopping of URL requests, improved resource management through cancellation mechanisms, and better control flow in processing tasks related to web views. These updates collectively aim to streamline request handling, making the system more robust and responsive.

Changes

Files Change Summary
v2/internal/frontend/desktop/darwin/WailsContext.m, v2/internal/frontend/desktop/darwin/frontend.go, v2/internal/frontend/desktop/darwin/message.h Introduced a new function processURLRequestStop to manage the stopping of URL requests, enhancing control flow and request handling capabilities.
v2/pkg/assetserver/assetserver_webview.go Added a cancellation mechanism for HTTP requests, including a new variable requestCancelFuncsMap and the function CancelRequest, improving resource management.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WebView
    participant AssetServer

    User->>WebView: Initiate URL Request
    WebView->>AssetServer: Create Request
    AssetServer->>AssetServer: Store Cancellation Function
    User->>WebView: Stop URL Request
    WebView->>AssetServer: processURLRequestStop
    AssetServer->>AssetServer: Cancel Request
    AssetServer-->>User: Request Stopped
Loading

Poem

🐇 In a world of bytes and streams,
Requests now dance in clever dreams,
A pause, a stop, all thanks to care,
Our web requests flow light as air!
So hop along, let changes cheer,
For code is magic, bright and clear! ✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

sonarcloud bot commented Jul 24, 2024

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7a40cc5 and 5ffcc30.

Files selected for processing (4)
  • v2/internal/frontend/desktop/darwin/WailsContext.m (1 hunks)
  • v2/internal/frontend/desktop/darwin/frontend.go (1 hunks)
  • v2/internal/frontend/desktop/darwin/message.h (1 hunks)
  • v2/pkg/assetserver/assetserver_webview.go (4 hunks)
Additional comments not posted (6)
v2/internal/frontend/desktop/darwin/message.h (1)

19-19: LGTM! The new function declaration is consistent with the existing code style.

The function declaration processURLRequestStop is consistent with the existing code style and follows the same pattern as other function declarations in the file.

v2/pkg/assetserver/assetserver_webview.go (3)

24-24: LGTM! The new variable declaration is consistent with the existing code style.

The variable requestCancelFuncsMap is introduced to store cancellation functions associated with request IDs. It uses sync.Map for thread-safe storage.


58-63: LGTM! The new function implementation is correct and follows the existing code style.

The function CancelRequest retrieves and invokes the cancellation function for a given request ID. It ensures that the cancellation function is invoked and the entry is removed from the map.


119-127: LGTM! The modifications in the method are correct and follow the existing code style.

The method processWebViewRequestInternal is modified to create a context with a cancellation function and store it in requestCancelFuncsMap. The modifications ensure that the cancellation function is stored and invoked when needed.

v2/internal/frontend/desktop/darwin/frontend.go (1)

466-475: LGTM! The new function implementation is correct and follows the existing code style.

The function processURLRequestStop creates a new request, retrieves the request ID, and calls CancelRequest. The implementation is correct and follows the existing code style.

v2/internal/frontend/desktop/darwin/WailsContext.m (1)

466-466: LGTM! Ensure processURLRequestStop is implemented correctly.

The addition of processURLRequestStop(self, urlSchemeTask); appears to handle necessary cleanup or processing when stopping a URL scheme task. Ensure that processURLRequestStop is implemented correctly to avoid any potential issues.

Verification successful

Verified: The implementation of processURLRequestStop is correct.

The function processURLRequestStop is implemented in v2/internal/frontend/desktop/darwin/frontend.go and handles the necessary cleanup by canceling the request using assetserver.CancelRequest(requestID).

  • v2/internal/frontend/desktop/darwin/frontend.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of `processURLRequestStop`.

# Test: Search for the implementation of `processURLRequestStop`. Expect: The function should be implemented and handle necessary cleanup or processing.
rg --type objc -A 5 $'void processURLRequestStop'

Length of output: 535


Script:

#!/bin/bash
# Description: Locate the definition of `processURLRequestStop`.

# Test: Search for the definition of `processURLRequestStop`. Expect: The function should be defined and handle necessary cleanup or processing.
rg --type objc -A 10 $'void processURLRequestStop(void *self, void *urlSchemeTask)'

Length of output: 84


Script:

#!/bin/bash
# Description: Locate the definition of `processURLRequestStop`.

# Test: Search for the definition of `processURLRequestStop`. Expect: The function should be defined and handle necessary cleanup or processing.
rg --type objc -A 10 'processURLRequestStop'

Length of output: 1752


Script:

#!/bin/bash
# Description: Locate the definition of `processURLRequestStop`.

# Test: Search for the definition of `processURLRequestStop`. Expect: The function should be defined and handle necessary cleanup or processing.
rg -A 10 'processURLRequestStop'

Length of output: 2611

@leaanthony
Copy link
Member

leaanthony commented Jul 29, 2024

Thanks for looking into this. I'm wondering whether it would be better to simply pass the URL as a string from obj-c back to Go doing something like:

- (void)webView:(nonnull WKWebView *)webView stopURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask {
    const char *cURL = [urlSchemeTask.request.URL.absoluteString UTF8String]
    processURLRequestStop(self, cURL);
    free(cURL);
    NSInputStream *stream = urlSchemeTask.request.HTTPBodyStream;
    if (stream) {
        NSStreamStatus status = stream.streamStatus;
        if (status != NSStreamStatusClosed && status != NSStreamStatusNotOpen) {
            [stream close];
        }
    }
}

Then in Go:

//export processURLRequestStop
func processURLRequestStop(_ unsafe.Pointer, requestID *C.char) {
	assetserver.CancelRequest(C.GoString(requestID))
}

@leaanthony
Copy link
Member

@kopotp - Any more thoughts on this?

1 similar comment
@leaanthony
Copy link
Member

@kopotp - Any more thoughts on this?

//export processURLRequestStop
func processURLRequestStop(_ unsafe.Pointer, wkURLSchemeTask unsafe.Pointer) {
r := webview.NewRequest(wkURLSchemeTask)
requestID, err := r.URL()
Copy link
Contributor

Choose a reason for hiding this comment

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

The requestID shouldn't just be the r.URL() , it should also contain the r.Method().

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.

3 participants