|
| 1 | +# coding: utf8 |
| 2 | +'''Pool of asyncio coroutines with familiar interface, python3.5+ friendly''' |
| 3 | + |
| 4 | +import traceback |
| 5 | +import collections |
| 6 | +import asyncio as aio |
| 7 | +from .utils import _get_future_result |
| 8 | + |
| 9 | + |
| 10 | +class BaseAioPool(object): |
| 11 | + |
| 12 | + def __init__(self, size=1024, *, loop=None): |
| 13 | + self.loop = loop or aio.get_event_loop() |
| 14 | + |
| 15 | + self.size = size |
| 16 | + self._executed = 0 |
| 17 | + self._joined = collections.deque() |
| 18 | + self._waiting = collections.deque() |
| 19 | + self.semaphore = aio.Semaphore(value=self.size, loop=self.loop) |
| 20 | + |
| 21 | + async def __aenter__(self): |
| 22 | + return self |
| 23 | + |
| 24 | + async def __aexit__(self, ext_type, exc, tb): |
| 25 | + await self.join() |
| 26 | + |
| 27 | + @property |
| 28 | + def n_active(self): |
| 29 | + return self.size - self.semaphore._value |
| 30 | + |
| 31 | + @property |
| 32 | + def is_empty(self): |
| 33 | + return 0 == len(self._waiting) == self.n_active |
| 34 | + |
| 35 | + @property |
| 36 | + def is_full(self): |
| 37 | + return self.size <= len(self._waiting) + self.n_active |
| 38 | + |
| 39 | + async def join(self): |
| 40 | + if self.is_empty: |
| 41 | + return True |
| 42 | + |
| 43 | + fut = self.loop.create_future() |
| 44 | + self._joined.append(fut) |
| 45 | + try: |
| 46 | + return await fut |
| 47 | + finally: |
| 48 | + self._joined.remove(fut) |
| 49 | + |
| 50 | + def _release_joined(self): |
| 51 | + if not self.is_empty: |
| 52 | + raise RuntimeError() # TODO better message |
| 53 | + |
| 54 | + for fut in self._joined: |
| 55 | + if not fut.done(): |
| 56 | + fut.set_result(True) |
| 57 | + |
| 58 | + async def _wrap(self, coro, future, cb=None, ctx=None): |
| 59 | + res, exc, tb = None, None, None |
| 60 | + try: |
| 61 | + res = await coro |
| 62 | + except Exception as _exc: |
| 63 | + exc = _exc |
| 64 | + tb = traceback.format_exc() # TODO tb object instead of text |
| 65 | + finally: |
| 66 | + self._executed += 1 |
| 67 | + |
| 68 | + if cb: |
| 69 | + err = None if exc is None else (exc, tb) |
| 70 | + wrapped = self._wrap(cb(res, err, ctx), future) |
| 71 | + self.loop.create_task(wrapped) |
| 72 | + return |
| 73 | + |
| 74 | + self.semaphore.release() |
| 75 | + if not exc: |
| 76 | + future.set_result(res) |
| 77 | + else: |
| 78 | + future.set_exception(exc) |
| 79 | + |
| 80 | + if self.is_empty: |
| 81 | + self._release_joined() |
| 82 | + |
| 83 | + async def _spawn(self, future, coro, cb=None, ctx=None): |
| 84 | + try: |
| 85 | + await self.semaphore.acquire() |
| 86 | + except Exception as e: |
| 87 | + future.set_exception(e) |
| 88 | + self._waiting.remove(future) |
| 89 | + wrapped = self._wrap(coro, future, cb=cb, ctx=ctx) |
| 90 | + self.loop.create_task(wrapped) |
| 91 | + return future |
| 92 | + |
| 93 | + async def spawn_n(self, coro, cb=None, ctx=None): |
| 94 | + future = self.loop.create_future() |
| 95 | + self._waiting.append(future) |
| 96 | + self.loop.create_task(self._spawn(future, coro, cb=cb, ctx=ctx)) |
| 97 | + return future |
| 98 | + |
| 99 | + async def spawn(self, coro, cb=None, ctx=None): |
| 100 | + future = self.loop.create_future() |
| 101 | + self._waiting.append(future) |
| 102 | + return await self._spawn(future, coro, cb=cb, ctx=ctx) |
| 103 | + |
| 104 | + async def exec(self, coro, cb=None, ctx=None): |
| 105 | + return await (await self.spawn(coro, cb=cb, ctx=ctx)) |
| 106 | + |
| 107 | + async def map_n(self, fn, iterable): |
| 108 | + futures = [] |
| 109 | + for it in iterable: |
| 110 | + fut = await self.spawn_n(fn(it)) |
| 111 | + futures.append(fut) |
| 112 | + return futures |
| 113 | + |
| 114 | + async def map(self, fn, iterable, exc_as_result=True): |
| 115 | + futures = await self.map_n(fn, iterable) |
| 116 | + await self.join() |
| 117 | + |
| 118 | + result = [] |
| 119 | + for fut in futures: |
| 120 | + if fut.exception(): |
| 121 | + res = fut.exception() if exc_as_result else None |
| 122 | + else: |
| 123 | + res = fut.result() |
| 124 | + result.append(res) |
| 125 | + return result |
| 126 | + |
| 127 | + async def iterwait(self, *arg, **kw): # TODO there's a way to support 3.5? |
| 128 | + raise NotImplementedError('python3.6+ required') |
| 129 | + |
| 130 | + async def itermap(self, *arg, **kw): # TODO there's a way to support 3.5? |
| 131 | + raise NotImplementedError('python3.6+ required') |
| 132 | + |
| 133 | + ''' |
| 134 | + if sys.version_info >= (3, 6): # supports async generators |
| 135 | +
|
| 136 | + async def iterwait(self, futures, *, flat=True, exc_as_result=True, |
| 137 | + timeout=None, yield_when=aio.ALL_COMPLETED): |
| 138 | +
|
| 139 | + _futures = futures[:] |
| 140 | + while _futures: |
| 141 | + done, _futures = await aio.wait(_futures, loop=self.loop, |
| 142 | + timeout=timeout, return_when=yield_when) |
| 143 | + if flat: |
| 144 | + for fut in done: |
| 145 | + yield _get_future_result(fut, exc_as_result) |
| 146 | + else: |
| 147 | + yield [_get_future_result(f, exc_as_result) for f in done] |
| 148 | +
|
| 149 | + async def itermap(self, fn, iterable, *, flat=True, exc_as_result=True, |
| 150 | + timeout=None, yield_when=aio.ALL_COMPLETED): |
| 151 | +
|
| 152 | + futures = await self.map_n(fn, iterable) |
| 153 | + generator = self.iterwait(futures, flat=flat, timeout=timeout, |
| 154 | + exc_as_result=exc_as_result, yield_when=yield_when) |
| 155 | + async for batch in generator: |
| 156 | + yield batch # TODO is it possible to return a generator? |
| 157 | + ''' |
0 commit comments