-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathresponse.py
400 lines (310 loc) · 10.6 KB
/
response.py
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# pylint: disable=C0301,W0105,W0401,W0614
"""
Request response types definitions.
"""
from collections.abc import Sequence
import json
import msgpack
from tarantool.const import (
IPROTO_REQUEST_TYPE,
IPROTO_DATA,
IPROTO_ERROR_24,
IPROTO_ERROR,
IPROTO_SYNC,
IPROTO_SCHEMA_ID,
REQUEST_TYPE_ERROR,
IPROTO_SQL_INFO,
IPROTO_SQL_INFO_ROW_COUNT,
IPROTO_SQL_INFO_AUTOINCREMENT_IDS,
IPROTO_VERSION,
IPROTO_FEATURES,
IPROTO_AUTH_TYPE,
)
from tarantool.types import decode_box_error
from tarantool.error import (
DatabaseError,
InterfaceError,
SchemaReloadException,
tnt_strerror
)
from tarantool.msgpack_ext.unpacker import ext_hook as unpacker_ext_hook
def unpacker_factory(conn):
"""
Build unpacker to unpack request response.
:param conn: Request sender.
:type conn: :class:`~tarantool.Connection`
:rtype: :class:`msgpack.Unpacker`
"""
unpacker_kwargs = dict()
# Decode MsgPack arrays into Python lists by default (not tuples).
# Can be configured in the Connection init
unpacker_kwargs['use_list'] = conn.use_list
# Use raw=False instead of encoding='utf-8'.
if msgpack.version >= (0, 5, 2) and conn.encoding == 'utf-8':
# Get rid of the following warning.
# > PendingDeprecationWarning: encoding is deprecated,
# > Use raw=False instead.
unpacker_kwargs['raw'] = False
elif conn.encoding is not None:
unpacker_kwargs['encoding'] = conn.encoding
# raw=False is default since msgpack-1.0.0.
#
# The option decodes mp_str to bytes, not a Unicode
# string (when True).
if msgpack.version >= (1, 0, 0) and conn.encoding is None:
unpacker_kwargs['raw'] = True
# encoding option is not supported since msgpack-1.0.0,
# but it is handled in the Connection constructor.
assert(msgpack.version < (1, 0, 0) or conn.encoding in (None, 'utf-8'))
# strict_map_key=True is default since msgpack-1.0.0.
#
# The option forbids non-string keys in a map (when True).
if msgpack.version >= (1, 0, 0):
unpacker_kwargs['strict_map_key'] = False
# We need configured unpacker to work with error extention
# type payload, but module do not provide access to self
# inside extension type unpackers.
unpacker_no_ext = msgpack.Unpacker(**unpacker_kwargs)
ext_hook = lambda code, data: unpacker_ext_hook(code, data, unpacker_no_ext)
unpacker_kwargs['ext_hook'] = ext_hook
return msgpack.Unpacker(**unpacker_kwargs)
class Response(Sequence):
"""
Represents a single response from the server in compliance with the
Tarantool protocol. Responsible for data encapsulation (i.e.
received list of tuples) and parsing of binary packets received from
the server.
"""
def __init__(self, conn, response):
"""
:param conn: Request sender.
:type conn: :class:`~tarantool.Connection`
:param response: Response binary data.
:type response: :obj:`bytes`
:raise: :exc:`~tarantool.error.DatabaseError`,
:exc:`~tarantool.error.SchemaReloadException`
"""
# This is not necessary, because underlying list data structures are
# created in the __new__().
# super(Response, self).__init__()
unpacker = conn._unpacker_factory()
unpacker.feed(response)
header = unpacker.unpack()
self.conn = conn
self._sync = header.get(IPROTO_SYNC, 0)
self._code = header[IPROTO_REQUEST_TYPE]
self._body = {}
self._schema_version = header.get(IPROTO_SCHEMA_ID, None)
try:
self._body = unpacker.unpack()
except msgpack.OutOfData:
pass
if self._code < REQUEST_TYPE_ERROR:
self._return_code = 0
self._schema_version = header.get(IPROTO_SCHEMA_ID, None)
self._data = self._body.get(IPROTO_DATA, None)
if (not isinstance(self._data, (list, tuple)) and
self._data is not None):
self._data = [self._data]
# # Backward-compatibility
# if isinstance(self._data, (list, tuple)):
# self.extend(self._data)
# else:
# self.append(self._data)
else:
# Separate return_code and completion_code
self._return_message = self._body.get(IPROTO_ERROR_24, "")
self._return_code = self._code & (REQUEST_TYPE_ERROR - 1)
self._return_error = None
return_error_map = self._body.get(IPROTO_ERROR)
if return_error_map is not None:
self._return_error = decode_box_error(return_error_map)
self._data = []
if self._return_code == 109:
raise SchemaReloadException(self._return_message,
self._schema_version)
if self.conn.error:
raise DatabaseError(self._return_code,
self._return_message,
extra_info=self._return_error)
def __getitem__(self, idx):
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return self._data.__getitem__(idx)
def __len__(self):
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return len(self._data)
def __contains__(self, item):
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return item in self._data
def __iter__(self):
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return iter(self._data)
def __reversed__(self):
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return reversed(self._data)
def index(self, *args):
"""
Refer to :class:`collections.abc.Sequence`.
:raises: :exc:`~tarantool.error.InterfaceError.`
"""
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return self._data.index(*args)
def count(self, item):
"""
Refer to :class:`collections.abc.Sequence`.
:raises: :exc:`~tarantool.error.InterfaceError`
"""
if self._data is None:
raise InterfaceError("Trying to access data when there's no data")
return self._data.count(item)
@property
def rowcount(self):
"""
:type: :obj:`int`
Number of rows affected or returned by a query.
"""
return len(self)
@property
def body(self):
"""
:type: :obj:`dict`
Raw response body.
"""
return self._body
@property
def code(self):
"""
:type: :obj:`int`
Response type id.
"""
return self._code
@property
def sync(self):
"""
:type: :obj:`int`
Response header IPROTO_SYNC.
"""
return self._sync
@property
def return_code(self):
"""
:type: :obj:`int`
If the request was successful, the value of is ``0``.
Otherwise, it contains an error code. If the value is non-zero,
:attr:`return_message` contains an error message.
"""
return self._return_code
@property
def data(self):
"""
:type: :obj:`object`
Contains the list of tuples for SELECT, REPLACE and DELETE
requests and arbitrary data for CALL.
"""
return self._data
@property
def strerror(self):
"""
Refer to :func:`~tarantool.error.tnt_strerror`.
"""
return tnt_strerror(self._return_code)
@property
def return_message(self):
"""
:type: :obj:`str`
The error message returned by the server in case of non-zero
:attr:`return_code` (empty string otherwise).
"""
return self._return_message
@property
def schema_version(self):
"""
:type: :obj:`int`
Request current schema version.
"""
return self._schema_version
def __str__(self):
if self.return_code:
return json.dumps({
'error': {
'code': self.strerror[0],
'reason': self.return_message
}
}, sort_keys = True, indent = 4, separators=(', ', ': '))
output = []
for tpl in self._data or ():
output.extend(("- ", repr(tpl), "\n"))
if len(output) > 0:
output.pop()
return ''.join(output)
__repr__ = __str__
class ResponseExecute(Response):
"""
Represents an SQL EXECUTE request response.
"""
@property
def autoincrement_ids(self):
"""
A list with the new primary-key value (or values) for an
INSERT in a table defined with PRIMARY KEY AUTOINCREMENT (NOT
result set size).
:rtype: :obj:`list` or :obj:`None`
"""
if self._return_code != 0:
return None
info = self._body.get(IPROTO_SQL_INFO)
if info is None:
return None
autoincrement_ids = info.get(IPROTO_SQL_INFO_AUTOINCREMENT_IDS)
return autoincrement_ids
@property
def affected_row_count(self):
"""
The number of changed rows for responses to DML requests and
``None`` for DQL requests.
:rtype: :obj:`int` or :obj:`None`
"""
if self._return_code != 0:
return None
info = self._body.get(IPROTO_SQL_INFO)
if info is None:
return None
return info.get(IPROTO_SQL_INFO_ROW_COUNT)
class ResponseProtocolVersion(Response):
"""
Represents an ID request response: information about server protocol
version and features it supports.
"""
@property
def protocol_version(self):
"""
Server protocol version.
:rtype: :obj:`int` or :obj:`None`
"""
if self._return_code != 0:
return None
return self._body.get(IPROTO_VERSION)
@property
def features(self):
"""
Server supported features.
:rtype: :obj:`list`
"""
if self._return_code != 0:
return []
return self._body.get(IPROTO_FEATURES)
@property
def auth_type(self):
"""
Server expected authentication method.
:rtype: :obj:`str` or :obj:`None`
"""
if self._return_code != 0:
return None
return self._body.get(IPROTO_AUTH_TYPE)