You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

585 lines
18 KiB

4 years ago
  1. import asyncio
  2. import collections
  3. from typing import List # noqa
  4. from typing import Awaitable, Callable, Optional, Tuple
  5. from .helpers import set_exception, set_result
  6. from .log import internal_logger
  7. from .typedefs import Byteish
  8. __all__ = (
  9. 'EMPTY_PAYLOAD', 'EofStream', 'StreamReader', 'DataQueue',
  10. 'FlowControlDataQueue')
  11. DEFAULT_LIMIT = 2 ** 16
  12. class EofStream(Exception):
  13. """eof stream indication."""
  14. class AsyncStreamIterator:
  15. def __init__(self, read_func: Callable[[], Awaitable[bytes]]) -> None:
  16. self.read_func = read_func
  17. def __aiter__(self) -> 'AsyncStreamIterator':
  18. return self
  19. async def __anext__(self) -> bytes:
  20. try:
  21. rv = await self.read_func()
  22. except EofStream:
  23. raise StopAsyncIteration # NOQA
  24. if rv == b'':
  25. raise StopAsyncIteration # NOQA
  26. return rv
  27. class ChunkTupleAsyncStreamIterator:
  28. def __init__(self, stream: 'StreamReader') -> None:
  29. self._stream = stream
  30. def __aiter__(self) -> 'ChunkTupleAsyncStreamIterator':
  31. return self
  32. async def __anext__(self) -> Tuple[bytes, bool]:
  33. rv = await self._stream.readchunk()
  34. if rv == (b'', False):
  35. raise StopAsyncIteration # NOQA
  36. return rv
  37. class AsyncStreamReaderMixin:
  38. def __aiter__(self) -> AsyncStreamIterator:
  39. return AsyncStreamIterator(self.readline) # type: ignore
  40. def iter_chunked(self, n: int) -> AsyncStreamIterator:
  41. """Returns an asynchronous iterator that yields chunks of size n.
  42. Python-3.5 available for Python 3.5+ only
  43. """
  44. return AsyncStreamIterator(lambda: self.read(n)) # type: ignore
  45. def iter_any(self) -> AsyncStreamIterator:
  46. """Returns an asynchronous iterator that yields all the available
  47. data as soon as it is received
  48. Python-3.5 available for Python 3.5+ only
  49. """
  50. return AsyncStreamIterator(self.readany) # type: ignore
  51. def iter_chunks(self) -> ChunkTupleAsyncStreamIterator:
  52. """Returns an asynchronous iterator that yields chunks of data
  53. as they are received by the server. The yielded objects are tuples
  54. of (bytes, bool) as returned by the StreamReader.readchunk method.
  55. Python-3.5 available for Python 3.5+ only
  56. """
  57. return ChunkTupleAsyncStreamIterator(self) # type: ignore
  58. class StreamReader(AsyncStreamReaderMixin):
  59. """An enhancement of asyncio.StreamReader.
  60. Supports asynchronous iteration by line, chunk or as available::
  61. async for line in reader:
  62. ...
  63. async for chunk in reader.iter_chunked(1024):
  64. ...
  65. async for slice in reader.iter_any():
  66. ...
  67. """
  68. total_bytes = 0
  69. def __init__(self, protocol,
  70. *, limit=DEFAULT_LIMIT, timer=None, loop=None):
  71. self._protocol = protocol
  72. self._low_water = limit
  73. self._high_water = limit * 2
  74. if loop is None:
  75. loop = asyncio.get_event_loop()
  76. self._loop = loop
  77. self._size = 0
  78. self._cursor = 0
  79. self._http_chunk_splits = None
  80. self._buffer = collections.deque()
  81. self._buffer_offset = 0
  82. self._eof = False
  83. self._waiter = None
  84. self._eof_waiter = None
  85. self._exception = None
  86. self._timer = timer
  87. self._eof_callbacks = []
  88. def __repr__(self):
  89. info = [self.__class__.__name__]
  90. if self._size:
  91. info.append('%d bytes' % self._size)
  92. if self._eof:
  93. info.append('eof')
  94. if self._low_water != DEFAULT_LIMIT:
  95. info.append('low=%d high=%d' % (self._low_water, self._high_water))
  96. if self._waiter:
  97. info.append('w=%r' % self._waiter)
  98. if self._exception:
  99. info.append('e=%r' % self._exception)
  100. return '<%s>' % ' '.join(info)
  101. def exception(self) -> Optional[BaseException]:
  102. return self._exception
  103. def set_exception(self, exc: BaseException) -> None:
  104. self._exception = exc
  105. self._eof_callbacks.clear()
  106. waiter = self._waiter
  107. if waiter is not None:
  108. self._waiter = None
  109. set_exception(waiter, exc)
  110. waiter = self._eof_waiter
  111. if waiter is not None:
  112. set_exception(waiter, exc)
  113. self._eof_waiter = None
  114. def on_eof(self, callback: Callable[[], None]) -> None:
  115. if self._eof:
  116. try:
  117. callback()
  118. except Exception:
  119. internal_logger.exception('Exception in eof callback')
  120. else:
  121. self._eof_callbacks.append(callback)
  122. def feed_eof(self) -> None:
  123. self._eof = True
  124. waiter = self._waiter
  125. if waiter is not None:
  126. self._waiter = None
  127. set_result(waiter, True)
  128. waiter = self._eof_waiter
  129. if waiter is not None:
  130. self._eof_waiter = None
  131. set_result(waiter, True)
  132. for cb in self._eof_callbacks:
  133. try:
  134. cb()
  135. except Exception:
  136. internal_logger.exception('Exception in eof callback')
  137. self._eof_callbacks.clear()
  138. def is_eof(self) -> bool:
  139. """Return True if 'feed_eof' was called."""
  140. return self._eof
  141. def at_eof(self) -> bool:
  142. """Return True if the buffer is empty and 'feed_eof' was called."""
  143. return self._eof and not self._buffer
  144. async def wait_eof(self) -> None:
  145. if self._eof:
  146. return
  147. assert self._eof_waiter is None
  148. self._eof_waiter = self._loop.create_future()
  149. try:
  150. await self._eof_waiter
  151. finally:
  152. self._eof_waiter = None
  153. def unread_data(self, data: Byteish) -> None:
  154. """ rollback reading some data from stream, inserting it to buffer head.
  155. """
  156. if not data:
  157. return
  158. if self._buffer_offset:
  159. self._buffer[0] = self._buffer[0][self._buffer_offset:]
  160. self._buffer_offset = 0
  161. self._size += len(data)
  162. self._cursor -= len(data)
  163. self._buffer.appendleft(data)
  164. self._eof_counter = 0
  165. # TODO: size is ignored, remove the param later
  166. def feed_data(self, data: Byteish, size: int=0) -> None:
  167. assert not self._eof, 'feed_data after feed_eof'
  168. if not data:
  169. return
  170. self._size += len(data)
  171. self._buffer.append(data)
  172. self.total_bytes += len(data)
  173. waiter = self._waiter
  174. if waiter is not None:
  175. self._waiter = None
  176. set_result(waiter, False)
  177. if (self._size > self._high_water and
  178. not self._protocol._reading_paused):
  179. self._protocol.pause_reading()
  180. def begin_http_chunk_receiving(self) -> None:
  181. if self._http_chunk_splits is None:
  182. self._http_chunk_splits = []
  183. def end_http_chunk_receiving(self) -> None:
  184. if self._http_chunk_splits is None:
  185. raise RuntimeError("Called end_chunk_receiving without calling "
  186. "begin_chunk_receiving first")
  187. if not self._http_chunk_splits or \
  188. self._http_chunk_splits[-1] != self.total_bytes:
  189. self._http_chunk_splits.append(self.total_bytes)
  190. async def _wait(self, func_name):
  191. # StreamReader uses a future to link the protocol feed_data() method
  192. # to a read coroutine. Running two read coroutines at the same time
  193. # would have an unexpected behaviour. It would not possible to know
  194. # which coroutine would get the next data.
  195. if self._waiter is not None:
  196. raise RuntimeError('%s() called while another coroutine is '
  197. 'already waiting for incoming data' % func_name)
  198. waiter = self._waiter = self._loop.create_future()
  199. try:
  200. if self._timer:
  201. with self._timer:
  202. await waiter
  203. else:
  204. await waiter
  205. finally:
  206. self._waiter = None
  207. async def readline(self) -> bytes:
  208. if self._exception is not None:
  209. raise self._exception
  210. line = []
  211. line_size = 0
  212. not_enough = True
  213. while not_enough:
  214. while self._buffer and not_enough:
  215. offset = self._buffer_offset
  216. ichar = self._buffer[0].find(b'\n', offset) + 1
  217. # Read from current offset to found b'\n' or to the end.
  218. data = self._read_nowait_chunk(ichar - offset if ichar else -1)
  219. line.append(data)
  220. line_size += len(data)
  221. if ichar:
  222. not_enough = False
  223. if line_size > self._high_water:
  224. raise ValueError('Line is too long')
  225. if self._eof:
  226. break
  227. if not_enough:
  228. await self._wait('readline')
  229. return b''.join(line)
  230. async def read(self, n: int=-1) -> bytes:
  231. if self._exception is not None:
  232. raise self._exception
  233. # migration problem; with DataQueue you have to catch
  234. # EofStream exception, so common way is to run payload.read() inside
  235. # infinite loop. what can cause real infinite loop with StreamReader
  236. # lets keep this code one major release.
  237. if __debug__:
  238. if self._eof and not self._buffer:
  239. self._eof_counter = getattr(self, '_eof_counter', 0) + 1
  240. if self._eof_counter > 5:
  241. internal_logger.warning(
  242. 'Multiple access to StreamReader in eof state, '
  243. 'might be infinite loop.', stack_info=True)
  244. if not n:
  245. return b''
  246. if n < 0:
  247. # This used to just loop creating a new waiter hoping to
  248. # collect everything in self._buffer, but that would
  249. # deadlock if the subprocess sends more than self.limit
  250. # bytes. So just call self.readany() until EOF.
  251. blocks = []
  252. while True:
  253. block = await self.readany()
  254. if not block:
  255. break
  256. blocks.append(block)
  257. return b''.join(blocks)
  258. if not self._buffer and not self._eof:
  259. await self._wait('read')
  260. return self._read_nowait(n)
  261. async def readany(self) -> bytes:
  262. if self._exception is not None:
  263. raise self._exception
  264. if not self._buffer and not self._eof:
  265. await self._wait('readany')
  266. return self._read_nowait(-1)
  267. async def readchunk(self) -> Tuple[bytes, bool]:
  268. """Returns a tuple of (data, end_of_http_chunk). When chunked transfer
  269. encoding is used, end_of_http_chunk is a boolean indicating if the end
  270. of the data corresponds to the end of a HTTP chunk , otherwise it is
  271. always False.
  272. """
  273. if self._exception is not None:
  274. raise self._exception
  275. if not self._buffer and not self._eof:
  276. if (self._http_chunk_splits and
  277. self._cursor == self._http_chunk_splits[0]):
  278. # end of http chunk without available data
  279. self._http_chunk_splits = self._http_chunk_splits[1:]
  280. return (b"", True)
  281. await self._wait('readchunk')
  282. if not self._buffer:
  283. # end of file
  284. return (b"", False)
  285. elif self._http_chunk_splits is not None:
  286. while self._http_chunk_splits:
  287. pos = self._http_chunk_splits[0]
  288. self._http_chunk_splits = self._http_chunk_splits[1:]
  289. if pos > self._cursor:
  290. return (self._read_nowait(pos-self._cursor), True)
  291. return (self._read_nowait(-1), False)
  292. else:
  293. return (self._read_nowait_chunk(-1), False)
  294. async def readexactly(self, n: int) -> bytes:
  295. if self._exception is not None:
  296. raise self._exception
  297. blocks = [] # type: List[bytes]
  298. while n > 0:
  299. block = await self.read(n)
  300. if not block:
  301. partial = b''.join(blocks)
  302. raise asyncio.streams.IncompleteReadError(
  303. partial, len(partial) + n)
  304. blocks.append(block)
  305. n -= len(block)
  306. return b''.join(blocks)
  307. def read_nowait(self, n: int=-1) -> bytes:
  308. # default was changed to be consistent with .read(-1)
  309. #
  310. # I believe the most users don't know about the method and
  311. # they are not affected.
  312. if self._exception is not None:
  313. raise self._exception
  314. if self._waiter and not self._waiter.done():
  315. raise RuntimeError(
  316. 'Called while some coroutine is waiting for incoming data.')
  317. return self._read_nowait(n)
  318. def _read_nowait_chunk(self, n):
  319. first_buffer = self._buffer[0]
  320. offset = self._buffer_offset
  321. if n != -1 and len(first_buffer) - offset > n:
  322. data = first_buffer[offset:offset + n]
  323. self._buffer_offset += n
  324. elif offset:
  325. self._buffer.popleft()
  326. data = first_buffer[offset:]
  327. self._buffer_offset = 0
  328. else:
  329. data = self._buffer.popleft()
  330. self._size -= len(data)
  331. self._cursor += len(data)
  332. if self._size < self._low_water and self._protocol._reading_paused:
  333. self._protocol.resume_reading()
  334. return data
  335. def _read_nowait(self, n):
  336. chunks = []
  337. while self._buffer:
  338. chunk = self._read_nowait_chunk(n)
  339. chunks.append(chunk)
  340. if n != -1:
  341. n -= len(chunk)
  342. if n == 0:
  343. break
  344. return b''.join(chunks) if chunks else b''
  345. class EmptyStreamReader(AsyncStreamReaderMixin):
  346. def exception(self) -> Optional[BaseException]:
  347. return None
  348. def set_exception(self, exc: BaseException) -> None:
  349. pass
  350. def on_eof(self, callback: Callable[[], None]):
  351. try:
  352. callback()
  353. except Exception:
  354. internal_logger.exception('Exception in eof callback')
  355. def feed_eof(self) -> None:
  356. pass
  357. def is_eof(self) -> bool:
  358. return True
  359. def at_eof(self) -> bool:
  360. return True
  361. async def wait_eof(self) -> None:
  362. return
  363. def feed_data(self, data: Byteish, n: int=0) -> None:
  364. pass
  365. async def readline(self) -> bytes:
  366. return b''
  367. async def read(self, n: int=-1) -> bytes:
  368. return b''
  369. async def readany(self) -> bytes:
  370. return b''
  371. async def readchunk(self) -> Tuple[bytes, bool]:
  372. return (b'', False)
  373. async def readexactly(self, n: int) -> bytes:
  374. raise asyncio.streams.IncompleteReadError(b'', n)
  375. def read_nowait(self) -> bytes:
  376. return b''
  377. EMPTY_PAYLOAD = EmptyStreamReader()
  378. class DataQueue:
  379. """DataQueue is a general-purpose blocking queue with one reader."""
  380. def __init__(self, *, loop=None):
  381. self._loop = loop
  382. self._eof = False
  383. self._waiter = None
  384. self._exception = None
  385. self._size = 0
  386. self._buffer = collections.deque()
  387. def __len__(self) -> int:
  388. return len(self._buffer)
  389. def is_eof(self) -> bool:
  390. return self._eof
  391. def at_eof(self) -> bool:
  392. return self._eof and not self._buffer
  393. def exception(self) -> Optional[BaseException]:
  394. return self._exception
  395. def set_exception(self, exc: BaseException) -> None:
  396. self._eof = True
  397. self._exception = exc
  398. waiter = self._waiter
  399. if waiter is not None:
  400. set_exception(waiter, exc)
  401. self._waiter = None
  402. def feed_data(self, data: Byteish, size: int=0) -> None:
  403. self._size += size
  404. self._buffer.append((data, size))
  405. waiter = self._waiter
  406. if waiter is not None:
  407. self._waiter = None
  408. set_result(waiter, True)
  409. def feed_eof(self) -> None:
  410. self._eof = True
  411. waiter = self._waiter
  412. if waiter is not None:
  413. self._waiter = None
  414. set_result(waiter, False)
  415. async def read(self) -> bytes:
  416. if not self._buffer and not self._eof:
  417. assert not self._waiter
  418. self._waiter = self._loop.create_future()
  419. try:
  420. await self._waiter
  421. except (asyncio.CancelledError, asyncio.TimeoutError):
  422. self._waiter = None
  423. raise
  424. if self._buffer:
  425. data, size = self._buffer.popleft()
  426. self._size -= size
  427. return data
  428. else:
  429. if self._exception is not None:
  430. raise self._exception
  431. else:
  432. raise EofStream
  433. def __aiter__(self) -> AsyncStreamIterator:
  434. return AsyncStreamIterator(self.read)
  435. class FlowControlDataQueue(DataQueue):
  436. """FlowControlDataQueue resumes and pauses an underlying stream.
  437. It is a destination for parsed data."""
  438. def __init__(self, protocol, *, limit: int=DEFAULT_LIMIT, loop:
  439. Optional[asyncio.AbstractEventLoop]=None) -> None:
  440. super().__init__(loop=loop)
  441. self._protocol = protocol
  442. self._limit = limit * 2
  443. def feed_data(self, data: Byteish, size: int=0) -> None:
  444. super().feed_data(data, size)
  445. if self._size > self._limit and not self._protocol._reading_paused:
  446. self._protocol.pause_reading()
  447. async def read(self) -> bytes:
  448. try:
  449. return await super().read()
  450. finally:
  451. if self._size < self._limit and self._protocol._reading_paused:
  452. self._protocol.resume_reading()