streams.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. __all__ = (
  2. 'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
  3. 'open_connection', 'start_server')
  4. import socket
  5. import sys
  6. import warnings
  7. import weakref
  8. if hasattr(socket, 'AF_UNIX'):
  9. __all__ += ('open_unix_connection', 'start_unix_server')
  10. from . import coroutines
  11. from . import events
  12. from . import exceptions
  13. from . import format_helpers
  14. from . import protocols
  15. from .log import logger
  16. from .tasks import sleep
  17. _DEFAULT_LIMIT = 2 ** 16 # 64 KiB
  18. async def open_connection(host=None, port=None, *,
  19. loop=None, limit=_DEFAULT_LIMIT, **kwds):
  20. """A wrapper for create_connection() returning a (reader, writer) pair.
  21. The reader returned is a StreamReader instance; the writer is a
  22. StreamWriter instance.
  23. The arguments are all the usual arguments to create_connection()
  24. except protocol_factory; most common are positional host and port,
  25. with various optional keyword arguments following.
  26. Additional optional keyword arguments are loop (to set the event loop
  27. instance to use) and limit (to set the buffer limit passed to the
  28. StreamReader).
  29. (If you want to customize the StreamReader and/or
  30. StreamReaderProtocol classes, just copy the code -- there's
  31. really nothing special here except some convenience.)
  32. """
  33. if loop is None:
  34. loop = events.get_event_loop()
  35. else:
  36. warnings.warn("The loop argument is deprecated since Python 3.8, "
  37. "and scheduled for removal in Python 3.10.",
  38. DeprecationWarning, stacklevel=2)
  39. reader = StreamReader(limit=limit, loop=loop)
  40. protocol = StreamReaderProtocol(reader, loop=loop)
  41. transport, _ = await loop.create_connection(
  42. lambda: protocol, host, port, **kwds)
  43. writer = StreamWriter(transport, protocol, reader, loop)
  44. return reader, writer
  45. async def start_server(client_connected_cb, host=None, port=None, *,
  46. loop=None, limit=_DEFAULT_LIMIT, **kwds):
  47. """Start a socket server, call back for each client connected.
  48. The first parameter, `client_connected_cb`, takes two parameters:
  49. client_reader, client_writer. client_reader is a StreamReader
  50. object, while client_writer is a StreamWriter object. This
  51. parameter can either be a plain callback function or a coroutine;
  52. if it is a coroutine, it will be automatically converted into a
  53. Task.
  54. The rest of the arguments are all the usual arguments to
  55. loop.create_server() except protocol_factory; most common are
  56. positional host and port, with various optional keyword arguments
  57. following. The return value is the same as loop.create_server().
  58. Additional optional keyword arguments are loop (to set the event loop
  59. instance to use) and limit (to set the buffer limit passed to the
  60. StreamReader).
  61. The return value is the same as loop.create_server(), i.e. a
  62. Server object which can be used to stop the service.
  63. """
  64. if loop is None:
  65. loop = events.get_event_loop()
  66. else:
  67. warnings.warn("The loop argument is deprecated since Python 3.8, "
  68. "and scheduled for removal in Python 3.10.",
  69. DeprecationWarning, stacklevel=2)
  70. def factory():
  71. reader = StreamReader(limit=limit, loop=loop)
  72. protocol = StreamReaderProtocol(reader, client_connected_cb,
  73. loop=loop)
  74. return protocol
  75. return await loop.create_server(factory, host, port, **kwds)
  76. if hasattr(socket, 'AF_UNIX'):
  77. # UNIX Domain Sockets are supported on this platform
  78. async def open_unix_connection(path=None, *,
  79. loop=None, limit=_DEFAULT_LIMIT, **kwds):
  80. """Similar to `open_connection` but works with UNIX Domain Sockets."""
  81. if loop is None:
  82. loop = events.get_event_loop()
  83. else:
  84. warnings.warn("The loop argument is deprecated since Python 3.8, "
  85. "and scheduled for removal in Python 3.10.",
  86. DeprecationWarning, stacklevel=2)
  87. reader = StreamReader(limit=limit, loop=loop)
  88. protocol = StreamReaderProtocol(reader, loop=loop)
  89. transport, _ = await loop.create_unix_connection(
  90. lambda: protocol, path, **kwds)
  91. writer = StreamWriter(transport, protocol, reader, loop)
  92. return reader, writer
  93. async def start_unix_server(client_connected_cb, path=None, *,
  94. loop=None, limit=_DEFAULT_LIMIT, **kwds):
  95. """Similar to `start_server` but works with UNIX Domain Sockets."""
  96. if loop is None:
  97. loop = events.get_event_loop()
  98. else:
  99. warnings.warn("The loop argument is deprecated since Python 3.8, "
  100. "and scheduled for removal in Python 3.10.",
  101. DeprecationWarning, stacklevel=2)
  102. def factory():
  103. reader = StreamReader(limit=limit, loop=loop)
  104. protocol = StreamReaderProtocol(reader, client_connected_cb,
  105. loop=loop)
  106. return protocol
  107. return await loop.create_unix_server(factory, path, **kwds)
  108. class FlowControlMixin(protocols.Protocol):
  109. """Reusable flow control logic for StreamWriter.drain().
  110. This implements the protocol methods pause_writing(),
  111. resume_writing() and connection_lost(). If the subclass overrides
  112. these it must call the super methods.
  113. StreamWriter.drain() must wait for _drain_helper() coroutine.
  114. """
  115. def __init__(self, loop=None):
  116. if loop is None:
  117. self._loop = events.get_event_loop()
  118. else:
  119. self._loop = loop
  120. self._paused = False
  121. self._drain_waiter = None
  122. self._connection_lost = False
  123. def pause_writing(self):
  124. assert not self._paused
  125. self._paused = True
  126. if self._loop.get_debug():
  127. logger.debug("%r pauses writing", self)
  128. def resume_writing(self):
  129. assert self._paused
  130. self._paused = False
  131. if self._loop.get_debug():
  132. logger.debug("%r resumes writing", self)
  133. waiter = self._drain_waiter
  134. if waiter is not None:
  135. self._drain_waiter = None
  136. if not waiter.done():
  137. waiter.set_result(None)
  138. def connection_lost(self, exc):
  139. self._connection_lost = True
  140. # Wake up the writer if currently paused.
  141. if not self._paused:
  142. return
  143. waiter = self._drain_waiter
  144. if waiter is None:
  145. return
  146. self._drain_waiter = None
  147. if waiter.done():
  148. return
  149. if exc is None:
  150. waiter.set_result(None)
  151. else:
  152. waiter.set_exception(exc)
  153. async def _drain_helper(self):
  154. if self._connection_lost:
  155. raise ConnectionResetError('Connection lost')
  156. if not self._paused:
  157. return
  158. waiter = self._drain_waiter
  159. assert waiter is None or waiter.cancelled()
  160. waiter = self._loop.create_future()
  161. self._drain_waiter = waiter
  162. await waiter
  163. def _get_close_waiter(self, stream):
  164. raise NotImplementedError
  165. class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
  166. """Helper class to adapt between Protocol and StreamReader.
  167. (This is a helper class instead of making StreamReader itself a
  168. Protocol subclass, because the StreamReader has other potential
  169. uses, and to prevent the user of the StreamReader to accidentally
  170. call inappropriate methods of the protocol.)
  171. """
  172. _source_traceback = None
  173. def __init__(self, stream_reader, client_connected_cb=None, loop=None):
  174. super().__init__(loop=loop)
  175. if stream_reader is not None:
  176. self._stream_reader_wr = weakref.ref(stream_reader)
  177. self._source_traceback = stream_reader._source_traceback
  178. else:
  179. self._stream_reader_wr = None
  180. if client_connected_cb is not None:
  181. # This is a stream created by the `create_server()` function.
  182. # Keep a strong reference to the reader until a connection
  183. # is established.
  184. self._strong_reader = stream_reader
  185. self._reject_connection = False
  186. self._stream_writer = None
  187. self._transport = None
  188. self._client_connected_cb = client_connected_cb
  189. self._over_ssl = False
  190. self._closed = self._loop.create_future()
  191. @property
  192. def _stream_reader(self):
  193. if self._stream_reader_wr is None:
  194. return None
  195. return self._stream_reader_wr()
  196. def connection_made(self, transport):
  197. if self._reject_connection:
  198. context = {
  199. 'message': ('An open stream was garbage collected prior to '
  200. 'establishing network connection; '
  201. 'call "stream.close()" explicitly.')
  202. }
  203. if self._source_traceback:
  204. context['source_traceback'] = self._source_traceback
  205. self._loop.call_exception_handler(context)
  206. transport.abort()
  207. return
  208. self._transport = transport
  209. reader = self._stream_reader
  210. if reader is not None:
  211. reader.set_transport(transport)
  212. self._over_ssl = transport.get_extra_info('sslcontext') is not None
  213. if self._client_connected_cb is not None:
  214. self._stream_writer = StreamWriter(transport, self,
  215. reader,
  216. self._loop)
  217. res = self._client_connected_cb(reader,
  218. self._stream_writer)
  219. if coroutines.iscoroutine(res):
  220. self._loop.create_task(res)
  221. self._strong_reader = None
  222. def connection_lost(self, exc):
  223. reader = self._stream_reader
  224. if reader is not None:
  225. if exc is None:
  226. reader.feed_eof()
  227. else:
  228. reader.set_exception(exc)
  229. if not self._closed.done():
  230. if exc is None:
  231. self._closed.set_result(None)
  232. else:
  233. self._closed.set_exception(exc)
  234. super().connection_lost(exc)
  235. self._stream_reader_wr = None
  236. self._stream_writer = None
  237. self._transport = None
  238. def data_received(self, data):
  239. reader = self._stream_reader
  240. if reader is not None:
  241. reader.feed_data(data)
  242. def eof_received(self):
  243. reader = self._stream_reader
  244. if reader is not None:
  245. reader.feed_eof()
  246. if self._over_ssl:
  247. # Prevent a warning in SSLProtocol.eof_received:
  248. # "returning true from eof_received()
  249. # has no effect when using ssl"
  250. return False
  251. return True
  252. def _get_close_waiter(self, stream):
  253. return self._closed
  254. def __del__(self):
  255. # Prevent reports about unhandled exceptions.
  256. # Better than self._closed._log_traceback = False hack
  257. closed = self._closed
  258. if closed.done() and not closed.cancelled():
  259. closed.exception()
  260. class StreamWriter:
  261. """Wraps a Transport.
  262. This exposes write(), writelines(), [can_]write_eof(),
  263. get_extra_info() and close(). It adds drain() which returns an
  264. optional Future on which you can wait for flow control. It also
  265. adds a transport property which references the Transport
  266. directly.
  267. """
  268. def __init__(self, transport, protocol, reader, loop):
  269. self._transport = transport
  270. self._protocol = protocol
  271. # drain() expects that the reader has an exception() method
  272. assert reader is None or isinstance(reader, StreamReader)
  273. self._reader = reader
  274. self._loop = loop
  275. self._complete_fut = self._loop.create_future()
  276. self._complete_fut.set_result(None)
  277. def __repr__(self):
  278. info = [self.__class__.__name__, f'transport={self._transport!r}']
  279. if self._reader is not None:
  280. info.append(f'reader={self._reader!r}')
  281. return '<{}>'.format(' '.join(info))
  282. @property
  283. def transport(self):
  284. return self._transport
  285. def write(self, data):
  286. self._transport.write(data)
  287. def writelines(self, data):
  288. self._transport.writelines(data)
  289. def write_eof(self):
  290. return self._transport.write_eof()
  291. def can_write_eof(self):
  292. return self._transport.can_write_eof()
  293. def close(self):
  294. return self._transport.close()
  295. def is_closing(self):
  296. return self._transport.is_closing()
  297. async def wait_closed(self):
  298. await self._protocol._get_close_waiter(self)
  299. def get_extra_info(self, name, default=None):
  300. return self._transport.get_extra_info(name, default)
  301. async def drain(self):
  302. """Flush the write buffer.
  303. The intended use is to write
  304. w.write(data)
  305. await w.drain()
  306. """
  307. if self._reader is not None:
  308. exc = self._reader.exception()
  309. if exc is not None:
  310. raise exc
  311. if self._transport.is_closing():
  312. # Wait for protocol.connection_lost() call
  313. # Raise connection closing error if any,
  314. # ConnectionResetError otherwise
  315. # Yield to the event loop so connection_lost() may be
  316. # called. Without this, _drain_helper() would return
  317. # immediately, and code that calls
  318. # write(...); await drain()
  319. # in a loop would never call connection_lost(), so it
  320. # would not see an error when the socket is closed.
  321. await sleep(0)
  322. await self._protocol._drain_helper()
  323. class StreamReader:
  324. _source_traceback = None
  325. def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
  326. # The line length limit is a security feature;
  327. # it also doubles as half the buffer limit.
  328. if limit <= 0:
  329. raise ValueError('Limit cannot be <= 0')
  330. self._limit = limit
  331. if loop is None:
  332. self._loop = events.get_event_loop()
  333. else:
  334. self._loop = loop
  335. self._buffer = bytearray()
  336. self._eof = False # Whether we're done.
  337. self._waiter = None # A future used by _wait_for_data()
  338. self._exception = None
  339. self._transport = None
  340. self._paused = False
  341. if self._loop.get_debug():
  342. self._source_traceback = format_helpers.extract_stack(
  343. sys._getframe(1))
  344. def __repr__(self):
  345. info = ['StreamReader']
  346. if self._buffer:
  347. info.append(f'{len(self._buffer)} bytes')
  348. if self._eof:
  349. info.append('eof')
  350. if self._limit != _DEFAULT_LIMIT:
  351. info.append(f'limit={self._limit}')
  352. if self._waiter:
  353. info.append(f'waiter={self._waiter!r}')
  354. if self._exception:
  355. info.append(f'exception={self._exception!r}')
  356. if self._transport:
  357. info.append(f'transport={self._transport!r}')
  358. if self._paused:
  359. info.append('paused')
  360. return '<{}>'.format(' '.join(info))
  361. def exception(self):
  362. return self._exception
  363. def set_exception(self, exc):
  364. self._exception = exc
  365. waiter = self._waiter
  366. if waiter is not None:
  367. self._waiter = None
  368. if not waiter.cancelled():
  369. waiter.set_exception(exc)
  370. def _wakeup_waiter(self):
  371. """Wakeup read*() functions waiting for data or EOF."""
  372. waiter = self._waiter
  373. if waiter is not None:
  374. self._waiter = None
  375. if not waiter.cancelled():
  376. waiter.set_result(None)
  377. def set_transport(self, transport):
  378. assert self._transport is None, 'Transport already set'
  379. self._transport = transport
  380. def _maybe_resume_transport(self):
  381. if self._paused and len(self._buffer) <= self._limit:
  382. self._paused = False
  383. self._transport.resume_reading()
  384. def feed_eof(self):
  385. self._eof = True
  386. self._wakeup_waiter()
  387. def at_eof(self):
  388. """Return True if the buffer is empty and 'feed_eof' was called."""
  389. return self._eof and not self._buffer
  390. def feed_data(self, data):
  391. assert not self._eof, 'feed_data after feed_eof'
  392. if not data:
  393. return
  394. self._buffer.extend(data)
  395. self._wakeup_waiter()
  396. if (self._transport is not None and
  397. not self._paused and
  398. len(self._buffer) > 2 * self._limit):
  399. try:
  400. self._transport.pause_reading()
  401. except NotImplementedError:
  402. # The transport can't be paused.
  403. # We'll just have to buffer all data.
  404. # Forget the transport so we don't keep trying.
  405. self._transport = None
  406. else:
  407. self._paused = True
  408. async def _wait_for_data(self, func_name):
  409. """Wait until feed_data() or feed_eof() is called.
  410. If stream was paused, automatically resume it.
  411. """
  412. # StreamReader uses a future to link the protocol feed_data() method
  413. # to a read coroutine. Running two read coroutines at the same time
  414. # would have an unexpected behaviour. It would not possible to know
  415. # which coroutine would get the next data.
  416. if self._waiter is not None:
  417. raise RuntimeError(
  418. f'{func_name}() called while another coroutine is '
  419. f'already waiting for incoming data')
  420. assert not self._eof, '_wait_for_data after EOF'
  421. # Waiting for data while paused will make deadlock, so prevent it.
  422. # This is essential for readexactly(n) for case when n > self._limit.
  423. if self._paused:
  424. self._paused = False
  425. self._transport.resume_reading()
  426. self._waiter = self._loop.create_future()
  427. try:
  428. await self._waiter
  429. finally:
  430. self._waiter = None
  431. async def readline(self):
  432. """Read chunk of data from the stream until newline (b'\n') is found.
  433. On success, return chunk that ends with newline. If only partial
  434. line can be read due to EOF, return incomplete line without
  435. terminating newline. When EOF was reached while no bytes read, empty
  436. bytes object is returned.
  437. If limit is reached, ValueError will be raised. In that case, if
  438. newline was found, complete line including newline will be removed
  439. from internal buffer. Else, internal buffer will be cleared. Limit is
  440. compared against part of the line without newline.
  441. If stream was paused, this function will automatically resume it if
  442. needed.
  443. """
  444. sep = b'\n'
  445. seplen = len(sep)
  446. try:
  447. line = await self.readuntil(sep)
  448. except exceptions.IncompleteReadError as e:
  449. return e.partial
  450. except exceptions.LimitOverrunError as e:
  451. if self._buffer.startswith(sep, e.consumed):
  452. del self._buffer[:e.consumed + seplen]
  453. else:
  454. self._buffer.clear()
  455. self._maybe_resume_transport()
  456. raise ValueError(e.args[0])
  457. return line
  458. async def readuntil(self, separator=b'\n'):
  459. """Read data from the stream until ``separator`` is found.
  460. On success, the data and separator will be removed from the
  461. internal buffer (consumed). Returned data will include the
  462. separator at the end.
  463. Configured stream limit is used to check result. Limit sets the
  464. maximal length of data that can be returned, not counting the
  465. separator.
  466. If an EOF occurs and the complete separator is still not found,
  467. an IncompleteReadError exception will be raised, and the internal
  468. buffer will be reset. The IncompleteReadError.partial attribute
  469. may contain the separator partially.
  470. If the data cannot be read because of over limit, a
  471. LimitOverrunError exception will be raised, and the data
  472. will be left in the internal buffer, so it can be read again.
  473. """
  474. seplen = len(separator)
  475. if seplen == 0:
  476. raise ValueError('Separator should be at least one-byte string')
  477. if self._exception is not None:
  478. raise self._exception
  479. # Consume whole buffer except last bytes, which length is
  480. # one less than seplen. Let's check corner cases with
  481. # separator='SEPARATOR':
  482. # * we have received almost complete separator (without last
  483. # byte). i.e buffer='some textSEPARATO'. In this case we
  484. # can safely consume len(separator) - 1 bytes.
  485. # * last byte of buffer is first byte of separator, i.e.
  486. # buffer='abcdefghijklmnopqrS'. We may safely consume
  487. # everything except that last byte, but this require to
  488. # analyze bytes of buffer that match partial separator.
  489. # This is slow and/or require FSM. For this case our
  490. # implementation is not optimal, since require rescanning
  491. # of data that is known to not belong to separator. In
  492. # real world, separator will not be so long to notice
  493. # performance problems. Even when reading MIME-encoded
  494. # messages :)
  495. # `offset` is the number of bytes from the beginning of the buffer
  496. # where there is no occurrence of `separator`.
  497. offset = 0
  498. # Loop until we find `separator` in the buffer, exceed the buffer size,
  499. # or an EOF has happened.
  500. while True:
  501. buflen = len(self._buffer)
  502. # Check if we now have enough data in the buffer for `separator` to
  503. # fit.
  504. if buflen - offset >= seplen:
  505. isep = self._buffer.find(separator, offset)
  506. if isep != -1:
  507. # `separator` is in the buffer. `isep` will be used later
  508. # to retrieve the data.
  509. break
  510. # see upper comment for explanation.
  511. offset = buflen + 1 - seplen
  512. if offset > self._limit:
  513. raise exceptions.LimitOverrunError(
  514. 'Separator is not found, and chunk exceed the limit',
  515. offset)
  516. # Complete message (with full separator) may be present in buffer
  517. # even when EOF flag is set. This may happen when the last chunk
  518. # adds data which makes separator be found. That's why we check for
  519. # EOF *ater* inspecting the buffer.
  520. if self._eof:
  521. chunk = bytes(self._buffer)
  522. self._buffer.clear()
  523. raise exceptions.IncompleteReadError(chunk, None)
  524. # _wait_for_data() will resume reading if stream was paused.
  525. await self._wait_for_data('readuntil')
  526. if isep > self._limit:
  527. raise exceptions.LimitOverrunError(
  528. 'Separator is found, but chunk is longer than limit', isep)
  529. chunk = self._buffer[:isep + seplen]
  530. del self._buffer[:isep + seplen]
  531. self._maybe_resume_transport()
  532. return bytes(chunk)
  533. async def read(self, n=-1):
  534. """Read up to `n` bytes from the stream.
  535. If n is not provided, or set to -1, read until EOF and return all read
  536. bytes. If the EOF was received and the internal buffer is empty, return
  537. an empty bytes object.
  538. If n is zero, return empty bytes object immediately.
  539. If n is positive, this function try to read `n` bytes, and may return
  540. less or equal bytes than requested, but at least one byte. If EOF was
  541. received before any byte is read, this function returns empty byte
  542. object.
  543. Returned value is not limited with limit, configured at stream
  544. creation.
  545. If stream was paused, this function will automatically resume it if
  546. needed.
  547. """
  548. if self._exception is not None:
  549. raise self._exception
  550. if n == 0:
  551. return b''
  552. if n < 0:
  553. # This used to just loop creating a new waiter hoping to
  554. # collect everything in self._buffer, but that would
  555. # deadlock if the subprocess sends more than self.limit
  556. # bytes. So just call self.read(self._limit) until EOF.
  557. blocks = []
  558. while True:
  559. block = await self.read(self._limit)
  560. if not block:
  561. break
  562. blocks.append(block)
  563. return b''.join(blocks)
  564. if not self._buffer and not self._eof:
  565. await self._wait_for_data('read')
  566. # This will work right even if buffer is less than n bytes
  567. data = bytes(self._buffer[:n])
  568. del self._buffer[:n]
  569. self._maybe_resume_transport()
  570. return data
  571. async def readexactly(self, n):
  572. """Read exactly `n` bytes.
  573. Raise an IncompleteReadError if EOF is reached before `n` bytes can be
  574. read. The IncompleteReadError.partial attribute of the exception will
  575. contain the partial read bytes.
  576. if n is zero, return empty bytes object.
  577. Returned value is not limited with limit, configured at stream
  578. creation.
  579. If stream was paused, this function will automatically resume it if
  580. needed.
  581. """
  582. if n < 0:
  583. raise ValueError('readexactly size can not be less than zero')
  584. if self._exception is not None:
  585. raise self._exception
  586. if n == 0:
  587. return b''
  588. while len(self._buffer) < n:
  589. if self._eof:
  590. incomplete = bytes(self._buffer)
  591. self._buffer.clear()
  592. raise exceptions.IncompleteReadError(incomplete, n)
  593. await self._wait_for_data('readexactly')
  594. if len(self._buffer) == n:
  595. data = bytes(self._buffer)
  596. self._buffer.clear()
  597. else:
  598. data = bytes(self._buffer[:n])
  599. del self._buffer[:n]
  600. self._maybe_resume_transport()
  601. return data
  602. def __aiter__(self):
  603. return self
  604. async def __anext__(self):
  605. val = await self.readline()
  606. if val == b'':
  607. raise StopAsyncIteration
  608. return val