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

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

294 statements  

1import logging 

2import re 

3from abc import ABC, abstractmethod 

4from asyncio import IncompleteReadError, StreamReader 

5from typing import Awaitable, Callable, List, Optional, Protocol, Union 

6 

7from redis.maint_notifications import ( 

8 MaintenanceNotification, 

9 NodeFailedOverNotification, 

10 NodeFailingOverNotification, 

11 NodeMigratedNotification, 

12 NodeMigratingNotification, 

13 NodeMovingNotification, 

14 OSSNodeMigratedNotification, 

15 OSSNodeMigratingNotification, 

16) 

17from redis.utils import deprecated_function, safe_str 

18 

19from ..exceptions import ( 

20 AskError, 

21 AuthenticationError, 

22 AuthenticationWrongNumberOfArgsError, 

23 BusyLoadingError, 

24 ClusterCrossSlotError, 

25 ClusterDownError, 

26 ConnectionError, 

27 ExecAbortError, 

28 ExternalAuthProviderError, 

29 InvalidResponse, 

30 MasterDownError, 

31 MaxClientsReachedError, 

32 ModuleError, 

33 MovedError, 

34 NoPermissionError, 

35 NoScriptError, 

36 NoSuchFieldsetError, 

37 OutOfMemoryError, 

38 ReadOnlyError, 

39 ResponseError, 

40 TryAgainError, 

41) 

42from ..typing import EncodableT 

43from .encoders import Encoder 

44from .socket import SERVER_CLOSED_CONNECTION_ERROR, SocketBuffer 

45 

46# Errors a parser can raise from the middle of a reply, after the read cursor 

47# has already advanced past bytes the parser cannot re-interpret. The resume 

48# machinery from #2510/#2695 rewinds so an *interrupted* read can be re-parsed 

49# from the start; it cannot help here, because re-parsing the same bytes just 

50# reproduces the same failure. Connection.read_response drops the connection on 

51# these regardless of disconnect_on_error, or the caller loops forever (#4291). 

52# 

53# - InvalidResponse: unknown reply type byte, or hiredis' own nesting limit. 

54# - UnicodeDecodeError: Encoder.decode at the tail of _read_response, reached 

55# only after the payload has been consumed (decode_responses=True subscriber 

56# receiving a binary PUBLISH payload). 

57# - RecursionError: deeply nested aggregate replies exhaust the stack in the 

58# pure-Python parsers. #4144 turns this into InvalidResponse at a bounded 

59# depth; until then, catching it here is what stops the loop. 

60# 

61# Malformed numeric frames (`:abc\r\n`, `$xyz\r\n`, `*abc\r\n`) are converted to 

62# InvalidResponse by the pure-Python parsers (_parse_int/_parse_float below), so 

63# they land here too. Plain ValueError is deliberately NOT in this tuple: a 

64# user push handler may raise it after the frame was fully consumed, and that 

65# must not tear down a healthy connection. 

66UNRECOVERABLE_PARSE_ERRORS = (InvalidResponse, UnicodeDecodeError, RecursionError) 

67 

68 

69def _parse_int(value: bytes, raw: bytes) -> int: 

70 """int() for a RESP numeric field; a non-numeric field is a protocol error.""" 

71 try: 

72 return int(value) 

73 except ValueError: 

74 raise InvalidResponse(f"Protocol Error: {raw!r}") from None 

75 

76 

77def _parse_float(value: bytes, raw: bytes) -> float: 

78 try: 

79 return float(value) 

80 except ValueError: 

81 raise InvalidResponse(f"Protocol Error: {raw!r}") from None 

82 

83 

84MODULE_LOAD_ERROR = "Error loading the extension. Please check the server logs." 

85NO_SUCH_MODULE_ERROR = "Error unloading module: no such module with that name" 

86MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not possible." 

87MODULE_EXPORTS_DATA_TYPES_ERROR = ( 

88 "Error unloading module: the module " 

89 "exports one or more module-side data " 

90 "types, can't unload" 

91) 

92# user send an AUTH cmd to a server without authorization configured 

93NO_AUTH_SET_ERROR = { 

94 # Redis >= 6.0 

95 "AUTH <password> called without any password " 

96 "configured for the default user. Are you sure " 

97 "your configuration is correct?": AuthenticationError, 

98 # Redis < 6.0 

99 "Client sent AUTH, but no password is set": AuthenticationError, 

100} 

101 

102EXTERNAL_AUTH_PROVIDER_ERROR = { 

103 "problem with LDAP service": ExternalAuthProviderError, 

104} 

105 

106# HIMPORT SET referencing a fieldset the connection has not prepared. The server 

107# reply is a fixed message with no fieldset name appended (verified against the 

108# server: always exactly ``ERR no such fieldset``), so an exact match is correct. 

109NO_SUCH_FIELDSET_ERROR = { 

110 "no such fieldset": NoSuchFieldsetError, 

111} 

112 

113# The code a Redis error reply starts with (ERR, WRONGTYPE, NOGROUP, and module 

114# codes such as SEARCH_SYNTAX). An unmapped error keeps its first word as the 

115# status code only in this shape, so free-form messages such as "Syntax error at 

116# offset 3" don't become one. 

117_ERROR_CODE_PATTERN = re.compile(r"[A-Z][A-Z0-9_]{0,63}") 

118 

119logger = logging.getLogger(__name__) 

120 

121 

122class BaseParser(ABC): 

123 EXCEPTION_CLASSES = { 

124 "ERR": { 

125 "max number of clients reached": MaxClientsReachedError, 

126 "invalid password": AuthenticationError, 

127 # some Redis server versions report invalid command syntax 

128 # in lowercase 

129 "wrong number of arguments " 

130 "for 'auth' command": AuthenticationWrongNumberOfArgsError, 

131 # some Redis server versions report invalid command syntax 

132 # in uppercase 

133 "wrong number of arguments " 

134 "for 'AUTH' command": AuthenticationWrongNumberOfArgsError, 

135 MODULE_LOAD_ERROR: ModuleError, 

136 MODULE_EXPORTS_DATA_TYPES_ERROR: ModuleError, 

137 NO_SUCH_MODULE_ERROR: ModuleError, 

138 MODULE_UNLOAD_NOT_POSSIBLE_ERROR: ModuleError, 

139 **NO_AUTH_SET_ERROR, 

140 **EXTERNAL_AUTH_PROVIDER_ERROR, 

141 **NO_SUCH_FIELDSET_ERROR, 

142 }, 

143 "OOM": OutOfMemoryError, 

144 "WRONGPASS": AuthenticationError, 

145 "EXECABORT": ExecAbortError, 

146 "LOADING": BusyLoadingError, 

147 "NOSCRIPT": NoScriptError, 

148 "READONLY": ReadOnlyError, 

149 "NOAUTH": AuthenticationError, 

150 "NOPERM": NoPermissionError, 

151 "ASK": AskError, 

152 "TRYAGAIN": TryAgainError, 

153 "MOVED": MovedError, 

154 "CLUSTERDOWN": ClusterDownError, 

155 "CROSSSLOT": ClusterCrossSlotError, 

156 "MASTERDOWN": MasterDownError, 

157 } 

158 

159 @classmethod 

160 def parse_error(cls, response): 

161 "Parse an error response" 

162 error_code = response.split(" ")[0] 

163 if error_code in cls.EXCEPTION_CLASSES: 

164 response = response[len(error_code) + 1 :] 

165 exception_class = cls.EXCEPTION_CLASSES[error_code] 

166 if isinstance(exception_class, dict): 

167 exception_class = exception_class.get(response, ResponseError) 

168 return exception_class(response, status_code=error_code) 

169 status_code = error_code if _ERROR_CODE_PATTERN.fullmatch(error_code) else None 

170 return ResponseError(response, status_code=status_code) 

171 

172 @abstractmethod 

173 def on_disconnect(self): 

174 pass 

175 

176 @abstractmethod 

177 def on_connect(self, connection): 

178 pass 

179 

180 

181class _RESPBase(BaseParser): 

182 """Base class for sync-based resp parsing""" 

183 

184 def __init__(self, socket_read_size): 

185 self.socket_read_size = socket_read_size 

186 self.encoder = None 

187 self._sock = None 

188 self._buffer = None 

189 

190 def __del__(self): 

191 try: 

192 self.on_disconnect() 

193 except Exception: 

194 pass 

195 

196 def on_connect(self, connection): 

197 "Called when the socket connects" 

198 self._sock = connection._sock 

199 self._buffer = SocketBuffer( 

200 self._sock, self.socket_read_size, connection.socket_timeout 

201 ) 

202 self.encoder = connection.encoder 

203 

204 def on_disconnect(self): 

205 "Called when the socket disconnects" 

206 self._sock = None 

207 if self._buffer is not None: 

208 self._buffer.close() 

209 self._buffer = None 

210 self.encoder = None 

211 

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

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

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

215 if self._buffer is None: 

216 return False 

217 return self._buffer.can_read(timeout) 

218 

219 

220class AsyncBaseParser(BaseParser): 

221 """Base parsing class for the python-backed async parser""" 

222 

223 __slots__ = "_stream", "_read_size", "_connected" 

224 

225 def __init__(self, socket_read_size: int): 

226 self._stream: Optional[StreamReader] = None 

227 self._read_size = socket_read_size 

228 # Initialized here, not only in on_connect() / on_disconnect(): the 

229 # read guards in can_read() and the subclasses' read_response() consult 

230 # this flag to turn a read on a dead connection into a retryable 

231 # ConnectionError. A parser that has never connected would otherwise 

232 # raise AttributeError from those guards, which no retry layer acts on. 

233 self._connected: bool = False 

234 

235 @deprecated_function( 

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

237 ) 

238 @abstractmethod 

239 async def can_read_destructive(self) -> bool: 

240 pass 

241 

242 @abstractmethod 

243 async def can_read(self) -> bool: 

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

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

246 pass 

247 

248 async def read_response( 

249 self, disable_decoding: bool = False 

250 ) -> Union[EncodableT, ResponseError, None, List[EncodableT]]: 

251 raise NotImplementedError() 

252 

253 

254class MaintenanceNotificationsParser: 

255 """Protocol defining maintenance push notification parsing functionality""" 

256 

257 @staticmethod 

258 def parse_oss_maintenance_start_msg(response): 

259 # Expected message format is: 

260 # SMIGRATING <seq_number> <slot, range1-range2,...> 

261 id = response[1] 

262 slots = safe_str(response[2]) 

263 return OSSNodeMigratingNotification(id, slots) 

264 

265 @staticmethod 

266 def parse_oss_maintenance_completed_msg(response): 

267 # Expected message format is: 

268 # SMIGRATED <seq_number> [[<src_host:port> <dest_host:port> <slot_range>], ...] 

269 id = response[1] 

270 nodes_to_slots_mapping_data = response[2] 

271 # Build the nodes_to_slots_mapping dict structure: 

272 # { 

273 # "src_host:port": [ 

274 # {"dest_host:port": "slot_range"}, 

275 # ... 

276 # ], 

277 # ... 

278 # } 

279 nodes_to_slots_mapping = {} 

280 for src_node, dest_node, slots in nodes_to_slots_mapping_data: 

281 src_node_str = safe_str(src_node) 

282 dest_node_str = safe_str(dest_node) 

283 slots_str = safe_str(slots) 

284 

285 if src_node_str not in nodes_to_slots_mapping: 

286 nodes_to_slots_mapping[src_node_str] = [] 

287 nodes_to_slots_mapping[src_node_str].append({dest_node_str: slots_str}) 

288 

289 return OSSNodeMigratedNotification(id, nodes_to_slots_mapping) 

290 

291 @staticmethod 

292 def parse_maintenance_start_msg(response, notification_type): 

293 # Expected message format is: <notification_type> <seq_number> <time> 

294 # Examples: 

295 # MIGRATING 1 10 

296 # FAILING_OVER 2 20 

297 id = response[1] 

298 ttl = response[2] 

299 return notification_type(id, ttl) 

300 

301 @staticmethod 

302 def parse_maintenance_completed_msg(response, notification_type): 

303 # Expected message format is: <notification_type> <seq_number> 

304 # Examples: 

305 # MIGRATED 1 

306 # FAILED_OVER 2 

307 id = response[1] 

308 return notification_type(id) 

309 

310 @staticmethod 

311 def parse_moving_msg(response): 

312 # Expected message format is: MOVING <seq_number> <time> <endpoint> 

313 id = response[1] 

314 ttl = response[2] 

315 if response[3] is None: 

316 host, port = None, None 

317 else: 

318 value = safe_str(response[3]) 

319 host, port = value.rsplit(":", 1) 

320 port = int(port) if port is not None else None 

321 

322 return NodeMovingNotification(id, host, port, ttl) 

323 

324 

325_INVALIDATION_MESSAGE = "invalidate" 

326_MOVING_MESSAGE = "MOVING" 

327_MIGRATING_MESSAGE = "MIGRATING" 

328_MIGRATED_MESSAGE = "MIGRATED" 

329_FAILING_OVER_MESSAGE = "FAILING_OVER" 

330_FAILED_OVER_MESSAGE = "FAILED_OVER" 

331_SMIGRATING_MESSAGE = "SMIGRATING" 

332_SMIGRATED_MESSAGE = "SMIGRATED" 

333 

334_MAINTENANCE_MESSAGES = ( 

335 _MIGRATING_MESSAGE, 

336 _MIGRATED_MESSAGE, 

337 _FAILING_OVER_MESSAGE, 

338 _FAILED_OVER_MESSAGE, 

339 _SMIGRATING_MESSAGE, 

340) 

341 

342MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING: dict[ 

343 str, tuple[type[MaintenanceNotification], Callable] 

344] = { 

345 _MIGRATING_MESSAGE: ( 

346 NodeMigratingNotification, 

347 MaintenanceNotificationsParser.parse_maintenance_start_msg, 

348 ), 

349 _MIGRATED_MESSAGE: ( 

350 NodeMigratedNotification, 

351 MaintenanceNotificationsParser.parse_maintenance_completed_msg, 

352 ), 

353 _FAILING_OVER_MESSAGE: ( 

354 NodeFailingOverNotification, 

355 MaintenanceNotificationsParser.parse_maintenance_start_msg, 

356 ), 

357 _FAILED_OVER_MESSAGE: ( 

358 NodeFailedOverNotification, 

359 MaintenanceNotificationsParser.parse_maintenance_completed_msg, 

360 ), 

361 _MOVING_MESSAGE: ( 

362 NodeMovingNotification, 

363 MaintenanceNotificationsParser.parse_moving_msg, 

364 ), 

365 _SMIGRATING_MESSAGE: ( 

366 OSSNodeMigratingNotification, 

367 MaintenanceNotificationsParser.parse_oss_maintenance_start_msg, 

368 ), 

369 _SMIGRATED_MESSAGE: ( 

370 OSSNodeMigratedNotification, 

371 MaintenanceNotificationsParser.parse_oss_maintenance_completed_msg, 

372 ), 

373} 

374 

375 

376class PushNotificationsParser(Protocol): 

377 """Protocol defining RESP3-specific parsing functionality""" 

378 

379 pubsub_push_handler_func: Callable 

380 invalidation_push_handler_func: Optional[Callable] = None 

381 node_moving_push_handler_func: Optional[Callable] = None 

382 maintenance_push_handler_func: Optional[Callable] = None 

383 oss_cluster_maint_push_handler_func: Optional[Callable] = None 

384 

385 def handle_pubsub_push_response(self, response): 

386 """Handle pubsub push responses""" 

387 raise NotImplementedError() 

388 

389 def handle_push_response(self, response, **kwargs): 

390 msg_type = response[0] 

391 if isinstance(msg_type, bytes): 

392 msg_type = msg_type.decode() 

393 

394 if msg_type not in ( 

395 _INVALIDATION_MESSAGE, 

396 *_MAINTENANCE_MESSAGES, 

397 _MOVING_MESSAGE, 

398 _SMIGRATED_MESSAGE, 

399 ): 

400 return self.pubsub_push_handler_func(response) 

401 

402 try: 

403 if ( 

404 msg_type == _INVALIDATION_MESSAGE 

405 and self.invalidation_push_handler_func 

406 ): 

407 return self.invalidation_push_handler_func(response) 

408 

409 if msg_type == _MOVING_MESSAGE and self.node_moving_push_handler_func: 

410 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

411 msg_type 

412 ][1] 

413 

414 notification = parser_function(response) 

415 return self.node_moving_push_handler_func(notification) 

416 

417 if msg_type in _MAINTENANCE_MESSAGES and self.maintenance_push_handler_func: 

418 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

419 msg_type 

420 ][1] 

421 if msg_type == _SMIGRATING_MESSAGE: 

422 notification = parser_function(response) 

423 else: 

424 notification_type = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

425 msg_type 

426 ][0] 

427 notification = parser_function(response, notification_type) 

428 

429 if notification is not None: 

430 return self.maintenance_push_handler_func(notification) 

431 if msg_type == _SMIGRATED_MESSAGE and ( 

432 self.oss_cluster_maint_push_handler_func 

433 or self.maintenance_push_handler_func 

434 ): 

435 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

436 msg_type 

437 ][1] 

438 notification = parser_function(response) 

439 

440 if notification is not None: 

441 if self.maintenance_push_handler_func: 

442 self.maintenance_push_handler_func(notification) 

443 if self.oss_cluster_maint_push_handler_func: 

444 self.oss_cluster_maint_push_handler_func(notification) 

445 except Exception as e: 

446 logger.error( 

447 "Error handling {} message ({}): {}".format(msg_type, response, e) 

448 ) 

449 

450 return None 

451 

452 def set_pubsub_push_handler(self, pubsub_push_handler_func): 

453 self.pubsub_push_handler_func = pubsub_push_handler_func 

454 

455 def set_invalidation_push_handler(self, invalidation_push_handler_func): 

456 self.invalidation_push_handler_func = invalidation_push_handler_func 

457 

458 def set_node_moving_push_handler(self, node_moving_push_handler_func): 

459 self.node_moving_push_handler_func = node_moving_push_handler_func 

460 

461 def set_maintenance_push_handler(self, maintenance_push_handler_func): 

462 self.maintenance_push_handler_func = maintenance_push_handler_func 

463 

464 def set_oss_cluster_maint_push_handler(self, oss_cluster_maint_push_handler_func): 

465 self.oss_cluster_maint_push_handler_func = oss_cluster_maint_push_handler_func 

466 

467 

468class AsyncPushNotificationsParser(Protocol): 

469 """Protocol defining async RESP3-specific parsing functionality""" 

470 

471 pubsub_push_handler_func: Callable 

472 invalidation_push_handler_func: Optional[Callable] = None 

473 node_moving_push_handler_func: Optional[Callable[..., Awaitable[None]]] = None 

474 maintenance_push_handler_func: Optional[Callable[..., Awaitable[None]]] = None 

475 oss_cluster_maint_push_handler_func: Optional[Callable[..., Awaitable[None]]] = None 

476 

477 async def handle_pubsub_push_response(self, response): 

478 """Handle pubsub push responses asynchronously""" 

479 raise NotImplementedError() 

480 

481 async def handle_push_response(self, response, **kwargs): 

482 """Handle push responses asynchronously""" 

483 

484 msg_type = response[0] 

485 if isinstance(msg_type, bytes): 

486 msg_type = msg_type.decode() 

487 

488 if msg_type not in ( 

489 _INVALIDATION_MESSAGE, 

490 *_MAINTENANCE_MESSAGES, 

491 _MOVING_MESSAGE, 

492 _SMIGRATED_MESSAGE, 

493 ): 

494 return await self.pubsub_push_handler_func(response) 

495 

496 try: 

497 if ( 

498 msg_type == _INVALIDATION_MESSAGE 

499 and self.invalidation_push_handler_func 

500 ): 

501 return await self.invalidation_push_handler_func(response) 

502 

503 if isinstance(msg_type, bytes): 

504 msg_type = msg_type.decode() 

505 

506 if msg_type == _MOVING_MESSAGE and self.node_moving_push_handler_func: 

507 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

508 msg_type 

509 ][1] 

510 notification = parser_function(response) 

511 return await self.node_moving_push_handler_func(notification) 

512 

513 if msg_type in _MAINTENANCE_MESSAGES and self.maintenance_push_handler_func: 

514 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

515 msg_type 

516 ][1] 

517 if msg_type == _SMIGRATING_MESSAGE: 

518 notification = parser_function(response) 

519 else: 

520 notification_type = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

521 msg_type 

522 ][0] 

523 notification = parser_function(response, notification_type) 

524 

525 if notification is not None: 

526 return await self.maintenance_push_handler_func(notification) 

527 if ( 

528 msg_type == _SMIGRATED_MESSAGE 

529 and self.oss_cluster_maint_push_handler_func 

530 ): 

531 parser_function = MSG_TYPE_TO_MAINT_NOTIFICATION_PARSER_MAPPING[ 

532 msg_type 

533 ][1] 

534 notification = parser_function(response) 

535 if notification is not None: 

536 return await self.oss_cluster_maint_push_handler_func(notification) 

537 except Exception as e: 

538 logger.error( 

539 "Error handling {} message ({}): {}".format(msg_type, response, e) 

540 ) 

541 

542 return None 

543 

544 def set_pubsub_push_handler(self, pubsub_push_handler_func): 

545 """Set the pubsub push handler function""" 

546 self.pubsub_push_handler_func = pubsub_push_handler_func 

547 

548 def set_invalidation_push_handler(self, invalidation_push_handler_func): 

549 """Set the invalidation push handler function""" 

550 self.invalidation_push_handler_func = invalidation_push_handler_func 

551 

552 def set_node_moving_push_handler(self, node_moving_push_handler_func): 

553 self.node_moving_push_handler_func = node_moving_push_handler_func 

554 

555 def set_maintenance_push_handler(self, maintenance_push_handler_func): 

556 self.maintenance_push_handler_func = maintenance_push_handler_func 

557 

558 def set_oss_cluster_maint_push_handler(self, oss_cluster_maint_push_handler_func): 

559 self.oss_cluster_maint_push_handler_func = oss_cluster_maint_push_handler_func 

560 

561 

562class _AsyncRESPBase(AsyncBaseParser): 

563 """Base class for async resp parsing""" 

564 

565 __slots__ = AsyncBaseParser.__slots__ + ("encoder", "_buffer", "_pos", "_chunks") 

566 

567 def __init__(self, socket_read_size: int): 

568 super().__init__(socket_read_size) 

569 self.encoder: Optional[Encoder] = None 

570 self._buffer = b"" 

571 self._chunks = [] 

572 self._pos = 0 

573 

574 def _clear(self): 

575 self._buffer = b"" 

576 self._chunks.clear() 

577 

578 def on_connect(self, connection): 

579 """Called when the stream connects""" 

580 self._stream = connection._reader 

581 if self._stream is None: 

582 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

583 self.encoder = connection.encoder 

584 self._clear() 

585 self._connected = True 

586 

587 def on_disconnect(self): 

588 """Called when the stream disconnects""" 

589 self._connected = False 

590 

591 @deprecated_function( 

592 version="8.0.0", 

593 reason="Use can_read() instead", 

594 name="can_read_destructive", 

595 ) 

596 async def can_read_destructive(self) -> bool: 

597 return await self.can_read() 

598 

599 async def can_read(self) -> bool: 

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

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

602 if not self._connected: 

603 raise OSError("Buffer is closed.") 

604 # buffered data wins over EOF, like the sync SocketBuffer: a pending 

605 # response or push notification must stay readable even if the server 

606 # has since closed the connection. 

607 if self._buffer: 

608 return True 

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

610 # Raise like the sync SocketBuffer does on a server-closed 

611 # connection, so callers that tolerate pending data (push 

612 # notifications) can't mistake EOF for a readable connection. 

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

614 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

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

616 # buffered bytes. Preserve dirty-connection detection for the Python 

617 # parser and fail loudly if the private buffer API changes. 

618 return bool(self._stream._buffer) 

619 

620 async def _read(self, length: int) -> bytes: 

621 """ 

622 Read `length` bytes of data. These are assumed to be followed 

623 by a '\r\n' terminator which is subsequently discarded. 

624 """ 

625 want = length + 2 

626 end = self._pos + want 

627 if len(self._buffer) >= end: 

628 result = self._buffer[self._pos : end - 2] 

629 else: 

630 tail = self._buffer[self._pos :] 

631 try: 

632 data = await self._stream.readexactly(want - len(tail)) 

633 except IncompleteReadError as error: 

634 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) from error 

635 result = (tail + data)[:-2] 

636 self._chunks.append(data) 

637 self._pos += want 

638 return result 

639 

640 async def _readline(self) -> bytes: 

641 """ 

642 read an unknown number of bytes up to the next '\r\n' 

643 line separator, which is discarded. 

644 """ 

645 found = self._buffer.find(b"\r\n", self._pos) 

646 if found >= 0: 

647 result = self._buffer[self._pos : found] 

648 else: 

649 tail = self._buffer[self._pos :] 

650 data = await self._stream.readline() 

651 if not data.endswith(b"\r\n"): 

652 raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) 

653 result = (tail + data)[:-2] 

654 self._chunks.append(data) 

655 self._pos += len(result) + 2 

656 return result