4
4
import logging
5
5
import uuid
6
6
import sys
7
+ from typing import Any , Dict , Mapping
7
8
8
9
from concurrent import futures
9
10
from .exceptions import (JsonRpcException , JsonRpcRequestCancelled ,
@@ -175,6 +176,17 @@ def _handle_cancel_notification(self, msg_id):
175
176
if request_future .cancel ():
176
177
log .debug ("Cancelled request with id %s" , msg_id )
177
178
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
+
178
190
def _handle_request (self , msg_id , method , params ):
179
191
"""Handle a request from the client."""
180
192
try :
@@ -195,11 +207,14 @@ def _handle_request(self, msg_id, method, params):
195
207
handler_result .add_done_callback (self ._request_callback (msg_id ))
196
208
else :
197
209
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 )
203
218
204
219
def _request_callback (self , request_id ):
205
220
"""Construct a request callback for the given request ID."""
@@ -216,7 +231,8 @@ def callback(future):
216
231
}
217
232
218
233
try :
219
- message ['result' ] = future .result ()
234
+ result = future .result ()
235
+ message = self ._make_response_payload (message , result )
220
236
except JsonRpcException as e :
221
237
log .exception ("Failed to handle request %s" , request_id )
222
238
message ['error' ] = e .to_dict ()
0 commit comments