Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

Fix plugin RPC completion and cancellation (#19710)

fengwind20063af38eeca39e
diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.go
index 0a191ff624..d9100c0052 100644
--- a/kernel/plugin/plugin.go
+++ b/kernel/plugin/plugin.go
@@ -546,7 +546,7 @@ func (p *KernelPlugin) BroadcastNotification(method string, params util.Optional
// dispatchRpcRequests dispatches multiple JSON-RPC requests concurrently.
// Returns responses in the same order as requests. Nil responses indicate notifications.
-func (p *KernelPlugin) dispatchRpcRequests(requests []*JsonRpcProcessingRequest) []*JsonRpcProcessingResponse {
+func (p *KernelPlugin) dispatchRpcRequests(ctx context.Context, requests []*JsonRpcProcessingRequest) []*JsonRpcProcessingResponse {
responses := make([]*JsonRpcProcessingResponse, len(requests))
var wg sync.WaitGroup
@@ -560,7 +560,7 @@ func (p *KernelPlugin) dispatchRpcRequests(requests []*JsonRpcProcessingRequest)
// For notifications, dispatch without waiting for a response.
if request.Request.IsNotification() {
go func(request *JsonRpcRequest) {
- p.dispatchRpcRequest(request)
+ p.dispatchRpcRequest(p.context, request)
}(request.Request)
responses[i] = nil
continue
@@ -575,7 +575,7 @@ func (p *KernelPlugin) dispatchRpcRequests(requests []*JsonRpcProcessingRequest)
wg.Add(1)
go func(index int, request *JsonRpcRequest) {
defer wg.Done()
- responses[index] = p.dispatchRpcRequest(request)
+ responses[index] = p.dispatchRpcRequest(ctx, request)
}(i, request.Request)
}
@@ -585,7 +585,7 @@ func (p *KernelPlugin) dispatchRpcRequests(requests []*JsonRpcProcessingRequest)
// dispatchRpcRequest routes a single JSON-RPC request to the plugin's registered JS method.
// Returns nil for notifications (no ID field).
-func (p *KernelPlugin) dispatchRpcRequest(request *JsonRpcRequest) *JsonRpcProcessingResponse {
+func (p *KernelPlugin) dispatchRpcRequest(ctx context.Context, request *JsonRpcRequest) *JsonRpcProcessingResponse {
// Validate request structure
if rpcError := request.Validate(); rpcError != nil {
// For notifications, return nil (no response).
@@ -605,12 +605,13 @@ func (p *KernelPlugin) dispatchRpcRequest(request *JsonRpcRequest) *JsonRpcProce
// For notifications, call the method without waiting for a response and return nil.
if request.IsNotification() {
- go p.callRpcMethod(request.Method, request.Params.Value)
+ // 通知由插件生命周期管理,HTTP 返回后仍可继续执行。
+ go p.callRpcMethod(p.context, request.Method, request.Params.Value)
return nil
}
// For normal requests, call the method and return response or error.
- rpcResult, rpcError := p.callRpcMethod(request.Method, request.Params.Value)
+ rpcResult, rpcError := p.callRpcMethod(ctx, request.Method, request.Params.Value)
if rpcError == nil {
return &JsonRpcProcessingResponse{
Response: &JsonRpcRequestResponse{
@@ -630,8 +631,8 @@ func (p *KernelPlugin) dispatchRpcRequest(request *JsonRpcRequest) *JsonRpcProce
}
}
-// callRpcMethod invokes a registered JS RPC method via the event bus and awaits the response.
-func (p *KernelPlugin) callRpcMethod(method string, params any) (rpcResult any, rpcError *JsonRpcError) {
+// callRpcMethod 在事件循环中调用 RPC 方法,等待结果、请求取消或插件停止。
+func (p *KernelPlugin) callRpcMethod(ctx context.Context, method string, params any) (rpcResult any, rpcError *JsonRpcError) {
defer func() {
if r := recover(); r != nil {
logging.LogDebugf("[plugin:%s] panic in RPC method [%s]: %v", p.Name, method, r)
@@ -673,8 +674,22 @@ func (p *KernelPlugin) callRpcMethod(method string, params any) (rpcResult any,
}
done := make(chan *TaskResult, 1)
+ var completeOnce sync.Once
+ complete := func(result *TaskResult) {
+ // 仅接收首次结果,等待者退出后的回调也不会阻塞事件循环。
+ completeOnce.Do(func() { done <- result })
+ }
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
+ // 排队期间取消的调用不再进入脚本,已执行的脚本不会被强制中断。
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-p.context.Done():
+ return nil, p.context.Err()
+ default:
+ }
- p.worker.Run(func(rt *goja.Runtime) (result any, err error) {
rpcParams := []goja.Value{}
jsParams := rt.ToValue(params)
if isJsArray(rt, jsParams) {
@@ -691,12 +706,26 @@ func (p *KernelPlugin) callRpcMethod(method string, params any) (rpcResult any,
}
invokeFunction(func(_ *goja.Runtime, result *CallResult) {
- done <- result.TaskResult()
+ complete(result.TaskResult())
}, rt, true, rpcMethod.Method, rt.GlobalObject(), rpcParams...)
return
- }, nil)
+ }, func(_ *goja.Runtime, _ any, err error) {
+ if err != nil {
+ complete(&TaskResult{err: err})
+ }
+ })
+ if runErr != nil {
+ complete(&TaskResult{err: runErr})
+ }
- result := <-done
+ var result *TaskResult
+ select {
+ case result = <-done:
+ case <-ctx.Done():
+ result = &TaskResult{err: ctx.Err()}
+ case <-p.context.Done():
+ result = &TaskResult{err: p.context.Err()}
+ }
if result.err != nil {
rpcError = &JsonRpcError{
Code: JsonRpcErrorCodeInternalError,
diff --git a/kernel/plugin/rpc.go b/kernel/plugin/rpc.go
index 7c0181e616..0cb95560b8 100644
--- a/kernel/plugin/rpc.go
+++ b/kernel/plugin/rpc.go
@@ -258,7 +258,7 @@ func HandleRpcHttp(c *gin.Context) {
return
}
- responses := p.dispatchRpcRequests(results.Requests)
+ responses := p.dispatchRpcRequests(c.Request.Context(), results.Requests)
if !results.Batch {
// Single request - return single response (or empty for notification)
@@ -322,7 +322,8 @@ func (p *KernelPlugin) serveRPCWebSocket(writer http.ResponseWriter, request *ht
logging.LogErrorf("[plugin:%s] RPC WebSocket request read failed: %s", name, err)
return
}
- response, err := p.dispatchRPCContract(request)
+ // WebSocket 调用随插件停止退出,不使用 HTTP 握手请求的上下文。
+ response, err := p.dispatchRPCContract(p.context, request)
if err != nil {
logging.LogErrorf("[plugin:%s] RPC response marshal failed: %s", name, err)
return
diff --git a/kernel/plugin/rpc_cancellation_test.go b/kernel/plugin/rpc_cancellation_test.go
new file mode 100644
index 0000000000..c40e724c42
--- /dev/null
+++ b/kernel/plugin/rpc_cancellation_test.go
@@ -0,0 +1,338 @@
+package plugin
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/gin-gonic/gin"
+ "github.com/lxzan/gws"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func newRPCCancellationTestPlugin(t *testing.T) *KernelPlugin {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ p := &KernelPlugin{
+ Petal: &model.Petal{Name: "rpc-cancellation"}, context: ctx, cancel: cancel,
+ runtime: eventloop.NewEventLoop(), sockets: map[*gws.Conn]bool{},
+ }
+ p.worker.Start(p.runtime)
+ p.runtime.Start()
+ p.state.Store(int64(PluginStateRunning))
+ GetManager().plugins.Store(p.Name, p)
+ t.Cleanup(func() {
+ cancel()
+ p.runtime.Terminate()
+ GetManager().plugins.Delete(p.Name)
+ })
+ return p
+}
+
+func rpcCancellationTestRun(t *testing.T, p *KernelPlugin, executor TaskExecutor) {
+ t.Helper()
+ if _, err := p.worker.RunSync(executor); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func rpcCancellationTestWait(t *testing.T, done <-chan struct{}, label string) {
+ t.Helper()
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ t.Fatalf("timed out waiting for %s", label)
+ }
+}
+
+func rpcCancellationTestHandler(c *gin.Context) {
+ endpoint := apicontract.PluginRPCHTTP
+ if early := PrepareRPCContract(c); early != nil {
+ c.JSON(endpoint.Status(*early), *early)
+ return
+ }
+ request, err := endpoint.Decode(c.Request.Body)
+ if err != nil {
+ c.JSON(200, endpoint.DecodeFailure(err))
+ return
+ }
+ response := DispatchRPCContract(c, request)
+ if endpoint.Status(response) == 204 {
+ c.Status(204)
+ return
+ }
+ c.JSON(endpoint.Status(response), response)
+}
+
+func TestRPCHTTPWaitCancellation(t *testing.T) {
+ for _, legacy := range []bool{false, true} {
+ for _, path := range []string{"/api/plugin/rpc?name=rpc-cancellation", "/api/plugin/rpc/rpc-cancellation"} {
+ t.Run(path+map[bool]string{false: "/contract", true: "/legacy"}[legacy], func(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ started := make(chan struct{})
+ var resolve func(interface{}) error
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ p.rpcMethods.Store("pending", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ promise, resolvePromise, _ := rt.NewPromise()
+ resolve = resolvePromise
+ close(started)
+ return rt.ToValue(promise), nil
+ }})
+ return nil, nil
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ engine := gin.New()
+ handler := rpcCancellationTestHandler
+ if legacy {
+ handler = HandleRpcHttp
+ }
+ engine.POST("/api/plugin/rpc", handler)
+ engine.POST("/api/plugin/rpc/:name", handler)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest("POST", path, strings.NewReader(`{"jsonrpc":"2.0","method":"pending","id":"cancelled"}`)).WithContext(ctx)
+ done := make(chan struct{})
+ go func() {
+ engine.ServeHTTP(recorder, request)
+ close(done)
+ }()
+ rpcCancellationTestWait(t, started, "RPC invocation")
+ // 即使断言失败,也完成 Promise,避免测试自身遗留等待者。
+ defer rpcCancellationTestRun(t, p, func(*goja.Runtime) (any, error) { return nil, resolve("late") })
+ cancel()
+ rpcCancellationTestWait(t, done, "HTTP cancellation")
+ var reply JsonRpcErrorResponse
+ if err := json.Unmarshal(recorder.Body.Bytes(), &reply); err != nil || reply.ID != "cancelled" || reply.Error == nil || reply.Error.Code != JsonRpcErrorCodeInternalError {
+ t.Fatalf("unexpected cancellation reply: %s, %v", recorder.Body, err)
+ }
+ })
+ }
+ }
+}
+
+func TestRPCWorkerFailureReturns(t *testing.T) {
+ for _, failure := range []string{"uninitialized", "terminated", "panic"} {
+ t.Run(failure, func(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ p.rpcMethods.Store("fail", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ panic("RPC executor failure")
+ }})
+ switch failure {
+ case "uninitialized":
+ p.worker.loop = nil
+ case "terminated":
+ p.runtime.Terminate()
+ }
+ done := make(chan struct{})
+ var rpcError *JsonRpcError
+ go func() {
+ _, rpcError = p.callRpcMethod(context.Background(), "fail", nil)
+ close(done)
+ }()
+ rpcCancellationTestWait(t, done, "worker failure")
+ if rpcError == nil || rpcError.Code != JsonRpcErrorCodeInternalError {
+ t.Fatalf("unexpected worker failure: %+v", rpcError)
+ }
+ })
+ }
+}
+
+func TestRPCPluginCancellation(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ started := make(chan struct{})
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ p.rpcMethods.Store("pending", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ promise, _, _ := rt.NewPromise()
+ close(started)
+ return rt.ToValue(promise), nil
+ }})
+ return nil, nil
+ })
+ done := make(chan struct{})
+ var rpcError *JsonRpcError
+ go func() {
+ _, rpcError = p.callRpcMethod(context.Background(), "pending", nil)
+ close(done)
+ }()
+ rpcCancellationTestWait(t, started, "RPC invocation")
+ p.cancel()
+ rpcCancellationTestWait(t, done, "plugin cancellation")
+ if rpcError == nil || rpcError.Code != JsonRpcErrorCodeInternalError {
+ t.Fatalf("unexpected plugin cancellation: %+v", rpcError)
+ }
+}
+
+func TestRPCNotificationOutlivesHTTPRequest(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ called := make(chan struct{})
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ p.rpcMethods.Store("notify", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ close(called)
+ return goja.Undefined(), nil
+ }})
+ return nil, nil
+ })
+ // 暂停事件循环,保证通知只能在 HTTP 返回并取消上下文后执行。
+ blocked, release := make(chan struct{}), make(chan struct{})
+ if err := p.worker.Run(func(*goja.Runtime) (any, error) {
+ close(blocked)
+ <-release
+ return nil, nil
+ }, nil); err != nil {
+ t.Fatal(err)
+ }
+ defer close(release)
+ rpcCancellationTestWait(t, blocked, "event loop blocker")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ engine := gin.New()
+ engine.POST("/api/plugin/rpc/:name", rpcCancellationTestHandler)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest("POST", "/api/plugin/rpc/"+p.Name, strings.NewReader(`{"jsonrpc":"2.0","method":"notify"}`)).WithContext(ctx)
+ engine.ServeHTTP(recorder, request)
+ cancel()
+ if recorder.Code != 204 || recorder.Body.Len() != 0 {
+ t.Fatalf("notification produced a reply: %d %s", recorder.Code, recorder.Body)
+ }
+ release <- struct{}{}
+ rpcCancellationTestWait(t, called, "notification after HTTP return")
+}
+
+func TestRPCBatchWaitCancellation(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ started := make(chan struct{}, 2)
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ p.rpcMethods.Store("pending", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ promise, _, _ := rt.NewPromise()
+ started <- struct{}{}
+ return rt.ToValue(promise), nil
+ }})
+ return nil, nil
+ })
+ request, err := apicontract.DecodePluginRPC(strings.NewReader(`[
+ {"jsonrpc":"2.0","method":"pending","id":"first"},
+ {"jsonrpc":"2.0","method":"missing"},
+ false,
+ {"jsonrpc":"2.0","method":"pending","id":null}
+ ]`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan struct{})
+ var response *apicontract.PluginRPCResponse
+ go func() {
+ response, err = p.dispatchRPCContract(ctx, request)
+ close(done)
+ }()
+ rpcCancellationTestWait(t, started, "first batch call")
+ rpcCancellationTestWait(t, started, "second batch call")
+ cancel()
+ rpcCancellationTestWait(t, done, "batch cancellation")
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(response)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var replies []JsonRpcErrorResponse
+ if err := json.Unmarshal(data, &replies); err != nil || len(replies) != 3 {
+ t.Fatalf("unexpected batch response: %s, %v", data, err)
+ }
+ for i, expected := range []JsonRpcErrorCode{JsonRpcErrorCodeInternalError, JsonRpcErrorCodeInvalidRequest, JsonRpcErrorCodeInternalError} {
+ if replies[i].Error == nil || replies[i].Error.Code != expected {
+ t.Fatalf("batch error order changed: %s", data)
+ }
+ }
+ if replies[0].ID != "first" || replies[1].ID != nil || replies[2].ID != nil {
+ t.Fatalf("batch IDs changed: %s", data)
+ }
+}
+
+func TestRPCCancelledCallDoesNotRun(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ called := false
+ p.rpcMethods.Store("write", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {
+ called = true
+ return goja.Undefined(), nil
+ }})
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ _, rpcError := p.callRpcMethod(ctx, "write", nil)
+ if rpcError == nil || rpcError.Code != JsonRpcErrorCodeInternalError {
+ t.Fatalf("unexpected cancellation: %+v", rpcError)
+ }
+ // 等待此前排队的任务处理完,检查取消的调用没有进入脚本。
+ rpcCancellationTestRun(t, p, func(*goja.Runtime) (any, error) { return nil, nil })
+ if called {
+ t.Fatal("cancelled RPC entered the script")
+ }
+}
+
+func TestRPCMethodResults(t *testing.T) {
+ for _, entry := range []struct {
+ name, script string
+ wantError bool
+ }{
+ {"synchronous", `() => 42`, false},
+ {"promise", `() => Promise.resolve(42)`, false},
+ {"throw", `() => { throw new Error("RPC failure"); }`, true},
+ {"reject", `() => Promise.reject(new Error("RPC failure"))`, true},
+ {"reject_string", `() => Promise.reject("RPC failure")`, true},
+ {"resolve_getter_throw", `() => Promise.resolve({
+ get value() { throw new Error("RPC failure"); }
+ })`, true},
+ {"reject_getter_throw", `() => Promise.reject({
+ get value() { throw new Error("RPC failure"); }
+ })`, true},
+ {"reject_to_string_throw", `() => {
+ const error = new Error("rejected");
+ error.toString = () => { throw new Error("RPC failure"); };
+ return Promise.reject(error);
+ }`, true},
+ {"then_throw", `() => {
+ const promise = Promise.resolve(42);
+ promise.then = () => { throw new Error("RPC failure"); };
+ return promise;
+ }`, true},
+ {"then_twice", `() => {
+ const promise = Promise.resolve(42);
+ promise.then = (resolve) => { resolve(42); resolve(42); };
+ return promise;
+ }`, false},
+ } {
+ t.Run(entry.name, func(t *testing.T) {
+ p := newRPCCancellationTestPlugin(t)
+ rpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {
+ value, err := rt.RunString(entry.script)
+ if err != nil {
+ return nil, err
+ }
+ method, _ := goja.AssertFunction(value)
+ p.rpcMethods.Store("result", &RpcMethod{Method: method})
+ return nil, nil
+ })
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ result, rpcError := p.callRpcMethod(ctx, "result", nil)
+ if ctx.Err() != nil {
+ t.Fatalf("RPC waited for context expiration instead of returning its result: %v", ctx.Err())
+ }
+ if entry.wantError {
+ if rpcError == nil || rpcError.Code != JsonRpcErrorCodeInternalError || !strings.Contains(rpcError.Data.(string), "RPC failure") {
+ t.Fatalf("unexpected script error: %#v", rpcError)
+ }
+ } else if rpcError != nil || result != int64(42) {
+ t.Fatalf("unexpected script result: %v, %+v", result, rpcError)
+ }
+ })
+ }
+}
diff --git a/kernel/plugin/rpc_contract.go b/kernel/plugin/rpc_contract.go
index e8f4361c4e..670a726aa5 100644
--- a/kernel/plugin/rpc_contract.go
+++ b/kernel/plugin/rpc_contract.go
@@ -1,6 +1,7 @@
package plugin
import (
+ "context"
"encoding/json"
"fmt"
@@ -47,7 +48,7 @@ func DispatchRPCContract(c *gin.Context, request apicontract.PluginRPCBatchReque
if !ok {
panic("RPC plugin was not prepared")
}
- response, err := p.dispatchRPCContract(request)
+ response, err := p.dispatchRPCContract(c.Request.Context(), request)
if err != nil {
return rpcContractInternalError(err)
}
@@ -58,7 +59,7 @@ func DispatchRPCContract(c *gin.Context, request apicontract.PluginRPCBatchReque
}
// dispatchRPCContract 共用单次与批量调用的类型化响应,空值表示不发送通知回复。
-func (p *KernelPlugin) dispatchRPCContract(request apicontract.PluginRPCBatchRequest) (*apicontract.PluginRPCResponse, error) {
+func (p *KernelPlugin) dispatchRPCContract(ctx context.Context, request apicontract.PluginRPCBatchRequest) (*apicontract.PluginRPCResponse, error) {
if request.Error != nil {
response := apicontract.RPCSingleResponse(apicontract.RPCFailureReply(*request.Error))
return &response, nil
@@ -67,7 +68,7 @@ func (p *KernelPlugin) dispatchRPCContract(request apicontract.PluginRPCBatchReq
if err != nil {
return nil, err
}
- responses := p.dispatchRpcRequests(requests)
+ responses := p.dispatchRpcRequests(ctx, requests)
var replies []apicontract.PluginRPCReply
for _, response := range responses {
if response == nil || response.Response == nil && response.Error == nil {
diff --git a/kernel/plugin/rpc_websocket_contract_test.go b/kernel/plugin/rpc_websocket_contract_test.go
index b39f25dac5..97bcdb0f4a 100644
--- a/kernel/plugin/rpc_websocket_contract_test.go
+++ b/kernel/plugin/rpc_websocket_contract_test.go
@@ -60,7 +60,7 @@ func TestRPCWebSocketContractMessages(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- expected, err := p.dispatchRPCContract(request)
+ expected, err := p.dispatchRPCContract(ctx, request)
if err != nil {
t.Fatal(err)
}
diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.go
index edaa6599c1..3916896234 100644
--- a/kernel/plugin/sandbox.go
+++ b/kernel/plugin/sandbox.go
@@ -395,17 +395,36 @@ func invokeFunction(callback func(rt *goja.Runtime, result *CallResult), rt *goj
return
}
- then(resultObj, rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) {
- // ⚠️ call.Arguments always is an empty array.
- promise, ok := result.(*goja.Promise)
- if ok {
- callback(rt, &CallResult{Value: promise.Result()})
- } else {
- callback(rt, &CallResult{Value: resultJs})
- }
- }), rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) {
- callback(rt, &CallResult{Error: fmt.Errorf("promise rejected: %v", call.Argument(0).Export())})
+ // 在 Promise 吸收回调异常前,将转换错误交回调用方。
+ runCallback := func(fn func()) {
+ defer func() {
+ if r := recover(); r != nil {
+ callback(rt, &CallResult{Error: fmt.Errorf("promise callback panicked: %v", r)})
+ }
+ }()
+ fn()
+ }
+
+ // 使用 Goja 原生函数签名接收 Promise 的完成值和拒绝原因。
+ _, thenErr := then(resultObj, rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ runCallback(func() {
+ callback(rt, &CallResult{Value: call.Argument(0)})
+ })
+ return goja.Undefined()
+ }), rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ runCallback(func() {
+ reason := call.Argument(0).Export()
+ // Error 的 message 通常不可枚举,导出对象时需保留其错误文本。
+ if object, ok := call.Argument(0).(*goja.Object); ok && object.ClassName() == "Error" {
+ reason = object.String()
+ }
+ callback(rt, &CallResult{Error: fmt.Errorf("promise rejected: %v", reason)})
+ })
+ return goja.Undefined()
}))
+ if thenErr != nil {
+ callback(rt, &CallResult{Error: thenErr})
+ }
} else {
callback(rt, &CallResult{Value: resultJs})
}