Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/_parsers/hiredis.py: 23%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

224 statements  

1import select 

2import selectors 

3import socket 

4from logging import getLogger 

5from typing import Callable, List, Optional, TypedDict, Union 

6 

7from ..exceptions import ConnectionError, InvalidResponse, RedisError, TimeoutError 

8from ..typing import EncodableT 

9from ..utils import ( 

10 HIREDIS_AVAILABLE, 

11 SENTINEL, 

12 deprecated_function, 

13 is_os_level_timeout, 

14) 

15from .base import ( 

16 AsyncBaseParser, 

17 AsyncPushNotificationsParser, 

18 BaseParser, 

19 PushNotificationsParser, 

20) 

21from .socket import ( 

22 NONBLOCKING_EXCEPTION_ERROR_NUMBERS, 

23 NONBLOCKING_EXCEPTIONS, 

24 SERVER_CLOSED_CONNECTION_ERROR, 

25) 

26 

27# Used to signal that hiredis-py does not have enough data to parse. 

28# Using `False` or `None` is not reliable, given that the parser can 

29# return `False` or `None` for legitimate reasons from RESP payloads. 

30NOT_ENOUGH_DATA = object() 

31 

32# select.poll() is unavailable on Windows; fall back to selectors there. 

33_HAS_POLL = hasattr(select, "poll") 

34 

35# POLLRDHUP (Linux) reports a peer half-close (FIN) that POLLHUP does not cover. 

36# It is absent on macOS/Windows, where 0 turns the masks that use it into no-ops. 

37_POLLRDHUP = getattr(select, "POLLRDHUP", 0) 

38 

39 

40def _socket_can_read(sock, timeout: float) -> bool: 

41 # SSL sockets can have decrypted bytes buffered above the OS socket layer. 

42 if hasattr(sock, "pending") and sock.pending(): 

43 return True 

44 # timeout=0 must be a non-blocking readiness check only; both branches 

45 # below are non-destructive and have no FD_SETSIZE limit (select.select 

46 # raises ValueError for fds >= 1024). 

47 if _HAS_POLL: 

48 # Prefer poll() over selectors.DefaultSelector: epoll/kqueue selectors 

49 # allocate a file descriptor per check and so fail with EMFILE under 

50 # fd exhaustion - the very condition that pushes sockets onto high 

51 # fds. poll() allocates nothing. 

52 poller = select.poll() 

53 poller.register(sock, select.POLLIN) 

54 # poll() takes milliseconds (None blocks forever). POLLHUP/POLLERR/ 

55 # POLLNVAL are always reported regardless of the registered mask, so 

56 # closed or errored sockets still count as readable, like select(). 

57 poll_timeout = None if timeout is None else timeout * 1000 

58 return bool(poller.poll(poll_timeout)) 

59 with selectors.DefaultSelector() as selector: 

60 selector.register(sock, selectors.EVENT_READ) 

61 return bool(selector.select(timeout)) 

62 

63 

64def _socket_is_closed(sock) -> bool: 

65 # A server-closed socket reads as ready (it yields EOF), so readiness alone 

66 # cannot tell it apart from a socket holding pending data, and both checks 

67 # here are non-destructive so pending push messages (e.g. cache 

68 # invalidations) are left intact to be processed. Without poll() the two 

69 # states are indistinguishable, so report not-closed. 

70 if not _HAS_POLL: 

71 return False 

72 # Decrypted TLS bytes buffered above the OS socket layer must be processed 

73 # before the connection can be treated as closed, like kernel-level data. 

74 if hasattr(sock, "pending") and sock.pending(): 

75 return False 

76 poller = select.poll() 

77 poller.register(sock, select.POLLIN | _POLLRDHUP) 

78 events = poller.poll(0) 

79 if not events: 

80 return False 

81 _, revents = events[0] 

82 # A readable socket holds either data or EOF, and the poll flags alone 

83 # cannot always tell which: POLLHUP/POLLRDHUP can be reported while unread 

84 # data is still buffered (the peer sent data, then closed), and a drained 

85 # closed socket reports plain POLLIN where POLLRDHUP is unavailable 

86 # (PyPy). A non-destructive MSG_PEEK settles it: EOF peeks as b"". 

87 try: 

88 return sock.recv(1, socket.MSG_PEEK) == b"" 

89 except NONBLOCKING_EXCEPTIONS: 

90 # Transient would-block: data may still arrive, keep the connection. 

91 return False 

92 except ValueError: 

93 # SSL sockets do not support recv() flags; their buffered plaintext is 

94 # covered by the pending() check above, so fall back to the poll 

95 # flags. POLLRDHUP must be in the register mask or poll() won't 

96 # report it: on Linux a graceful FIN reports POLLIN|POLLRDHUP and 

97 # never POLLHUP. macOS/Windows set POLLHUP instead (_POLLRDHUP is 0). 

98 closed_flags = select.POLLHUP | select.POLLERR | select.POLLNVAL | _POLLRDHUP 

99 return bool(revents & closed_flags) 

100 except OSError: 

101 # The socket is errored (POLLERR/POLLNVAL); nothing left to read. 

102 return True 

103 

104 

105class _HiredisReaderArgs(TypedDict, total=False): 

106 protocolError: Callable[[str], Exception] 

107 replyError: Callable[[str], Exception] 

108 encoding: Optional[str] 

109 errors: Optional[str] 

110 

111 

112class _HiredisParser(BaseParser, PushNotificationsParser): 

113 "Parser class for connections using Hiredis" 

114 

115 def __init__(self, socket_read_size): 

116 if not HIREDIS_AVAILABLE: 

117 raise RedisError("Hiredis is not installed") 

118 self.socket_read_size = socket_read_size 

119 self._buffer = bytearray(socket_read_size) 

120 self.pubsub_push_handler_func = self.handle_pubsub_push_response 

121 self.node_moving_push_handler_func = None 

122 self.maintenance_push_handler_func = None 

123 self.oss_cluster_maint_push_handler_func = None 

124 self.invalidation_push_handler_func = None 

125 self._hiredis_PushNotificationType = None 

126 

127 def __del__(self): 

128 try: 

129 self.on_disconnect() 

130 except Exception: 

131 pass 

132 

133 def handle_pubsub_push_response(self, response): 

134 logger = getLogger("push_response") 

135 logger.debug("Push response: %s", response) 

136 return response 

137 

138 def on_connect(self, connection, **kwargs): 

139 import hiredis 

140 

141 self._sock = connection._sock 

142 self._socket_timeout = connection.socket_timeout 

143 kwargs = { 

144 "protocolError": InvalidResponse, 

145 "replyError": self.parse_error, 

146 "errors": connection.encoder.encoding_errors, 

147 "notEnoughData": NOT_ENOUGH_DATA, 

148 } 

149 

150 if connection.encoder.decode_responses: 

151 kwargs["encoding"] = connection.encoder.encoding 

152 self._reader = hiredis.Reader(**kwargs) 

153 

154 try: 

155 self._hiredis_PushNotificationType = hiredis.PushNotification 

156 except AttributeError: 

157 # hiredis < 3.2 

158 self._hiredis_PushNotificationType = None 

159 

160 def on_disconnect(self): 

161 self._sock = None 

162 self._reader = None 

163 

164 def can_read(self, timeout: float = 0) -> bool: 

165 # TODO: Rename this API; it detects pending data or dirty/closed 

166 # connection state, not only whether application data can be read. 

167 reader = self._reader 

168 sock = self._sock 

169 # Another thread may disconnect this connection while we are here (e.g. 

170 # the multi-database health check taking a database out of service); 

171 # on_disconnect() sets both _sock and _reader to None. Bind them locally 

172 # so the checks below cannot disagree about the connection, and fail with 

173 # a descriptive, retryable ConnectionError instead of a TypeError from 

174 # registering None with poll(). 

175 if reader is None or sock is None: 

176 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

177 

178 if reader.has_data(): 

179 return True 

180 try: 

181 if not _socket_can_read(sock, timeout): 

182 return False 

183 # the socket reports readable but the reader has no buffered data. a 

184 # server-closed socket also reads as ready (it yields EOF), so tell the 

185 # two apart with a non-destructive poll: a peer-closed socket must not be 

186 # reused, while a readable-but-open socket may just hold a pending push. 

187 # this mirrors how the pure-Python parser (recv -> b"") and the async 

188 # parser (StreamReader.at_eof()) already signal a closed connection. 

189 if _socket_is_closed(sock): 

190 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

191 except ValueError: 

192 # Same race as above, one step later: a concurrent disconnect closed 

193 # the socket, so its file descriptor is -1 and neither poll() nor a 

194 # selector can register it. The connection is gone either way. 

195 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None 

196 return True 

197 

198 def read_from_socket(self, timeout=SENTINEL, raise_on_timeout=True): 

199 sock = self._sock 

200 reader = self._reader 

201 # Another thread may disconnect this connection while we are here (e.g. 

202 # a shared client closed via `with redis:`); on_disconnect() sets both 

203 # _sock and _reader to None. Bind them locally and fail with a 

204 # descriptive, retryable ConnectionError instead of an AttributeError. 

205 if sock is None or reader is None: 

206 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

207 custom_timeout = timeout is not SENTINEL 

208 try: 

209 if custom_timeout: 

210 sock.settimeout(timeout) 

211 bufflen = sock.recv_into(self._buffer) 

212 if bufflen == 0: 

213 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

214 reader.feed(self._buffer, 0, bufflen) 

215 # data was read from the socket and added to the buffer. 

216 # return True to indicate that data was read. 

217 return True 

218 except socket.timeout as e: 

219 if is_os_level_timeout(e): 

220 # ETIMEDOUT from the OS (e.g. after a network change): the 

221 # connection is dead, not slow. Reporting it as a timeout - or 

222 # as "no data" when polling - would hide a broken connection. 

223 raise ConnectionError(f"Error while reading from socket: {e.args}") 

224 if raise_on_timeout: 

225 raise TimeoutError("Timeout reading from socket") 

226 return False 

227 except NONBLOCKING_EXCEPTIONS as ex: 

228 # if we're in nonblocking mode and the recv raises a 

229 # blocking error, simply return False indicating that 

230 # there's no data to be read. otherwise raise the 

231 # original exception. 

232 allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1) 

233 if ex.errno == allowed: 

234 if not raise_on_timeout: 

235 return False 

236 if timeout == 0: 

237 raise TimeoutError("Timeout reading from socket") 

238 raise ConnectionError(f"Error while reading from socket: {ex.args}") 

239 finally: 

240 if custom_timeout: 

241 try: 

242 sock.settimeout(self._socket_timeout) 

243 except OSError: 

244 # A disconnect from another thread closes the socket, so there 

245 # is nothing left to restore the timeout on. An exception from 

246 # here would replace the outcome the body reported - including 

247 # the retryable ConnectionError above - with EBADF. 

248 pass 

249 

250 def read_response( 

251 self, 

252 disable_decoding=False, 

253 push_request=False, 

254 timeout: Union[float, object] = SENTINEL, 

255 ): 

256 while True: 

257 # Bind the reader locally so a concurrent disconnect that clears 

258 # self._reader can't turn a later .gets() into an AttributeError; 

259 # re-checking the attribute each time would still race. It is 

260 # re-bound per frame because a push handler may have disconnected. 

261 reader = self._reader 

262 if reader is None: 

263 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

264 

265 if disable_decoding: 

266 response = reader.gets(False) 

267 else: 

268 response = reader.gets() 

269 

270 while response is NOT_ENOUGH_DATA: 

271 self.read_from_socket(timeout=timeout) 

272 if disable_decoding: 

273 response = reader.gets(False) 

274 else: 

275 response = reader.gets() 

276 if self._hiredis_PushNotificationType is None or not isinstance( 

277 response, self._hiredis_PushNotificationType 

278 ): 

279 break 

280 response = self.handle_push_response(response) 

281 if push_request: 

282 return response 

283 # Otherwise read the reply the push interleaved with. Looping 

284 # instead of recursing keeps a burst of consecutive push frames 

285 # from growing the stack. 

286 # if the response is a ConnectionError or the response is a list and 

287 # the first item is a ConnectionError, raise it as something bad 

288 # happened 

289 if isinstance(response, ConnectionError): 

290 raise response 

291 elif ( 

292 isinstance(response, list) 

293 and response 

294 and isinstance(response[0], ConnectionError) 

295 ): 

296 raise response[0] 

297 return response 

298 

299 

300class _AsyncHiredisParser(AsyncBaseParser, AsyncPushNotificationsParser): 

301 """Async implementation of parser class for connections using Hiredis""" 

302 

303 __slots__ = ("_reader",) 

304 

305 def __init__(self, socket_read_size: int): 

306 if not HIREDIS_AVAILABLE: 

307 raise RedisError("Hiredis is not available.") 

308 super().__init__(socket_read_size=socket_read_size) 

309 self._reader = None 

310 self.pubsub_push_handler_func = self.handle_pubsub_push_response 

311 self.invalidation_push_handler_func = None 

312 self._hiredis_PushNotificationType = None 

313 

314 async def handle_pubsub_push_response(self, response): 

315 logger = getLogger("push_response") 

316 logger.debug("Push response: %s", response) 

317 return response 

318 

319 def on_connect(self, connection): 

320 import hiredis 

321 

322 self._stream = connection._reader 

323 kwargs: _HiredisReaderArgs = { 

324 "protocolError": InvalidResponse, 

325 "replyError": self.parse_error, 

326 "notEnoughData": NOT_ENOUGH_DATA, 

327 } 

328 if connection.encoder.decode_responses: 

329 kwargs["encoding"] = connection.encoder.encoding 

330 kwargs["errors"] = connection.encoder.encoding_errors 

331 

332 self._reader = hiredis.Reader(**kwargs) 

333 self._connected = True 

334 

335 try: 

336 self._hiredis_PushNotificationType = getattr( 

337 hiredis, "PushNotification", None 

338 ) 

339 except AttributeError: 

340 # hiredis < 3.2 

341 self._hiredis_PushNotificationType = None 

342 

343 def on_disconnect(self): 

344 self._connected = False 

345 

346 @deprecated_function( 

347 version="8.0.0", reason="Use can_read() instead", name="can_read_destructive" 

348 ) 

349 async def can_read_destructive(self) -> bool: 

350 return await self.can_read() 

351 

352 async def can_read(self) -> bool: 

353 # TODO: Rename this API; it detects pending data or dirty/closed 

354 # connection state, not only whether application data can be read. 

355 if not self._connected: 

356 raise OSError("Buffer is closed.") 

357 # buffered data wins over EOF, like the sync parser: a pending 

358 # response or push notification must stay readable even if the 

359 # server has since closed the connection. 

360 if self._reader.has_data(): 

361 return True 

362 if self._stream.at_eof() or self._stream.exception() is not None: 

363 # Raise like the sync parser does on a server-closed connection, 

364 # so callers that tolerate pending data (push notifications) 

365 # can't mistake EOF for a readable connection. 

366 # A reset (RST) leaves no EOF but an exception on the stream. 

367 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

368 # asyncio.StreamReader has no public non-destructive API for checking 

369 # buffered bytes. Preserve dirty-connection detection for hiredis; tests 

370 # with a real StreamReader guard this private buffer API in CI. 

371 return bool(self._stream._buffer) 

372 

373 async def read_from_socket(self): 

374 buffer = await self._stream.read(self._read_size) 

375 if not buffer or not isinstance(buffer, bytes): 

376 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None 

377 self._reader.feed(buffer) 

378 # data was read from the socket and added to the buffer. 

379 # return True to indicate that data was read. 

380 return True 

381 

382 async def read_response( 

383 self, disable_decoding: bool = False, push_request: bool = False 

384 ) -> Union[EncodableT, List[EncodableT]]: 

385 while True: 

386 # If `on_disconnect()` has been called, prohibit any more reads 

387 # even if they could happen because data might be present. 

388 # We still allow reads in progress to finish 

389 if not self._connected: 

390 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from None 

391 

392 if disable_decoding: 

393 response = self._reader.gets(False) 

394 else: 

395 response = self._reader.gets() 

396 

397 while response is NOT_ENOUGH_DATA: 

398 await self.read_from_socket() 

399 if disable_decoding: 

400 response = self._reader.gets(False) 

401 else: 

402 response = self._reader.gets() 

403 if self._hiredis_PushNotificationType is None or not isinstance( 

404 response, self._hiredis_PushNotificationType 

405 ): 

406 break 

407 response = await self.handle_push_response(response) 

408 if push_request: 

409 return response 

410 # Otherwise read the reply the push interleaved with. Looping 

411 # instead of recursing keeps a burst of consecutive push frames 

412 # from growing the stack. 

413 

414 # if the response is a ConnectionError or the response is a list and 

415 # the first item is a ConnectionError, raise it as something bad 

416 # happened 

417 if isinstance(response, ConnectionError): 

418 raise response 

419 elif ( 

420 isinstance(response, list) 

421 and response 

422 and isinstance(response[0], ConnectionError) 

423 ): 

424 raise response[0] 

425 return response