| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Utilities for use with asynchronous code.""" |
| 17 |
|
| 18 |
import asyncio |
| 19 |
from contextlib import asynccontextmanager |
| 20 |
from functools import partial, wraps |
| 21 |
from inspect import signature |
| 22 |
import os |
| 23 |
from pathlib import Path |
| 24 |
from typing import List, Union |
| 25 |
|
| 26 |
from cylc.flow import LOG |
| 27 |
|
| 28 |
|
| 29 |
class _AsyncPipe: |
| 30 |
"""Implement the @pipe interface. |
| 31 |
|
| 32 |
Represents and implements an asynchronous pipe. |
| 33 |
|
| 34 |
Note: |
| 35 |
_AsyncPipe objects are created when you construct a pipe (using __or__) |
| 36 |
or attempt to iterate over an @pipe function. |
| 37 |
|
| 38 |
Attrs: |
| 39 |
func (callable): |
| 40 |
The function that this stage of the pipe represents. |
| 41 |
args (tuple): |
| 42 |
Args to call the function with. |
| 43 |
kwargs (dict): |
| 44 |
Kwargs to call the function with. |
| 45 |
filter_stop (bool): |
| 46 |
If True then items which fail a filter will not get yielded. |
| 47 |
If False then they will get yielded immediately. |
| 48 |
preserve_order (bool): |
| 49 |
If True then this will behave like a "conventional" pipe i.e. |
| 50 |
first-in first-out. |
| 51 |
|
| 52 |
If False then results will be yielded as soon as they arrive. |
| 53 |
|
| 54 |
Concurrency is the same for both options as results get cached |
| 55 |
in the first case. |
| 56 |
_left (_AsyncPipe): |
| 57 |
The previous item in the pipe or None. |
| 58 |
_right (_AsyncPipe): |
| 59 |
The next item in the pipe or None. |
| 60 |
|
| 61 |
""" |
| 62 |
|
| 63 |
def __init__( |
| 64 |
self, |
| 65 |
func, |
| 66 |
args=None, |
| 67 |
kwargs=None, |
| 68 |
filter_stop=True, |
| 69 |
preserve_order=True |
| 70 |
): |
| 71 |
self.func = func |
| 72 |
self.args = args or () |
| 73 |
self.kwargs = kwargs or {} |
| 74 |
self.filter_stop = filter_stop |
| 75 |
self.preserve_order = preserve_order |
| 76 |
self._left = None |
| 77 |
self._right = None |
| 78 |
|
| 79 |
async def __aiter__(self): |
| 80 |
# aiter = async iter |
| 81 |
coros = self.__iter__() |
| 82 |
gen = next(coros) # the generator we start the pipe with |
| 83 |
coros = list(coros) # the coros to push data through |
| 84 |
running = [] # list of running asyncio tasks |
| 85 |
completed = asyncio.Queue() # queue of processed items to yield |
| 86 |
try: |
| 87 |
# run the generator |
| 88 |
running.append( |
| 89 |
asyncio.create_task( |
| 90 |
self._generate(gen, coros, running, completed) |
| 91 |
) |
| 92 |
) |
| 93 |
# push the data through the pipe and yield results |
| 94 |
if self.preserve_order: |
| 95 |
meth = self._ordered |
| 96 |
else: |
| 97 |
meth = self._unordered |
| 98 |
async for item in meth(running, completed): |
| 99 |
yield item |
| 100 |
finally: |
| 101 |
# tidy up after ourselves |
| 102 |
for task in running: |
| 103 |
task.cancel() |
| 104 |
|
| 105 |
async def _ordered(self, running, completed): |
| 106 |
"""The classic first-in first-out pipe behaviour.""" |
| 107 |
cache = {} # cache of results {index: result} |
| 108 |
skip_cache = [] # list of results which have been filtered out |
| 109 |
yield_ind = 0 # the result index used when preserve_order == True |
| 110 |
|
| 111 |
while cache or running or not completed.empty(): |
| 112 |
# cache any completed items |
| 113 |
if not completed.empty(): |
| 114 |
ind, item = await completed.get() |
| 115 |
# add the item to the cache so we can yield in order |
| 116 |
cache[ind] = item |
| 117 |
# skip over any results which have been filtered out |
| 118 |
while yield_ind in skip_cache: |
| 119 |
skip_cache.remove(yield_ind) |
| 120 |
yield_ind += 1 |
| 121 |
# yield any cached results |
| 122 |
while yield_ind in cache: |
| 123 |
yield cache.pop(yield_ind) |
| 124 |
yield_ind += 1 |
| 125 |
# process completed tasks |
| 126 |
for task in running: |
| 127 |
if task.done(): |
| 128 |
running.remove(task) |
| 129 |
ind = task.result() |
| 130 |
if ind is not None: |
| 131 |
# this item has been filtered out |
| 132 |
skip_cache.append(ind) |
| 133 |
|
| 134 |
await asyncio.sleep(0) # don't allow this loop to block |
| 135 |
|
| 136 |
async def _unordered(self, running, completed): |
| 137 |
"""The optimal yield items as they are processed behaviour.""" |
| 138 |
while running or not completed.empty(): |
| 139 |
# return any completed items |
| 140 |
if not completed.empty(): |
| 141 |
_, item = await completed.get() |
| 142 |
yield item |
| 143 |
# process completed tasks |
| 144 |
for task in running: |
| 145 |
if task.done(): |
| 146 |
running.remove(task) |
| 147 |
|
| 148 |
await asyncio.sleep(0) # don't allow this loop to block |
| 149 |
|
| 150 |
async def _generate(self, gen, coros, running, completed): |
| 151 |
"""Pull data out of the generator.""" |
| 152 |
ind = 0 |
| 153 |
async for item in gen.func(*gen.args, **gen.kwargs): |
| 154 |
running.append( |
| 155 |
asyncio.create_task( |
| 156 |
self._chain((ind, item), coros, completed) |
| 157 |
) |
| 158 |
) |
| 159 |
ind += 1 |
| 160 |
|
| 161 |
async def _chain(self, item, coros, completed): |
| 162 |
"""Push data through the coroutine pipe.""" |
| 163 |
ind, item = item |
| 164 |
for coro in coros: |
| 165 |
try: |
| 166 |
ret = await coro.func(item, *coro.args, **coro.kwargs) |
| 167 |
except Exception as exc: |
| 168 |
# if something goes wrong log the error and skip the item |
| 169 |
LOG.warning(exc) |
| 170 |
ret = False |
| 171 |
if ret is True: |
| 172 |
# filter passed -> continue |
| 173 |
continue |
| 174 |
elif ret is False and coro.filter_stop: |
| 175 |
# filter failed -> stop |
| 176 |
return ind |
| 177 |
elif ret is False: |
| 178 |
# filter failed but pipe configured to yield -> stop + yield |
| 179 |
break |
| 180 |
else: |
| 181 |
# returned an object -> continue |
| 182 |
item = ret |
| 183 |
await completed.put((ind, item)) |
| 184 |
|
| 185 |
def __or__(self, other): |
| 186 |
if isinstance(other, _PipeFunction): |
| 187 |
other = _AsyncPipe(other.func) |
| 188 |
other._left = self |
| 189 |
self.fastforward()._right = other |
| 190 |
# because we return self we only need __or__ not __ror__ |
| 191 |
return self |
| 192 |
|
| 193 |
def rewind(self): |
| 194 |
"""Return the head of the pipe.""" |
| 195 |
ptr = self |
| 196 |
while ptr._left: |
| 197 |
ptr = ptr._left |
| 198 |
return ptr |
| 199 |
|
| 200 |
def fastforward(self): |
| 201 |
"""Return the tail of the pipe.""" |
| 202 |
ptr = self |
| 203 |
while ptr._right: |
| 204 |
ptr = ptr._right |
| 205 |
return ptr |
| 206 |
|
| 207 |
def __iter__(self): |
| 208 |
ptr = self.rewind() |
| 209 |
while ptr._right: |
| 210 |
yield ptr |
| 211 |
ptr = ptr._right |
| 212 |
yield ptr |
| 213 |
|
| 214 |
def __repr__(self): |
| 215 |
return ' | '.join((str(ptr) for ptr in self)) |
| 216 |
|
| 217 |
def __str__(self): |
| 218 |
args = '' |
| 219 |
if self.args: |
| 220 |
args = ', '.join(map(repr, self.args)) |
| 221 |
if self.kwargs: |
| 222 |
if args: |
| 223 |
args += ', ' |
| 224 |
args += ', '.join(f'{k}={repr(v)}' for k, v in self.kwargs.items()) |
| 225 |
return f'{self.func.__name__}({args})' |
| 226 |
|
| 227 |
|
| 228 |
class _PipeFunction: |
| 229 |
"""Represent a function for use in an async pipe. |
| 230 |
|
| 231 |
This class is just for syntactic sugar, it enables us to assign arguments |
| 232 |
via the __call__ interface and enables us to add an interface for |
| 233 |
preprocessing args. |
| 234 |
|
| 235 |
""" |
| 236 |
|
| 237 |
def __init__(self, func, preproc=None): |
| 238 |
self.func = func |
| 239 |
self.preproc = preproc |
| 240 |
|
| 241 |
def __call__(self, *args, filter_stop=True, **kwargs): |
| 242 |
# assign args/kwargs to a function in a pipe |
| 243 |
if self.preproc: |
| 244 |
args, kwargs = self.preproc(*args, **kwargs) |
| 245 |
return _AsyncPipe( |
| 246 |
self.func, |
| 247 |
args, |
| 248 |
kwargs, |
| 249 |
filter_stop |
| 250 |
) |
| 251 |
|
| 252 |
def __or__(self, other): |
| 253 |
this = _AsyncPipe(self.func) |
| 254 |
return this | other |
| 255 |
|
| 256 |
async def __aiter__(self): |
| 257 |
# this permits pipes with only one step |
| 258 |
async for item in _AsyncPipe(self.func): |
| 259 |
yield item |
| 260 |
|
| 261 |
def __str__(self): |
| 262 |
return _AsyncPipe(self.func).__str__() |
| 263 |
|
| 264 |
def __repr__(self): |
| 265 |
return _AsyncPipe(self.func).__repr__() |
| 266 |
|
| 267 |
@property |
| 268 |
def __name__(self): |
| 269 |
return self.func.__name__ |
| 270 |
|
| 271 |
@property |
| 272 |
def __doc__(self): |
| 273 |
return self.func.__doc__ |
| 274 |
|
| 275 |
@property |
| 276 |
def __signature__(self): |
| 277 |
return signature(self.func) |
| 278 |
|
| 279 |
@property |
| 280 |
def __annotations__(self): |
| 281 |
return self.func.__annotations__ |
| 282 |
|
| 283 |
|
| 284 |
def pipe(func=None, preproc=None): |
| 285 |
"""An asynchronous pipe implementation in pure Python. |
| 286 |
|
| 287 |
Use this to decorate async functions in order to arrange them into |
| 288 |
asynchronous pipes. These pipes can process multiple items through multiple |
| 289 |
stages of the pipe simultaneously by doing what processing it can whilst |
| 290 |
waiting on IO to take place in the background. |
| 291 |
|
| 292 |
Async pipes perform maximum concurrency running as far ahead as they can. |
| 293 |
Don't use for cases where you only want the first N items as the pipe may |
| 294 |
process items outside of this window. |
| 295 |
|
| 296 |
Args: |
| 297 |
func (callable): |
| 298 |
The function this decorator decorates. |
| 299 |
preproc (callable): |
| 300 |
An optional function for pre-processing any args or kwargs |
| 301 |
provided to a function when the pipe is created. |
| 302 |
|
| 303 |
preproc(args: tuple, kwargs: dict) -> (args: tuple, kwargs: dict) |
| 304 |
|
| 305 |
Example: |
| 306 |
A generator to begin our pipe with: |
| 307 |
>>> @pipe |
| 308 |
... async def arange(): |
| 309 |
... for i in range(10): |
| 310 |
... yield i |
| 311 |
|
| 312 |
A filter which returns a boolean: |
| 313 |
>>> @pipe |
| 314 |
... async def even(x): |
| 315 |
... # note the first argument (x) is the value passed down the pipe |
| 316 |
... return x % 2 == 0 |
| 317 |
|
| 318 |
A transformation returns anything other than a boolean: |
| 319 |
>>> @pipe |
| 320 |
... async def mult(x, y): |
| 321 |
... # note subsequent args must be provided when you build the pipe |
| 322 |
... return x * y |
| 323 |
|
| 324 |
Assemble them into a pipe |
| 325 |
>>> mypipe = arange | even | mult(2) |
| 326 |
>>> mypipe |
| 327 |
arange() | even() | mult(2) |
| 328 |
|
| 329 |
Write a function to "consume items": |
| 330 |
>>> async def consumer(pipe): |
| 331 |
... async for item in pipe: |
| 332 |
... print(item) |
| 333 |
|
| 334 |
Run pipe run: |
| 335 |
>>> import asyncio |
| 336 |
>>> asyncio.run(consumer(mypipe)) |
| 337 |
0 |
| 338 |
4 |
| 339 |
8 |
| 340 |
12 |
| 341 |
16 |
| 342 |
|
| 343 |
Real world examples will involve a bit of awaiting. |
| 344 |
|
| 345 |
Result Order |
| 346 |
By default this behaves like a "conventional" pipe where results |
| 347 |
are yielded in the order which the generator at the start of the pipe |
| 348 |
created them. |
| 349 |
|
| 350 |
By setting the ``preserve_order`` attribute on a pipe to ``False`` |
| 351 |
you can make it yield items as soon as they are processed irrespective |
| 352 |
or order for more immediate results e.g:: |
| 353 |
|
| 354 |
pipe = arange | even |
| 355 |
pipe.preserve_order = False |
| 356 |
|
| 357 |
Providing Arguments To Functions: |
| 358 |
The first function in the pipe will receive no data. All subsequent |
| 359 |
functions will receive the result of the previous function |
| 360 |
as its first argument (unless the previous function was a filter). |
| 361 |
|
| 362 |
To provide extra args/kwargs call the function when the pipe is |
| 363 |
being constructed e.g:: |
| 364 |
|
| 365 |
pipe = my_function(arg1, kwarg1='x') |
| 366 |
|
| 367 |
If you want to transform args/kwargs before running the pipe use the |
| 368 |
``preproc`` argument e.g:: |
| 369 |
|
| 370 |
def my_preproc(*args, **kwargs): |
| 371 |
# do some transformation |
| 372 |
return args, kwargs |
| 373 |
|
| 374 |
@pipe(preproc=my_preproc) |
| 375 |
def my_pipe_step(x, *args, *kwargs): pass |
| 376 |
|
| 377 |
Filters And Transforms: |
| 378 |
If a function in the pipe returns a bool then it will be interpreted |
| 379 |
as a filter. If it returns any other object then it is a transform. |
| 380 |
|
| 381 |
Transforms mutate data as it passes through the pipe. |
| 382 |
|
| 383 |
Filters stop data from travelling further through the pipe. |
| 384 |
True means the filter passed, False means it failed. |
| 385 |
By default if a value fails a filter then it will not get yielded, |
| 386 |
you can change this using the filter_stop argument e.g:: |
| 387 |
|
| 388 |
# if the filter fails yield the item straight away |
| 389 |
# if it passes run the item through function and yield the result |
| 390 |
pipe = generator | filter(filter_stop=False) | function |
| 391 |
|
| 392 |
""" |
| 393 |
if preproc and not func: |
| 394 |
# @pipe(preproc=x) |
| 395 |
def _pipe(func): |
| 396 |
return _PipeFunction(func, preproc) |
| 397 |
return _pipe |
| 398 |
elif func: |
| 399 |
# @pipe |
| 400 |
return _PipeFunction(func) |
| 401 |
else: |
| 402 |
# @pipe() |
| 403 |
def _pipe(func): |
| 404 |
return _PipeFunction(func) |
| 405 |
return _pipe |
| 406 |
|
| 407 |
|
| 408 |
async def scandir(path: Union[Path, str]) -> List[Path]: |
| 409 |
"""Asynchronous directory listing (performs os.listdir in an executor).""" |
| 410 |
return [ |
| 411 |
Path(path, sub_path) |
| 412 |
for sub_path in await async_listdir(path) |
| 413 |
] |
| 414 |
|
| 415 |
|
| 416 |
async def asyncqgen(queue): |
| 417 |
"""Turn a queue into an async generator.""" |
| 418 |
while not queue.empty(): |
| 419 |
yield await queue.get() |
| 420 |
|
| 421 |
|
| 422 |
def wrap_exception(coroutine): |
| 423 |
"""Catch and return exceptions rather than raising them. |
| 424 |
|
| 425 |
Examples: |
| 426 |
>>> async def myfcn(): |
| 427 |
... raise Exception('foo') |
| 428 |
>>> mywrappedfcn = wrap_exception(myfcn) |
| 429 |
>>> ret = asyncio.run(mywrappedfcn()) # the exception is not raised... |
| 430 |
>>> ret # ...it is returned |
| 431 |
Exception('foo') |
| 432 |
|
| 433 |
""" |
| 434 |
async def _inner(*args, **kwargs): |
| 435 |
try: |
| 436 |
return await coroutine(*args, **kwargs) |
| 437 |
except Exception as exc: |
| 438 |
return exc |
| 439 |
|
| 440 |
return _inner |
| 441 |
|
| 442 |
|
| 443 |
async def unordered_map(coroutine, iterator, wrap_exceptions=False): |
| 444 |
"""An asynchronous map function which does not preserve order. |
| 445 |
|
| 446 |
Use in situations where you want results as they are completed rather than |
| 447 |
once they are all completed. |
| 448 |
|
| 449 |
Args: |
| 450 |
coroutine: |
| 451 |
The async function you want to call. |
| 452 |
iterator: |
| 453 |
The arguments you want to call it with. |
| 454 |
wrap_exceptions: |
| 455 |
If True, then exceptions will be caught and returned rather than |
| 456 |
raised. |
| 457 |
|
| 458 |
Example: |
| 459 |
# define your async coroutine |
| 460 |
>>> async def square(x): return x**2 |
| 461 |
|
| 462 |
# define your iterator (must yield tuples) |
| 463 |
>>> iterator = [(num,) for num in range(5)] |
| 464 |
|
| 465 |
# use `async for` to iterate over the results |
| 466 |
# (sorted in this case so the test is repeatable) |
| 467 |
>>> async def test(): |
| 468 |
... ret = [] |
| 469 |
... async for x in unordered_map(square, iterator): |
| 470 |
... ret.append(x) |
| 471 |
... return sorted(ret) |
| 472 |
>>> asyncio.run(test()) |
| 473 |
[((0,), 0), ((1,), 1), ((2,), 4), ((3,), 9), ((4,), 16)] |
| 474 |
|
| 475 |
""" |
| 476 |
if wrap_exceptions: |
| 477 |
coroutine = wrap_exception(coroutine) |
| 478 |
|
| 479 |
# create tasks |
| 480 |
pending = [] |
| 481 |
for args in iterator: |
| 482 |
task = asyncio.create_task(coroutine(*args)) |
| 483 |
task._args = args |
| 484 |
pending.append(task) |
| 485 |
|
| 486 |
# run tasks |
| 487 |
while pending: |
| 488 |
done, pending = await asyncio.wait( |
| 489 |
pending, |
| 490 |
return_when=asyncio.FIRST_COMPLETED |
| 491 |
) |
| 492 |
for task in done: |
| 493 |
yield task._args, task.result() |
| 494 |
|
| 495 |
|
| 496 |
def make_async(fcn): |
| 497 |
"""Make a synchronous function async by running it in an executor. |
| 498 |
|
| 499 |
The default asyncio executor is the ThreadPoolExecutor so this essentially |
| 500 |
syntactic sugar for running the wrapped function in a thread. |
| 501 |
""" |
| 502 |
@wraps(fcn) |
| 503 |
async def _fcn(*args, executor=None, **kwargs): |
| 504 |
return await asyncio.get_event_loop().run_in_executor( |
| 505 |
executor, |
| 506 |
partial(fcn, *args, **kwargs), |
| 507 |
) |
| 508 |
|
| 509 |
return _fcn |
| 510 |
|
| 511 |
|
| 512 |
async_listdir = make_async(os.listdir) |
| 513 |
|
| 514 |
|
| 515 |
@asynccontextmanager |
| 516 |
async def async_block(): |
| 517 |
"""Ensure all tasks started within the context are awaited when it closes. |
| 518 |
|
| 519 |
Normally, you would await a task e.g: |
| 520 |
|
| 521 |
await three() |
| 522 |
|
| 523 |
If it's possible to await the task, do that, however, this isn't always an |
| 524 |
option. This interface exists is to help patch over issues where async code |
| 525 |
(one) calls sync code (two) which calls async code (three) e.g: |
| 526 |
|
| 527 |
async def one(): |
| 528 |
two() |
| 529 |
|
| 530 |
def two(): |
| 531 |
# this breaks - event loop is already running |
| 532 |
asyncio.get_event_loop().run_until_complete(three()) |
| 533 |
|
| 534 |
async def three(): |
| 535 |
await asyncio.sleep(1) |
| 536 |
|
| 537 |
This code will error because you can't nest asyncio (without nest-asyncio) |
| 538 |
which means you can schedule tasks the tasks in "two", but you can't await |
| 539 |
them. |
| 540 |
|
| 541 |
def two(): |
| 542 |
# this works, but it doesn't wait for three() to complete |
| 543 |
asyncio.create_task(three()) |
| 544 |
|
| 545 |
This interface allows you to await the tasks |
| 546 |
|
| 547 |
async def one() |
| 548 |
async with async_block(): |
| 549 |
two() |
| 550 |
# any tasks two() started will have been awaited by now |
| 551 |
""" |
| 552 |
# make a list of all tasks running before we enter the context manager |
| 553 |
tasks_before = asyncio.all_tasks() |
| 554 |
# run the user code |
| 555 |
yield |
| 556 |
# await any new tasks |
| 557 |
await asyncio.gather(*(asyncio.all_tasks() - tasks_before)) |