|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import warnings |
| 4 | +from functools import wraps |
| 5 | +from typing import ( |
| 6 | + TYPE_CHECKING, |
| 7 | + Any, |
| 8 | + Callable, |
| 9 | + Dict, |
| 10 | + Optional, |
| 11 | + TypeVar, |
| 12 | + overload, |
| 13 | +) |
| 14 | +from uuid import uuid4 |
| 15 | + |
| 16 | +from typing_extensions import ParamSpec, Self |
| 17 | + |
| 18 | +from taskiq.decor import AsyncTaskiqDecoratedTask |
| 19 | +from taskiq.utils import remove_suffix |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from taskiq.abc.broker import AsyncBroker |
| 23 | + |
| 24 | + |
| 25 | +_FuncParams = ParamSpec("_FuncParams") |
| 26 | +_ReturnType = TypeVar("_ReturnType") |
| 27 | + |
| 28 | + |
| 29 | +class BaseTaskCreator: |
| 30 | + """ |
| 31 | + Base class for task creator. |
| 32 | +
|
| 33 | + Instances of this class are used to make tasks out of the given functions. |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self, broker: "AsyncBroker") -> None: |
| 37 | + self._broker = broker |
| 38 | + self._task_name: Optional[str] = None |
| 39 | + self._labels: Dict[str, Any] = {} |
| 40 | + |
| 41 | + def name(self, name: str) -> Self: |
| 42 | + """Assign custom name to the task.""" |
| 43 | + self._task_name = name |
| 44 | + return self |
| 45 | + |
| 46 | + def labels(self, **labels: Any) -> Self: |
| 47 | + """Assign custom labels to the task.""" |
| 48 | + self._labels = labels |
| 49 | + return self |
| 50 | + |
| 51 | + def make_task( |
| 52 | + self, |
| 53 | + task_name: str, |
| 54 | + func: Callable[_FuncParams, _ReturnType], |
| 55 | + ) -> AsyncTaskiqDecoratedTask[_FuncParams, _ReturnType]: |
| 56 | + """Make a task from the given function.""" |
| 57 | + return AsyncTaskiqDecoratedTask( |
| 58 | + broker=self._broker, |
| 59 | + original_func=func, |
| 60 | + labels=self._labels, |
| 61 | + task_name=task_name, |
| 62 | + ) |
| 63 | + |
| 64 | + @overload |
| 65 | + def __call__( |
| 66 | + self, |
| 67 | + task_name: Callable[_FuncParams, _ReturnType], |
| 68 | + **labels: Any, |
| 69 | + ) -> AsyncTaskiqDecoratedTask[_FuncParams, _ReturnType]: # pragma: no cover |
| 70 | + ... |
| 71 | + |
| 72 | + @overload |
| 73 | + def __call__( |
| 74 | + self, |
| 75 | + task_name: Optional[str] = None, |
| 76 | + **labels: Any, |
| 77 | + ) -> Callable[ |
| 78 | + [Callable[_FuncParams, _ReturnType]], |
| 79 | + AsyncTaskiqDecoratedTask[_FuncParams, _ReturnType], |
| 80 | + ]: # pragma: no cover |
| 81 | + ... |
| 82 | + |
| 83 | + def __call__( # type: ignore[misc] |
| 84 | + self, |
| 85 | + task_name: Optional[str] = None, |
| 86 | + **labels: Any, |
| 87 | + ) -> Any: |
| 88 | + """ |
| 89 | + Decorator that turns function into a task. |
| 90 | +
|
| 91 | + This decorator converts function to |
| 92 | + a `TaskiqDecoratedTask` object. |
| 93 | +
|
| 94 | + This object can be called as a usual function, |
| 95 | + because it uses decorated function in it's __call__ |
| 96 | + method. |
| 97 | +
|
| 98 | + !! You have to use it with parentheses in order to |
| 99 | + get autocompletion. Like this: |
| 100 | +
|
| 101 | + >>> @task() |
| 102 | + >>> def my_func(): |
| 103 | + >>> ... |
| 104 | +
|
| 105 | + :param task_name: custom name of a task, defaults to decorated function's name. |
| 106 | + :param labels: some addition labels for task. |
| 107 | +
|
| 108 | + :returns: decorator function or AsyncTaskiqDecoratedTask. |
| 109 | + """ |
| 110 | + if task_name is not None and isinstance(task_name, str): |
| 111 | + warnings.warn( |
| 112 | + "Using task_name is deprecated, @broker.task.name('name') instead", |
| 113 | + DeprecationWarning, |
| 114 | + stacklevel=2, |
| 115 | + ) |
| 116 | + self._task_name = task_name |
| 117 | + if labels: |
| 118 | + warnings.warn( |
| 119 | + "Using labels is deprecated, @broker.task.labels(**labels) instead", |
| 120 | + DeprecationWarning, |
| 121 | + stacklevel=2, |
| 122 | + ) |
| 123 | + self._labels.update(labels) |
| 124 | + |
| 125 | + def make_decorated_task() -> Callable[ |
| 126 | + [Callable[_FuncParams, _ReturnType]], |
| 127 | + AsyncTaskiqDecoratedTask[_FuncParams, _ReturnType], |
| 128 | + ]: |
| 129 | + def inner( |
| 130 | + func: Callable[_FuncParams, _ReturnType], |
| 131 | + ) -> AsyncTaskiqDecoratedTask[_FuncParams, _ReturnType]: |
| 132 | + inner_task_name = self._task_name |
| 133 | + if inner_task_name is None: |
| 134 | + fmodule = func.__module__ |
| 135 | + if fmodule == "__main__": # pragma: no cover |
| 136 | + fmodule = ".".join( |
| 137 | + remove_suffix(sys.argv[0], ".py").split(os.path.sep), |
| 138 | + ) |
| 139 | + fname = func.__name__ |
| 140 | + if fname == "<lambda>": |
| 141 | + fname = f"lambda_{uuid4().hex}" |
| 142 | + inner_task_name = f"{fmodule}:{fname}" |
| 143 | + |
| 144 | + wrapper = wraps(func) |
| 145 | + decorated_task = wrapper( |
| 146 | + self.make_task( |
| 147 | + task_name=inner_task_name, |
| 148 | + func=func, |
| 149 | + ), |
| 150 | + ) |
| 151 | + |
| 152 | + # We need these ignored lines because |
| 153 | + # `wrap` function copies __annotations__, |
| 154 | + # therefore mypy thinks that decorated_task |
| 155 | + # is still an instance of the original function. |
| 156 | + self._broker._register_task( # noqa: SLF001 |
| 157 | + decorated_task.task_name, # type: ignore |
| 158 | + decorated_task, # type: ignore |
| 159 | + ) |
| 160 | + |
| 161 | + return decorated_task # type: ignore |
| 162 | + |
| 163 | + return inner |
| 164 | + |
| 165 | + if callable(task_name): |
| 166 | + # This is an edge case, |
| 167 | + # when decorator called without parameters. |
| 168 | + return make_decorated_task()(task_name) |
| 169 | + |
| 170 | + return make_decorated_task() |
0 commit comments