|
| 1 | +import asyncio |
| 2 | +from functools import wraps |
| 3 | +from collections import deque |
| 4 | +import attr |
| 5 | +from typing import List, Dict |
| 6 | + |
| 7 | + |
| 8 | +@attr.s(auto_attribs=True) |
| 9 | +class Context: |
| 10 | + in_queue: asyncio.Queue |
| 11 | + out_queue: asyncio.Queue |
| 12 | + initialized: bool |
| 13 | + |
| 14 | + |
| 15 | +def run_sequentially_in_context(target_args: List[str] = None): |
| 16 | + """All request to function with same calling context will be run sequentially. |
| 17 | +
|
| 18 | + Example: |
| 19 | +
|
| 20 | + Given the following decorated function |
| 21 | +
|
| 22 | + @run_sequentially_in_context(target_args=["param3", "param1"]) |
| 23 | + async def func(param1, param2, param3): |
| 24 | + await asyncio.sleep(1) |
| 25 | +
|
| 26 | + The context will be formed by the values of the arguments "param3" and "param1". |
| 27 | + The values must be serializable as they will be converted to string |
| 28 | + and put together as storage key for the context. |
| 29 | +
|
| 30 | + The below calls will all run in a sequence: |
| 31 | +
|
| 32 | + functions = [ |
| 33 | + func(1, "something", 3), |
| 34 | + func(1, "else", 3), |
| 35 | + func(1, "here", 3), |
| 36 | + ] |
| 37 | + await asyncio.gather(*functions) |
| 38 | +
|
| 39 | + The following calls will run in parallel, because they have different contexts: |
| 40 | +
|
| 41 | + functions = [ |
| 42 | + func(1, "something", 3), |
| 43 | + func(2, "else", 3), |
| 44 | + func(3, "here", 3), |
| 45 | + ] |
| 46 | + await asyncio.gather(*functions) |
| 47 | +
|
| 48 | + """ |
| 49 | + target_args = [] if target_args is None else target_args |
| 50 | + |
| 51 | + def internal(decorated_function): |
| 52 | + contexts = {} |
| 53 | + |
| 54 | + def get_context(args, kwargs: Dict) -> Context: |
| 55 | + arg_names = decorated_function.__code__.co_varnames[ |
| 56 | + : decorated_function.__code__.co_argcount |
| 57 | + ] |
| 58 | + search_args = dict(zip(arg_names, args)) |
| 59 | + search_args.update(kwargs) |
| 60 | + |
| 61 | + key_parts = deque() |
| 62 | + for arg in target_args: |
| 63 | + if arg not in search_args: |
| 64 | + message = ( |
| 65 | + f"Expected '{arg}' in '{decorated_function.__name__}'" |
| 66 | + f" arguments. Got '{search_args}'" |
| 67 | + ) |
| 68 | + raise ValueError(message) |
| 69 | + key_parts.append(search_args[arg]) |
| 70 | + |
| 71 | + key = ":".join(map(str, key_parts)) |
| 72 | + |
| 73 | + if key not in contexts: |
| 74 | + contexts[key] = Context( |
| 75 | + in_queue=asyncio.Queue(), |
| 76 | + out_queue=asyncio.Queue(), |
| 77 | + initialized=False, |
| 78 | + ) |
| 79 | + |
| 80 | + return contexts[key] |
| 81 | + |
| 82 | + @wraps(decorated_function) |
| 83 | + async def wrapper(*args, **kwargs): |
| 84 | + context: Context = get_context(args, kwargs) |
| 85 | + |
| 86 | + if not context.initialized: |
| 87 | + context.initialized = True |
| 88 | + |
| 89 | + async def worker(in_q: asyncio.Queue, out_q: asyncio.Queue): |
| 90 | + while True: |
| 91 | + awaitable = await in_q.get() |
| 92 | + in_q.task_done() |
| 93 | + try: |
| 94 | + result = await awaitable |
| 95 | + except Exception as e: # pylint: disable=broad-except |
| 96 | + result = e |
| 97 | + await out_q.put(result) |
| 98 | + |
| 99 | + asyncio.get_event_loop().create_task( |
| 100 | + worker(context.in_queue, context.out_queue) |
| 101 | + ) |
| 102 | + |
| 103 | + await context.in_queue.put(decorated_function(*args, **kwargs)) |
| 104 | + |
| 105 | + wrapped_result = await context.out_queue.get() |
| 106 | + if isinstance(wrapped_result, Exception): |
| 107 | + raise wrapped_result |
| 108 | + |
| 109 | + return wrapped_result |
| 110 | + |
| 111 | + return wrapper |
| 112 | + |
| 113 | + return internal |
0 commit comments