1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
|
import inspect
import json
import logging
import uuid
_LOGGER = logging.getLogger(__name__)
class JSONRPCError(Exception):
"""Root exception for all errors related to this library"""
class TransportError(JSONRPCError):
"""An error occurred while performing a connection to the server"""
def __init__(self, exception_text, message=None, *args):
"""Create the transport error for the attempted message."""
if message:
super(TransportError, self).__init__(
'%s: %s' % (message.transport_error_text, exception_text),
*args)
else:
super(TransportError, self).__init__(exception_text, *args)
class ProtocolError(JSONRPCError):
"""An error occurred while dealing with the JSON-RPC protocol"""
class Server(object):
"""A connection to a JSON-RPC server"""
def __init__(self):
"""Initialize the json-rpc server object."""
self._server_request_handlers = {}
def send_message(self, message):
"""Issue the request to the server and return the method result.
This method must be implemented by the child class.
"""
raise NotImplementedError()
def receive_request(self, request):
"""Called when a request is received from the server."""
result = None
error = None
args, kwargs = request.get_args()
if request.method in self._server_request_handlers:
try:
handler = self._server_request_handlers[request.method]
if inspect.iscoroutinefunction(handler):
raise TypeError(
"Async handlers are not supported in "
"synchronous sever implementations")
else:
result = handler(*args, **kwargs)
except Exception as exc:
_LOGGER.error(exc, exc_info=exc)
error = {
'code': -32000,
'message': 'Server Error: %s' % exc,
}
else:
error = {
'code': -32601,
'message': 'Method not found',
}
if request.msg_id is not None:
return Response(request, result, error)
else:
return None
async def async_receive_request(self, request):
"""Called when a request is received from the server.
If the implementation calls async_receive_request instead of
receive_request, asynchronous request handlers are also supported
"""
result = None
error = None
args, kwargs = request.get_args()
if request.method in self._server_request_handlers:
try:
handler = self._server_request_handlers[request.method]
if inspect.iscoroutinefunction(handler):
result = await handler(*args, **kwargs)
else:
result = handler(*args, **kwargs)
except Exception as exc:
_LOGGER.error(exc, exc_info=exc)
error = {
'code': -32000,
'message': 'Server Error: %s' % exc,
}
else:
error = {
'code': -32601,
'message': 'Method not found',
}
if request.msg_id is not None:
return Response(request, result, error)
else:
return None
def __getattr__(self, method_name):
if method_name.startswith("_"): # prevent calls for private methods
raise AttributeError("invalid attribute '%s'" % method_name)
return Method(self.__request, self.__register, method_name)
def __setattr__(self, method_name, callback):
if method_name.startswith("_"): # prevent calls for private methods
return super(Server, self).__setattr__(method_name, callback)
return self.__register(method_name, callback)
def __request(self, method_name, args=None, kwargs=None):
"""Perform the actual RPC call.
If _notification=True, don't wait for a response
"""
if kwargs.pop('_notification', False):
msg_id = None
else:
msg_id = str(uuid.uuid4())
if args and kwargs:
raise ProtocolError(
'JSON-RPC spec forbids mixing arguments and keyword arguments')
return self.send_message(Request(method_name, args or kwargs, msg_id))
def __register(self, method_name, callback):
"""Register a callback for if the server sends this request."""
self._server_request_handlers[method_name] = callback
class Message(object):
"""Message to be sent to the jsonrpc server."""
@property
def response_id(self):
return None
def serialize(self):
"""Generate the raw JSON message to be sent to the server"""
raise NotImplementedError()
def parse_response(self, response):
"""Parse the response from the server and return the result."""
raise NotImplementedError()
@property
def transport_error_text(self):
"""Exception text for a transport error."""
raise NotImplementedError()
def __str__(self):
return self.serialize()
class Request(Message):
"""Request a method call on the server."""
def __init__(self, method=None, params=None, msg_id=None):
self.method = method
self.params = params
self.msg_id = msg_id
@staticmethod
def parse(data):
"""Generate a request object by parsing the json data."""
if 'method' not in data:
raise ProtocolError('Request from server does not contain method')
method = data.get('method')
params = data.get('params')
msg_id = data.get('id')
if (
not isinstance(params, list)
and not isinstance(params, dict)
and params is not None):
raise ProtocolError(
'Parameters must either be a positional list or named dict.')
return Request(method, params, msg_id)
@property
def response_id(self):
return self.msg_id
def serialize(self):
"""Generate the raw JSON message to be sent to the server"""
data = {'jsonrpc': '2.0', 'method': self.method}
if self.params:
data['params'] = self.params
if self.msg_id is not None:
data['id'] = self.msg_id
return json.dumps(data)
def parse_response(self, data):
"""Parse the response from the server and return the result."""
if self.msg_id is None:
# Don't parse results for notification requests
return None
if not isinstance(data, dict):
raise ProtocolError('Response is not a dictionary')
if data.get('error') is not None:
code = data['error'].get('code', '')
message = data['error'].get('message', '')
raise ProtocolError(code, message, data)
elif 'result' not in data:
raise ProtocolError('Response without a result field')
else:
return data['result']
@property
def transport_error_text(self):
"""Exception text for a transport error."""
return 'Error calling method %r' % self.method
def get_args(self):
"""Transform the request parameters into args/kwargs"""
args = []
kwargs = {}
if isinstance(self.params, list):
args = self.params
elif isinstance(self.params, dict):
kwargs = self.params
elif self.params is not None:
raise ProtocolError(
'Parameters must either be a positional list or named dict.')
return args, kwargs
class Response(Message):
"""Respond to a method call from the server."""
def __init__(self, request, result=None, error=None):
self.request = request
self.result = result
self.error = error
def serialize(self):
"""Generate the raw JSON message to be sent to the server"""
data = {'jsonrpc': '2.0', 'id': self.request.msg_id}
if self.error is not None:
data['error'] = self.error
else:
data['result'] = self.result
return json.dumps(data)
def parse_response(self, response):
"""Parse the response from the server and return the result."""
# Don't parse results from response messages
return None
@property
def transport_error_text(self):
"""Exception text for a transport error."""
return 'Error responding to server method %r' % self.request.method
class Method(object):
"""Map the methods called on the server to json-rpc methods."""
def __init__(self, request_method, register_method, method_name):
self.__request_method = request_method
self.__register_method = register_method
self.__method_name = method_name
def __getattr__(self, method_name):
if method_name.startswith("_"): # prevent calls for private methods
raise AttributeError("invalid attribute '%s'" % method_name)
return Method(self.__request_method, self.__register_method,
"%s.%s" % (self.__method_name, method_name))
def __call__(self, *args, **kwargs):
return self.__request_method(self.__method_name, args, kwargs)
def __setattr__(self, method_name, callback):
if method_name.startswith("_"): # prevent calls for private methods
return super(Method, self).__setattr__(method_name, callback)
return self.__register_method(
"%s.%s" % (self.__method_name, method_name), callback)
|