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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .. import RPCBatchProtocol, RPCRequest, RPCResponse, RPCErrorResponse,\
InvalidRequestError, MethodNotFoundError, ServerError,\
InvalidReplyError, RPCError, RPCBatchRequest, RPCBatchResponse
import json
import six
import inspect
import sys
if 'jsonext' in sys.modules:
# jsonext was imported before this file, assume the intent is that
# it is used in place of the regular json encoder.
import jsonext
json_dumps = jsonext.dumps
else:
json_dumps = json.dumps
class FixedErrorMessageMixin(object):
def __init__(self, *args, **kwargs):
if not args:
args = [self.message]
super(FixedErrorMessageMixin, self).__init__(*args, **kwargs)
def error_respond(self):
response = JSONRPCErrorResponse()
response.error = self.message
response.unique_id = None
response._jsonrpc_error_code = self.jsonrpc_error_code
return response
class JSONRPCParseError(FixedErrorMessageMixin, InvalidRequestError):
jsonrpc_error_code = -32700
message = 'Parse error'
class JSONRPCInvalidRequestError(FixedErrorMessageMixin, InvalidRequestError):
jsonrpc_error_code = -32600
message = 'Invalid Request'
class JSONRPCMethodNotFoundError(FixedErrorMessageMixin, MethodNotFoundError):
jsonrpc_error_code = -32601
message = 'Method not found'
class JSONRPCInvalidParamsError(FixedErrorMessageMixin, InvalidRequestError):
jsonrpc_error_code = -32602
message = 'Invalid params'
class JSONRPCInternalError(FixedErrorMessageMixin, InvalidRequestError):
jsonrpc_error_code = -32603
message = 'Internal error'
class JSONRPCServerError(FixedErrorMessageMixin, InvalidRequestError):
jsonrpc_error_code = -32000
message = ''
class JSONRPCSuccessResponse(RPCResponse):
def _to_dict(self):
return {
'jsonrpc': JSONRPCProtocol.JSON_RPC_VERSION,
'id': self.unique_id,
'result': self.result,
}
def serialize(self):
return json_dumps(self._to_dict())
class JSONRPCErrorResponse(RPCErrorResponse):
def _to_dict(self):
return {
'jsonrpc': JSONRPCProtocol.JSON_RPC_VERSION,
'id': self.unique_id,
'error': {
'message': str(self.error),
'code': self._jsonrpc_error_code,
}
}
def serialize(self):
return json_dumps(self._to_dict())
def _get_code_and_message(error):
assert isinstance(error, (Exception, six.string_types))
if isinstance(error, Exception):
if hasattr(error, 'jsonrpc_error_code'):
code = error.jsonrpc_error_code
msg = str(error)
elif isinstance(error, InvalidRequestError):
code = JSONRPCInvalidRequestError.jsonrpc_error_code
msg = JSONRPCInvalidRequestError.message
elif isinstance(error, MethodNotFoundError):
code = JSONRPCMethodNotFoundError.jsonrpc_error_code
msg = JSONRPCMethodNotFoundError.message
else:
# allow exception message to propagate
code = JSONRPCServerError.jsonrpc_error_code
msg = str(error)
else:
code = -32000
msg = error
return code, msg
class JSONRPCRequest(RPCRequest):
def error_respond(self, error):
if self.unique_id is None:
return None
response = JSONRPCErrorResponse()
code, msg = _get_code_and_message(error)
response.error = msg
response.unique_id = self.unique_id
response._jsonrpc_error_code = code
return response
def respond(self, result):
if self.unique_id is None:
return None
response = JSONRPCSuccessResponse()
response.result = result
response.unique_id = self.unique_id
return response
def _to_dict(self):
jdata = {
'jsonrpc': JSONRPCProtocol.JSON_RPC_VERSION,
'method': self.method,
}
if self.args:
jdata['params'] = self.args
if self.kwargs:
jdata['params'] = self.kwargs
if hasattr(self, 'unique_id') and self.unique_id is not None:
jdata['id'] = self.unique_id
return jdata
def serialize(self):
return json_dumps(self._to_dict())
class JSONRPCBatchRequest(RPCBatchRequest):
def create_batch_response(self):
if self._expects_response():
return JSONRPCBatchResponse()
def _expects_response(self):
for request in self:
if isinstance(request, Exception):
return True
if request.unique_id != None:
return True
return False
def serialize(self):
return json_dumps([req._to_dict() for req in self])
class JSONRPCBatchResponse(RPCBatchResponse):
def serialize(self):
return json_dumps([resp._to_dict() for resp in self if resp != None])
class JSONRPCProtocol(RPCBatchProtocol):
"""JSONRPC protocol implementation.
Currently, only version 2.0 is supported."""
JSON_RPC_VERSION = "2.0"
_ALLOWED_REPLY_KEYS = sorted(['id', 'jsonrpc', 'error', 'result'])
_ALLOWED_REQUEST_KEYS = sorted(['id', 'jsonrpc', 'method', 'params'])
def __init__(self, *args, **kwargs):
super(JSONRPCProtocol, self).__init__(*args, **kwargs)
self._id_counter = 0
def _get_unique_id(self):
self._id_counter += 1
return self._id_counter
def create_batch_request(self, requests=None):
return JSONRPCBatchRequest(requests or [])
def create_request(self, method, args=None, kwargs=None, one_way=False):
if args and kwargs:
raise InvalidRequestError('Does not support args and kwargs at '\
'the same time')
request = JSONRPCRequest()
if not one_way:
request.unique_id = self._get_unique_id()
request.method = method
request.args = args
request.kwargs = kwargs
return request
def parse_reply(self, data):
if six.PY3 and isinstance(data, bytes):
# zmq won't accept unicode strings, and this is the other
# end; decoding non-unicode strings back into unicode
data = data.decode()
try:
rep = json.loads(data)
except Exception as e:
raise InvalidReplyError(e)
for k in six.iterkeys(rep):
if not k in self._ALLOWED_REPLY_KEYS:
raise InvalidReplyError('Key not allowed: %s' % k)
if not 'jsonrpc' in rep:
raise InvalidReplyError('Missing jsonrpc (version) in response.')
if rep['jsonrpc'] != self.JSON_RPC_VERSION:
raise InvalidReplyError('Wrong JSONRPC version')
if not 'id' in rep:
raise InvalidReplyError('Missing id in response')
if ('error' in rep) == ('result' in rep):
raise InvalidReplyError(
'Reply must contain exactly one of result and error.'
)
if 'error' in rep:
response = JSONRPCErrorResponse()
error = rep['error']
response.error = error['message']
response._jsonrpc_error_code = error['code']
else:
response = JSONRPCSuccessResponse()
response.result = rep.get('result', None)
response.unique_id = rep['id']
return response
def parse_request(self, data):
if six.PY3 and isinstance(data, bytes):
# zmq won't accept unicode strings, and this is the other
# end; decoding non-unicode strings back into unicode
data = data.decode()
try:
req = json.loads(data)
except Exception as e:
raise JSONRPCParseError()
if isinstance(req, list):
# batch request
requests = JSONRPCBatchRequest()
for subreq in req:
try:
requests.append(self._parse_subrequest(subreq))
except RPCError as e:
requests.append(e)
except Exception as e:
requests.append(JSONRPCInvalidRequestError())
if not requests:
raise JSONRPCInvalidRequestError()
return requests
else:
return self._parse_subrequest(req)
def _parse_subrequest(self, req):
for k in six.iterkeys(req):
if not k in self._ALLOWED_REQUEST_KEYS:
raise JSONRPCInvalidRequestError()
if req.get('jsonrpc', None) != self.JSON_RPC_VERSION:
raise JSONRPCInvalidRequestError()
if not isinstance(req['method'], six.string_types):
raise JSONRPCInvalidRequestError()
request = JSONRPCRequest()
request.method = str(req['method'])
request.unique_id = req.get('id', None)
params = req.get('params', None)
if params != None:
if isinstance(params, list):
request.args = req['params']
elif isinstance(params, dict):
request.kwargs = req['params']
else:
raise JSONRPCInvalidParamsError()
return request
def _caller(self, method, args, kwargs):
# custom dispatcher called by RPCDispatcher._dispatch()
# when provided with the address of a custom dispatcher.
# Used to generate a customized error message when the
# function signature doesn't match the parameter list.
try:
inspect.getcallargs(method, *args, **kwargs)
except TypeError:
raise JSONRPCInvalidParamsError()
else:
return method(*args, **kwargs)
|