-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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(client/windows): introduce go plugin to call fetchResource
as a library
#2263
Merged
Merged
Changes from 10 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
de56679
feat(client/windows): call `fetchResource` as a library
jyyi1 9c6a234
export FetchResource from Go
jyyi1 3c607ed
add library build script to Go taskfile
jyyi1 10fa95e
include shared library in the app
jyyi1 fd3ac51
introduce slog to the library calls
jyyi1 61d56f0
Simplify the native code by introducing GoPlugin
jyyi1 bb65fbc
Use InvokeGoAPI in TypeScript
jyyi1 1387385
move logs to invokeGoApi
jyyi1 1b40ee1
pr comment and zig on Windows action
jyyi1 ba4201f
expose invoke-go-api to renderer process
jyyi1 5d8d838
Merge branch 'master' into junyi/electron-library-call
jyyi1 7db3d62
remove fetchUrl from tun2socks binary
jyyi1 6e38b62
remove log in init so it won't pollute tun2socks.exe stderr
jyyi1 89f599c
remove C header files from the final binary
jyyi1 2bf6f6c
Merge branch 'master' into junyi/electron-library-call
jyyi1 2a38297
Merge branch 'master' into junyi/electron-library-call
jyyi1 b1ae381
InternalError instead of IllegalConfig
jyyi1 cb5a5c8
`use` instead of `loader`
jyyi1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
// Copyright 2024 The Outline Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import {promisify} from 'node:util'; | ||
|
||
import koffi from 'koffi'; | ||
|
||
import {pathToBackendLibrary} from './app_paths'; | ||
|
||
let invokeGoAPIFunc: Function | undefined; | ||
|
||
export type GoApiName = 'FetchResource'; | ||
|
||
/** | ||
* Calls a Go function by invoking the `InvokeGoAPI` function in the native backend library. | ||
* | ||
* @param api The name of the Go API to invoke. | ||
* @param input The input string to pass to the API. | ||
* @returns A Promise that resolves to the output string returned by the API. | ||
* @throws An Error containing PlatformError details if the API call fails. | ||
* | ||
* @remarks | ||
* Ensure that the function signature and data structures are consistent with the C definitions | ||
* in `./client/go/outline/electron/go_plugin.go`. | ||
*/ | ||
export async function invokeGoApi( | ||
api: GoApiName, | ||
input: string | ||
): Promise<string> { | ||
if (!invokeGoAPIFunc) { | ||
const backendLib = koffi.load(pathToBackendLibrary()); | ||
|
||
// Define C strings and setup auto release | ||
const cgoString = koffi.disposable( | ||
'CGoAutoReleaseString', | ||
'str', | ||
backendLib.func('FreeCGoString', 'void', ['str']) | ||
); | ||
|
||
// Define InvokeGoAPI data structures and function | ||
const invokeGoApiResult = koffi.struct('InvokeGoAPIResult', { | ||
Output: cgoString, | ||
ErrorJson: cgoString, | ||
}); | ||
invokeGoAPIFunc = promisify( | ||
backendLib.func('InvokeGoAPI', invokeGoApiResult, ['str', 'str']).async | ||
); | ||
} | ||
|
||
console.debug('[Backend] - calling InvokeGoAPI ...'); | ||
const result = await invokeGoAPIFunc(api, input); | ||
console.debug('[Backend] - InvokeGoAPI returned', result); | ||
if (result.ErrorJson) { | ||
throw Error(result.ErrorJson); | ||
} | ||
return result.Output; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
// Copyright 2024 The Outline Authors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package main | ||
|
||
/* | ||
#include <stdlib.h> // for C.free | ||
|
||
// InvokeGoAPIResult is a struct used to pass result from Go to TypeScript boundary. | ||
typedef struct InvokeGoAPIResult_t | ||
{ | ||
// A string representing the result of the Go function call. | ||
// This may be a raw string or a JSON string depending on the API call. | ||
const char *Output; | ||
|
||
// A string containing a JSON representation of any error that occurred during the | ||
// Go function call, or NULL if no error occurred. | ||
// This error can be parsed by the PlatformError in TypeScript. | ||
const char *ErrorJson; | ||
} InvokeGoAPIResult; | ||
*/ | ||
import "C" | ||
import ( | ||
"fmt" | ||
"log/slog" | ||
"os" | ||
"unsafe" | ||
|
||
"github.com/Jigsaw-Code/outline-apps/client/go/outline" | ||
"github.com/Jigsaw-Code/outline-apps/client/go/outline/platerrors" | ||
) | ||
|
||
// API name constants | ||
const ( | ||
// FetchResourceAPI fetches a resource located at a given URL. | ||
// | ||
// - Input: the URL string of the resource to fetch | ||
// - Output: the content in raw string of the fetched resource | ||
FetchResourceAPI = "FetchResource" | ||
) | ||
|
||
// InvokeGoAPI is the unified entry point for TypeScript to invoke various Go functions. | ||
// | ||
// The input and output are all defined as string, but they may represent either a raw string, | ||
// or a JSON string depending on the API call. | ||
// | ||
// Check the API name constants comment for more details about the input and output format. | ||
// | ||
//export InvokeGoAPI | ||
func InvokeGoAPI(api *C.char, input *C.char) C.InvokeGoAPIResult { | ||
apiName := C.GoString(api) | ||
switch apiName { | ||
|
||
case FetchResourceAPI: | ||
res := outline.FetchResource(C.GoString(input)) | ||
return C.InvokeGoAPIResult{ | ||
Output: newCGoString(res.Content), | ||
ErrorJson: marshalCGoErrorJson(platerrors.ToPlatformError(res.Error)), | ||
} | ||
|
||
default: | ||
err := &platerrors.PlatformError{ | ||
Code: platerrors.IllegalConfig, | ||
Message: fmt.Sprintf("unsupported Go API: %s", apiName), | ||
} | ||
return C.InvokeGoAPIResult{ErrorJson: marshalCGoErrorJson(err)} | ||
} | ||
} | ||
|
||
// newCGoString allocates memory for a C string based on the given Go string. | ||
// It should be paired with [FreeCGoString] to avoid memory leaks. | ||
func newCGoString(s string) *C.char { | ||
if s == "" { | ||
return nil | ||
} | ||
res := C.CString(s) | ||
slog.Debug("malloc CGoString", "addr", res) | ||
return res | ||
} | ||
|
||
// FreeCGoString releases the memory allocated by newCGoString. | ||
// It also accepts null. | ||
// | ||
//export FreeCGoString | ||
func FreeCGoString(s *C.char) { | ||
if s != nil { | ||
slog.Debug("free CGoString", "addr", s) | ||
C.free(unsafe.Pointer(s)) | ||
} | ||
} | ||
|
||
// marshalCGoErrorJson marshals a PlatformError to a C style JSON string. | ||
// It always succeeds with a non-empty string if e is not nil. | ||
func marshalCGoErrorJson(e *platerrors.PlatformError) *C.char { | ||
if e == nil { | ||
return nil | ||
} | ||
json, err := platerrors.MarshalJSONString(e) | ||
if err != nil { | ||
return newCGoString(fmt.Sprintf("%s, failed to retrieve details due to: %s", e.Code, err.Error())) | ||
} | ||
return newCGoString(json) | ||
} | ||
|
||
// init initializes the backend module. | ||
// It sets up a default logger based on the OUTLINE_DEBUG environment variable. | ||
func init() { | ||
opts := slog.HandlerOptions{Level: slog.LevelInfo} | ||
|
||
dbg := os.Getenv("OUTLINE_DEBUG") | ||
if dbg != "" && dbg != "false" { | ||
dbg = "true" | ||
opts.Level = slog.LevelDebug | ||
} else { | ||
dbg = "false" | ||
} | ||
|
||
logger := slog.New(slog.NewTextHandler(os.Stderr, &opts)) | ||
slog.SetDefault(logger) | ||
|
||
slog.Info("Backend module initialized", "debug", dbg) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you can define this struct in Go instead and only have the include here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you mean define it as the
struct
as:I'm afraid this is not supported by CGo: