streams.py 27 KB

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