From 9afb4ea3882cbf7cda9d5ab235edbc0d514c58a3 Mon Sep 17 00:00:00 2001 From: King Star Date: Sat, 13 Jun 2026 03:05:50 +0800 Subject: [PATCH] fix: preserve JSON-RPC error response ids --- lib/json_rpc_handler.rb | 2 +- test/json_rpc_handler_test.rb | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/lib/json_rpc_handler.rb b/lib/json_rpc_handler.rb index 977afa39..e055b2f7 100644 --- a/lib/json_rpc_handler.rb +++ b/lib/json_rpc_handler.rb @@ -79,7 +79,7 @@ def process_request(request, id_validation_pattern:, &method_finder) 'Method name must be a string and not start with "rpc."' end - return error_response(id: :unknown_id, id_validation_pattern: id_validation_pattern, error: { + return error_response(id: id, id_validation_pattern: id_validation_pattern, error: { code: ErrorCode::INVALID_REQUEST, message: "Invalid Request", data: error, diff --git a/test/json_rpc_handler_test.rb b/test/json_rpc_handler_test.rb index c1f08f11..9782c632 100644 --- a/test/json_rpc_handler_test.rb +++ b/test/json_rpc_handler_test.rb @@ -36,13 +36,14 @@ end it "returns an error when jsonrpc is not 2.0" do - handle jsonrpc: "3.0", id: 1, method: "add", params: { a: 1, b: 2 } + handle jsonrpc: "3.0", id: 3, method: "add", params: { a: 1, b: 2 } assert_rpc_error expected_error: { code: -32600, message: "Invalid Request", data: "JSON-RPC version must be 2.0", } + assert_equal 3, @response[:id] end # method @@ -51,13 +52,14 @@ # used for anything else. it "returns an error when method is not a string" do - handle jsonrpc: "2.0", id: 1, method: 42, params: { a: 1, b: 2 } + handle jsonrpc: "2.0", id: 8, method: 42, params: { a: 1, b: 2 } assert_rpc_error expected_error: { code: -32600, message: "Invalid Request", data: 'Method name must be a string and not start with "rpc."', } + assert_equal 8, @response[:id] end it "returns an error when method begins with 'rpc.'" do @@ -756,8 +758,19 @@ assert_nil @response end - it "returns an error with the id set to nil when the request is invalid" do - handle_json({ jsonrpc: "0.0", id: 1, method: "add", params: { a: 1, b: 2 } }.to_json) + it "returns an error with the request id when the JSON-RPC version is missing" do + handle_json({ id: 4, method: "add", params: { a: 1, b: 2 } }.to_json) + + assert_rpc_error expected_error: { + code: -32600, + message: "Invalid Request", + data: "JSON-RPC version must be 2.0", + } + assert_equal 4, @response[:id] + end + + it "returns an error with the id set to nil when the request id is invalid" do + handle_json({ jsonrpc: "2.0", id: {}, method: "add", params: { a: 1, b: 2 } }.to_json) assert_nil @response[:id] end