44import logging
55import uuid
66import sys
7+ from typing import Any , Dict , Mapping
78
89from concurrent import futures
910from .exceptions import (JsonRpcException , JsonRpcRequestCancelled ,
@@ -175,6 +176,17 @@ def _handle_cancel_notification(self, msg_id):
175176 if request_future .cancel ():
176177 log .debug ("Cancelled request with id %s" , msg_id )
177178
179+ @staticmethod
180+ def _make_response_payload (header : Dict [str , Any ], result : Any ) -> Mapping [str , Any ]:
181+ # return type of 'Mapping' because it should not be mutated
182+ # further from here
183+ response = dict (header )
184+ if isinstance (result , dict ) and ('result' in result or 'error' in result ):
185+ response .update (result )
186+ else :
187+ response ['result' ] = result
188+ return response
189+
178190 def _handle_request (self , msg_id , method , params ):
179191 """Handle a request from the client."""
180192 try :
@@ -195,11 +207,14 @@ def _handle_request(self, msg_id, method, params):
195207 handler_result .add_done_callback (self ._request_callback (msg_id ))
196208 else :
197209 log .debug ("Got result from synchronous request handler: %s" , handler_result )
198- self ._consumer ({
199- 'jsonrpc' : JSONRPC_VERSION ,
200- 'id' : msg_id ,
201- 'result' : handler_result
202- })
210+ response = self ._make_response_payload (
211+ {
212+ 'jsonrpc' : JSONRPC_VERSION ,
213+ 'id' : msg_id ,
214+ },
215+ handler_result ,
216+ )
217+ self ._consumer (response )
203218
204219 def _request_callback (self , request_id ):
205220 """Construct a request callback for the given request ID."""
@@ -216,7 +231,8 @@ def callback(future):
216231 }
217232
218233 try :
219- message ['result' ] = future .result ()
234+ result = future .result ()
235+ message = self ._make_response_payload (message , result )
220236 except JsonRpcException as e :
221237 log .exception ("Failed to handle request %s" , request_id )
222238 message ['error' ] = e .to_dict ()
0 commit comments