|
| 1 | +--- |
| 2 | +order: 7 |
| 3 | +--- |
| 4 | + |
| 5 | +# State and Dependencies |
| 6 | + |
| 7 | + |
| 8 | +## State |
| 9 | + |
| 10 | +The `TaskiqState` is a global variable where you can keep the variables you want to use later. |
| 11 | +For example, you want to open a database connection pool at a broker's startup. |
| 12 | + |
| 13 | +This can be acieved by adding event handlers. |
| 14 | + |
| 15 | +You can use one of these events: |
| 16 | +* `WORKER_STARTUP` |
| 17 | +* `CLIENT_STARTUP` |
| 18 | +* `WORKER_SHUTDOWN` |
| 19 | +* `CLIENT_SHUTDOWN` |
| 20 | + |
| 21 | +Worker events are called when you start listening to the broker messages using taskiq. |
| 22 | +Client events are called when you call the `startup` method of your broker from your code. |
| 23 | + |
| 24 | +This is an example of code using event handlers: |
| 25 | + |
| 26 | +@[code python](../examples/state/events_example.py) |
| 27 | + |
| 28 | +::: tip Cool tip! |
| 29 | + |
| 30 | +If you want to add handlers programmatically, you can use the `broker.add_event_handler` function. |
| 31 | + |
| 32 | +::: |
| 33 | + |
| 34 | +As you can see in this example, this worker will initialize the Redis pool at the startup. |
| 35 | +You can access the state from the context. |
| 36 | + |
| 37 | + |
| 38 | +## Dependencies |
| 39 | + |
| 40 | +Using context directly is nice, but this way won't get completion. |
| 41 | + |
| 42 | +That's why we suggest you try TaskiqDependencies. The implementation is very similar to FastApi's dependencies. You can use classes, functions, and generators as dependencies. |
| 43 | + |
| 44 | +::: danger Cool alarm! |
| 45 | + |
| 46 | +FastAPI's `Depends` is not compatible with `TaskiqDepends`. |
| 47 | + |
| 48 | +::: |
| 49 | + |
| 50 | +### How dependencies are useful |
| 51 | + |
| 52 | +You can use dependencies for better autocompletion and reduce the amount of code you write. |
| 53 | +Since the state is generic, we cannot guess the types of the state fields. |
| 54 | +Dependencies can be annotated with type hints and therfore provide better auto-completion. |
| 55 | + |
| 56 | +Let's assume that you've stored a Redis connection pool in the state as in the example above. |
| 57 | +```python |
| 58 | +@broker.on_event(TaskiqEvents.WORKER_STARTUP) |
| 59 | +async def startup(state: TaskiqState) -> None: |
| 60 | + # Here we store connection pool on startup for later use. |
| 61 | + state.redis = ConnectionPool.from_url("redis://localhost/1") |
| 62 | + |
| 63 | +``` |
| 64 | + |
| 65 | +You can access this variable by using the current execution context directly, like this: |
| 66 | + |
| 67 | +```python |
| 68 | +@broker.task |
| 69 | +async def my_task(context: Context = TaskiqDepends()) -> None: |
| 70 | + async with Redis(connection_pool=context.state.redis, decode_responses=True) as redis: |
| 71 | + await redis.set('key', 'value') |
| 72 | +``` |
| 73 | + |
| 74 | +If you hit the `TAB` button after the `context.state.` expression, your IDE won't give you any auto-completion. |
| 75 | +But we can create a dependency function to add auto-completion. |
| 76 | + |
| 77 | +```python |
| 78 | + |
| 79 | +def redis_dep(context: Context = TaskiqDepends()) -> Redis: |
| 80 | + return Redis(connection_pool=context.state.redis, decode_responses=True) |
| 81 | + |
| 82 | +@broker.task |
| 83 | +async def my_task(redis: Redis = TaskiqDepends(redis_dep)) -> None: |
| 84 | + await redis.set('key', 'value') |
| 85 | + |
| 86 | +``` |
| 87 | + |
| 88 | +Now, this dependency injection will be autocompleted. But, of course, state fields cannot be autocompleted, |
| 89 | +even in dependencies. But this way, you won't make any typos while writing tasks. |
| 90 | + |
| 91 | + |
| 92 | +### How do dependencies work |
| 93 | + |
| 94 | +We build a graph of dependencies on startup. If the parameter of the function has |
| 95 | +the default value of `TaskiqDepends` this parameter will be treated as a dependency. |
| 96 | + |
| 97 | +Dependencies can also depend on something. Also dependencies are optimized to **not** evaluate things many times. |
| 98 | + |
| 99 | +For example: |
| 100 | + |
| 101 | +@[code python](../examples/state/dependencies_tree.py) |
| 102 | + |
| 103 | +In this code, the dependency `common_dep` is going to be evaluated only once and the `dep1` and the `dep2` are going to recevie the same value. You can control this behaviour by using the `use_cache=False` parameter to you dependency. This parameter will force the |
| 104 | +dependency to reevaluate all it's subdependencies. |
| 105 | + |
| 106 | + |
| 107 | +In this example we cannot predict the result. Since the `dep2` doesn't use cache for the `common_dep` function. |
| 108 | +@[code python](../examples/state/no_cache.py) |
| 109 | + |
| 110 | +The graph for cached dependencies looks like this: |
| 111 | + |
| 112 | +```mermaid |
| 113 | +graph TD |
| 114 | + A[common_dep] |
| 115 | + B[dep1] |
| 116 | + C[dep2] |
| 117 | + D[my_task] |
| 118 | + A --> B |
| 119 | + A --> C |
| 120 | + B --> D |
| 121 | + C --> D |
| 122 | +``` |
| 123 | + |
| 124 | +The dependencies graph for `my_task` where `dep2` doesn't use cached value for `common_dep` looks like this: |
| 125 | + |
| 126 | +```mermaid |
| 127 | +graph TD |
| 128 | + A[common_dep] |
| 129 | + B[dep1] |
| 130 | + D[my_task] |
| 131 | + C[dep2] |
| 132 | + subgraph without cache |
| 133 | + A1[common_dep] |
| 134 | + end |
| 135 | + A --> B |
| 136 | + A1 --> C |
| 137 | + B --> D |
| 138 | + C --> D |
| 139 | +``` |
| 140 | + |
| 141 | +### Class as a dependency |
| 142 | + |
| 143 | +You can use classes as dependencies, and they can also use other dependencies too. |
| 144 | + |
| 145 | +Let's see an example: |
| 146 | + |
| 147 | +@[code python](../examples/state/class_dependency.py) |
| 148 | + |
| 149 | +As you can see, the dependency for `my_task` function is declared with `TaskiqDependency()`. |
| 150 | +It's because you can omit the class if it's declared in typehint for the parameter. This feature doesn't |
| 151 | +work with dependency functions, it's only for classes. |
| 152 | + |
| 153 | +You can pass dependencies for classes in the constructor. |
| 154 | + |
| 155 | +### Generator dependencies |
| 156 | + |
| 157 | +Generator dependencies are used to perform startup before task execution and teardown after the task execution. |
| 158 | + |
| 159 | +@[code python](../examples/state/generator_deps.py) |
| 160 | + |
| 161 | +In this example, we can do something at startup before the execution and at shutdown after the task is completed. |
| 162 | + |
| 163 | +If you want to do something asynchronously, convert this function to an asynchronous generator. Like this: |
| 164 | + |
| 165 | +@[code python](../examples/state/async_generator_deps.py) |
| 166 | + |
| 167 | + |
| 168 | +### Default dependencies |
| 169 | + |
| 170 | +By default taskiq has only two deendencies: |
| 171 | +* Context from `taskiq.context.Context` |
| 172 | +* TaskiqState from `taskiq.state.TaskiqState` |
0 commit comments