Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions pylsp_jsonrpc/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging
import uuid
import sys
from typing import Any, Dict, Mapping

from concurrent import futures
from .exceptions import (JsonRpcException, JsonRpcRequestCancelled,
Expand Down Expand Up @@ -175,6 +176,17 @@ def _handle_cancel_notification(self, msg_id):
if request_future.cancel():
log.debug("Cancelled request with id %s", msg_id)

@staticmethod
def _make_response_payload(header: Dict[str, Any], result: Any) -> Mapping[str, Any]:
# return type of 'Mapping' because it should not be mutated
# further from here
response = dict(header)
if isinstance(result, dict) and ('result' in result or 'error' in result):
response.update(result)
else:
response['result'] = result
return response

def _handle_request(self, msg_id, method, params):
"""Handle a request from the client."""
try:
Expand All @@ -195,11 +207,14 @@ def _handle_request(self, msg_id, method, params):
handler_result.add_done_callback(self._request_callback(msg_id))
else:
log.debug("Got result from synchronous request handler: %s", handler_result)
self._consumer({
'jsonrpc': JSONRPC_VERSION,
'id': msg_id,
'result': handler_result
})
response = self._make_response_payload(
{
'jsonrpc': JSONRPC_VERSION,
'id': msg_id,
},
handler_result,
)
self._consumer(response)

def _request_callback(self, request_id):
"""Construct a request callback for the given request ID."""
Expand All @@ -216,7 +231,8 @@ def callback(future):
}

try:
message['result'] = future.result()
result = future.result()
message = self._make_response_payload(message, result)
except JsonRpcException as e:
log.exception("Failed to handle request %s", request_id)
message['error'] = e.to_dict()
Expand Down