Skip to content

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

:recycle: Remove unwired RPC handlers and retain contract coverage https://github.com/siyuan-note/siyuan/issues/20234

Danielc583d077ccf2
diff --git a/kernel/plugin/rpc.go b/kernel/plugin/rpc.go
index 0cb95560b8..3a71ef1231 100644
--- a/kernel/plugin/rpc.go
+++ b/kernel/plugin/rpc.go
@@ -26,7 +26,6 @@ import (
"strings"
"sync"
- "github.com/gin-gonic/gin"
"github.com/lxzan/gws"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/apicontract"
@@ -196,13 +195,6 @@ type JsonRpcError struct {
Data any `json:"data,omitempty"`
}
-// JsonRpcRequestProcessingResults represents the results of parsing and validating JSON-RPC requests, including any global error and the individual results for each request in a batch.
-type JsonRpcRequestProcessingResults struct {
- Batch bool // Whether the original request was a batch (array) or single request
- GlobalError *JsonRpcErrorResponse // If the entire request is invalid
- Requests []*JsonRpcProcessingRequest
-}
-
// JsonRpcProcessingRequest represents the result of parsing and validating a single JSON-RPC request, including any error if the request is invalid.
type JsonRpcProcessingRequest struct {
Request *JsonRpcRequest // The parsed request, or nil if the request was invalid
@@ -218,91 +210,6 @@ type JsonRpcProcessingResponse struct {
Error *JsonRpcErrorResponse // The error response, or nil if the request was a notification or the response is a success
}
-// JsonRpcResponse returns the appropriate response (either success or error) to be sent back to the client, or nil if this is a notification and no response should be sent.
-func (r *JsonRpcProcessingResponse) JsonRpcResponse() any {
- if r.Response != nil {
- return r.Response
- }
- if r.Error != nil {
- return r.Error
- }
- return nil
-}
-
-// HandleRpcHttp handles POST /api/plugin/rpc/:name
-// Supports single call, batch call, and notification (no response for notification).
-func HandleRpcHttp(c *gin.Context) {
- name := util.GetRequestUrlStringParam(c, "name")
- p := resolveRunningPlugin(c, name, http.StatusOK)
- if p == nil {
- return
- }
-
- body, err := io.ReadAll(c.Request.Body)
- if err != nil {
- c.JSON(http.StatusOK, &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: &JsonRpcError{
- Code: JsonRpcErrorCodeInternalError,
- Message: JsonRpcErrorInternalError.Message,
- Data: fmt.Sprintf("Failed to read request body: %s", err),
- },
- ID: nil,
- })
- return
- }
-
- results := parseRpcRequests(body)
- if results.GlobalError != nil {
- c.JSON(http.StatusOK, results.GlobalError)
- return
- }
-
- responses := p.dispatchRpcRequests(c.Request.Context(), results.Requests)
-
- if !results.Batch {
- // Single request - return single response (or empty for notification)
- if len(responses) > 0 && responses[0] != nil {
- response := responses[0]
- if response.Response != nil {
- c.JSON(http.StatusOK, response.Response)
- return
- } else if response.Error != nil {
- c.JSON(http.StatusOK, response.Error)
- return
- }
- }
- c.Status(http.StatusNoContent)
- return
- }
-
- // Batch request - filter out nil responses (notifications) and return array
- filtered := filterRpcResponses(responses)
-
- if len(filtered) > 0 {
- c.JSON(http.StatusOK, filtered)
- } else {
- // All notifications in batch - send nothing per spec (MUST NOT return empty array)
- c.Status(http.StatusNoContent)
- }
-}
-
-// HandleRpcWebSocket handles GET /ws/plugin/rpc/:name
-// Supports single call, batch call, notification, and server push notifications.
-func HandleRpcWebSocket(c *gin.Context) {
- name := util.GetRequestUrlStringParam(c, "name")
- p := resolveRunningPlugin(c, name, http.StatusNotFound)
- if p == nil {
- return
- }
-
- if c.IsWebsocket() == false {
- c.String(http.StatusBadRequest, "This endpoint only accepts WebSocket connections")
- return
- }
- p.serveRPCWebSocket(c.Writer, c.Request)
-}
-
func (p *KernelPlugin) serveRPCWebSocket(writer http.ResponseWriter, request *http.Request) {
name := p.Name
if !strings.EqualFold(request.Header.Get("Upgrade"), "websocket") || !strings.Contains(strings.ToLower(request.Header.Get("Connection")), "upgrade") {
@@ -380,120 +287,3 @@ func (p *KernelPlugin) serveRPCWebSocket(writer http.ResponseWriter, request *ht
doOpen()
<-ctx.Done()
}
-
-// resolveRunningPlugin looks up the plugin by name and writes an error response if it is
-// not found (-32001) or not running (-32002). Returns nil when the caller should abort.
-func resolveRunningPlugin(c *gin.Context, name string, errStatus int) *KernelPlugin {
- p := GetManager().GetPlugin(name)
- if p == nil {
- c.JSON(errStatus, &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: JsonRpcErrorPluginNotLoaded,
- })
- return nil
- }
- if p.State() != PluginStateRunning {
- c.JSON(errStatus, &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: JsonRpcErrorPluginNotRunning,
- })
- return nil
- }
- return p
-}
-
-// parseRpcRequest parses a single JSON-RPC request from the given body. The body must be a JSON object.
-func parseRpcRequest(body []byte) (parsedRequest JsonRpcProcessingRequest) {
- var request JsonRpcRequest
- if !json.Valid(body) {
- // Invalid JSON
- parsedRequest.Error = &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: &JsonRpcError{
- Code: JsonRpcErrorCodeParseError,
- Message: JsonRpcErrorParseError.Message,
- Data: "RPC request is not valid JSON",
- },
- ID: nil,
- }
- return
- }
- if err := json.Unmarshal(body, &request); err != nil {
- // Invalid request structure
- parsedRequest.Error = &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: &JsonRpcError{
- Code: JsonRpcErrorCodeInvalidRequest,
- Message: JsonRpcErrorInvalidRequest.Message,
- Data: fmt.Sprintf("RPC request is not a valid JSON-RPC object: %s", err),
- },
- ID: nil,
- }
- return
- }
- parsedRequest.Request = &request
- return
-}
-
-// parseRpcRequests parses the given body into one or more JSON-RPC requests, handling both single and batch requests.
-func parseRpcRequests(body []byte) (results JsonRpcRequestProcessingResults) {
- if !json.Valid(body) {
- // Invalid JSON
- results.GlobalError = &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: &JsonRpcError{
- Code: JsonRpcErrorCodeParseError,
- Message: JsonRpcErrorParseError.Message,
- Data: "RPC request is not valid JSON",
- },
- ID: nil,
- }
- return
- }
-
- var jsonArray []json.RawMessage
- if err := json.Unmarshal(body, &jsonArray); err != nil {
- // single request
- request := parseRpcRequest(body)
- results.Requests = append(results.Requests, &request)
- return
- } else {
- // batch request
- if len(jsonArray) == 0 {
- // per spec, an empty array is invalid
- results.GlobalError = &JsonRpcErrorResponse{
- JsonRpc: JsonRpcVersion,
- Error: &JsonRpcError{
- Code: JsonRpcErrorCodeInvalidRequest,
- Message: JsonRpcErrorInvalidRequest.Message,
- Data: "RPC request is not allowed to be an empty array",
- },
- ID: nil,
- }
- return
- }
-
- results.Batch = true
- results.Requests = make([]*JsonRpcProcessingRequest, len(jsonArray))
- for i, raw := range jsonArray {
- request := parseRpcRequest(raw)
- results.Requests[i] = &request
- }
- }
- return
-}
-
-// filterRpcResponses filters out nil responses (for notifications) and extracts the actual response objects for non-nil responses.
-func filterRpcResponses(responses []*JsonRpcProcessingResponse) []any {
- filtered := make([]any, 0, len(responses))
- for _, response := range responses {
- if response != nil {
- if response.Response != nil {
- filtered = append(filtered, response.Response)
- } else if response.Error != nil {
- filtered = append(filtered, response.Error)
- }
- }
- }
- return filtered
-}
diff --git a/kernel/plugin/rpc_cancellation_test.go b/kernel/plugin/rpc_cancellation_test.go
index c40e724c42..a7e3fceeff 100644
--- a/kernel/plugin/rpc_cancellation_test.go
+++ b/kernel/plugin/rpc_cancellation_test.go
@@ -71,48 +71,42 @@ func rpcCancellationTestHandler(c *gin.Context) {
}
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)
- }
+ for _, path := range []string{"/api/plugin/rpc?name=rpc-cancellation", "/api/plugin/rpc/rpc-cancellation"} {
+ t.Run(path, 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()
+ engine.POST("/api/plugin/rpc", rpcCancellationTestHandler)
+ engine.POST("/api/plugin/rpc/:name", rpcCancellationTestHandler)
+ 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)
+ }
+ })
}
}
diff --git a/kernel/plugin/rpc_contract_test.go b/kernel/plugin/rpc_contract_test.go
index 3a5d8959ce..089e881664 100644
--- a/kernel/plugin/rpc_contract_test.go
+++ b/kernel/plugin/rpc_contract_test.go
@@ -2,6 +2,7 @@ package plugin
import (
"bytes"
+ "context"
"encoding/json"
"io"
"math"
@@ -104,7 +105,29 @@ func TestRPCContractHTTPCompatibility(t *testing.T) {
engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/plugin/rpc/contract-rpc", strings.NewReader(body)))
return recorder
}
- legacy := call(HandleRpcHttp)
+ parsed := parseRpcRequests([]byte(body))
+ var expected any = parsed.GlobalError
+ if parsed.GlobalError == nil {
+ responses := filterRpcResponses(p.dispatchRpcRequests(context.Background(), parsed.Requests))
+ expected = nil
+ if len(responses) > 0 {
+ if parsed.Batch {
+ expected = responses
+ } else {
+ expected = responses[0]
+ }
+ }
+ }
+ expectedStatus := 200
+ var expectedBody []byte
+ if expected == nil {
+ expectedStatus = 204
+ } else {
+ expectedBody, err = json.Marshal(expected)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
actual := call(func(c *gin.Context) {
var response apicontract.Response[apicontract.PluginRPCResponse]
if early := PrepareRPCContract(c); early != nil {
@@ -123,8 +146,8 @@ func TestRPCContractHTTPCompatibility(t *testing.T) {
c.JSON(status, response)
}
})
- if legacy.Code != actual.Code || !bytes.Equal(legacy.Body.Bytes(), actual.Body.Bytes()) {
- t.Fatalf("RPC HTTP changed for %s:\n%d %s\n%d %s", body, legacy.Code, legacy.Body, actual.Code, actual.Body)
+ if expectedStatus != actual.Code || !bytes.Equal(expectedBody, actual.Body.Bytes()) {
+ t.Fatalf("RPC HTTP changed for %s:\n%d %s\n%d %s", body, expectedStatus, expectedBody, actual.Code, actual.Body)
}
if err := bundle.ValidateHTTPResponse("POST", "/api/plugin/rpc/:name", actual.Code, actual.Header().Get("Content-Type"), actual.Body.Bytes()); err != nil {
t.Fatalf("RPC response violates contract: %s, %v", actual.Body, err)
diff --git a/kernel/plugin/rpc_legacy_test.go b/kernel/plugin/rpc_legacy_test.go
new file mode 100644
index 0000000000..8a0c3be2fc
--- /dev/null
+++ b/kernel/plugin/rpc_legacy_test.go
@@ -0,0 +1,108 @@
+package plugin
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+type JsonRpcRequestProcessingResults struct {
+ Batch bool // 是否为批量请求
+ GlobalError *JsonRpcErrorResponse // 整个请求的错误
+ Requests []*JsonRpcProcessingRequest
+}
+
+// parseRpcRequest 保留契约迁移前的解析规则,作为兼容性测试的独立参照。
+func parseRpcRequest(body []byte) (parsedRequest JsonRpcProcessingRequest) {
+ var request JsonRpcRequest
+ if !json.Valid(body) {
+ // JSON 格式错误。
+ parsedRequest.Error = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeParseError,
+ Message: JsonRpcErrorParseError.Message,
+ Data: "RPC request is not valid JSON",
+ },
+ ID: nil,
+ }
+ return
+ }
+ if err := json.Unmarshal(body, &request); err != nil {
+ // 请求结构错误。
+ parsedRequest.Error = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeInvalidRequest,
+ Message: JsonRpcErrorInvalidRequest.Message,
+ Data: fmt.Sprintf("RPC request is not a valid JSON-RPC object: %s", err),
+ },
+ ID: nil,
+ }
+ return
+ }
+ parsedRequest.Request = &request
+ return
+}
+
+// parseRpcRequests 为兼容性测试解析单次请求、批量请求与全局错误。
+func parseRpcRequests(body []byte) (results JsonRpcRequestProcessingResults) {
+ if !json.Valid(body) {
+ // JSON 格式错误。
+ results.GlobalError = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeParseError,
+ Message: JsonRpcErrorParseError.Message,
+ Data: "RPC request is not valid JSON",
+ },
+ ID: nil,
+ }
+ return
+ }
+
+ var jsonArray []json.RawMessage
+ if err := json.Unmarshal(body, &jsonArray); err != nil {
+ // 单次请求。
+ request := parseRpcRequest(body)
+ results.Requests = append(results.Requests, &request)
+ return
+ } else {
+ // 批量请求。
+ if len(jsonArray) == 0 {
+ // 规范不接受空数组。
+ results.GlobalError = &JsonRpcErrorResponse{
+ JsonRpc: JsonRpcVersion,
+ Error: &JsonRpcError{
+ Code: JsonRpcErrorCodeInvalidRequest,
+ Message: JsonRpcErrorInvalidRequest.Message,
+ Data: "RPC request is not allowed to be an empty array",
+ },
+ ID: nil,
+ }
+ return
+ }
+
+ results.Batch = true
+ results.Requests = make([]*JsonRpcProcessingRequest, len(jsonArray))
+ for i, raw := range jsonArray {
+ request := parseRpcRequest(raw)
+ results.Requests[i] = &request
+ }
+ }
+ return
+}
+
+// filterRpcResponses 为兼容性测试提取非通知响应。
+func filterRpcResponses(responses []*JsonRpcProcessingResponse) []any {
+ filtered := make([]any, 0, len(responses))
+ for _, response := range responses {
+ if response != nil {
+ if response.Response != nil {
+ filtered = append(filtered, response.Response)
+ } else if response.Error != nil {
+ filtered = append(filtered, response.Error)
+ }
+ }
+ }
+ return filtered
+}