userver: userver/concurrent/background_task_storage.hpp Source File
Loading...
Searching...
No Matches
background_task_storage.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/concurrent/background_task_storage.hpp
4/// @brief @copybrief concurrent::BackgroundTaskStorage
5
6#include <cstdint>
7#include <utility>
8
9#include <userver/engine/impl/detached_tasks_sync_block.hpp>
10#include <userver/engine/task/task_processor_fwd.hpp>
11#include <userver/utils/async.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace concurrent {
16
17/// @ingroup userver_concurrency userver_containers
18///
19/// A version of concurrent::BackgroundTaskStorage for advanced use cases (e.g.
20/// driver internals) that can take the ownership of any kind of task.
21class BackgroundTaskStorageCore final {
22public:
23 /// Creates an empty BTS.
25
26 BackgroundTaskStorageCore(BackgroundTaskStorageCore&&) = delete;
27 BackgroundTaskStorageCore& operator=(BackgroundTaskStorageCore&&) = delete;
28 ~BackgroundTaskStorageCore();
29
30 /// @brief Explicitly cancel and wait for the tasks.
31 /// New tasks must not be launched after this call returns.
32 ///
33 /// More precisely, new tasks must not be launched once this call is completed, but can be launched in the process
34 /// of waiting for the remaining tasks. This means that one detached task is allowed to spawn another detached
35 /// task into the same BTS, which will immediately be cancelled and for which this call will wait as well.
36 ///
37 /// Can only be called from a coroutine.
38 void CancelAndWait() noexcept;
39
40 /// @brief Wait for the remaining tasks to complete without cancelling them.
41 /// New tasks must not be launched after this call returns.
42 ///
43 /// More precisely, new tasks must not be launched once this call is completed, but can be launched in the process
44 /// of waiting for the remaining tasks. This means that one detached task is allowed to spawn another detached
45 /// task into the same BTS, for which this call will wait as well.
46 ///
47 /// @note Running this method burns some CPU time (a few microseconds). Awaiting the tasks once on service
48 /// shutdown, or even periodically, is okay, but don't use `BackgroundTaskStorage` as a substitute
49 /// for `std::vector<Task>` in handlers, because it is less efficient.
50 ///
51 /// Can only be called from a coroutine.
52 void WaitAndDisposeSlow() noexcept;
53
54 /// @brief Detaches task, allowing it to continue execution out of scope. It
55 /// will be cancelled and waited for on BTS destruction.
56 /// @note After detach, Task becomes invalid
57 ///
58 /// If this function throws (due to OOM), the task is cancelled and waited for before the exception
59 /// is rethrown. The task may already have started; its side effects are not rolled back.
60 /// After the exception, the task does not keep running.
61 ///
62 /// Can be called from a coroutine or a non-coroutine thread.
63 /// Cannot be called after @ref CancelAndWait or @ref WaitAndDisposeSlow has been called.
64 void Detach(engine::Task&& task);
65
66 /// @returns Approximate number of currently active tasks.
67 ///
68 /// Can be called from a coroutine or a non-coroutine thread.
69 /// Cannot be called after @ref CancelAndWait or @ref WaitAndDisposeSlow has been called.
70 std::int64_t ActiveTasksApprox() const noexcept;
71
72private:
73 std::optional<engine::impl::DetachedTasksSyncBlock> sync_block_;
74};
75
76/// @ingroup userver_concurrency userver_containers
77///
78/// A storage that allows one to start detached tasks; cancels and waits for
79/// unfinished tasks completion at the destructor. Provides CancelAndWait to
80/// explicitly cancel tasks (recommended).
81///
82/// Usable for detached tasks that capture references to resources with a
83/// limited lifetime. You must guarantee that the resources are available while
84/// the BackgroundTaskStorage is alive.
85///
86/// ## Performance considerations
87///
88/// Tasks remove themselves from the BackgroundTaskStorage on completion, so there is no memory leak.
89///
90/// @warning The implementation is optimized for spawning tasks. Waiting for remaining tasks may be slow CPU-wise.
91/// As a guideline, do not create `BackgroundTaskStorage` instances for each request, use `std::vector<Task>`
92/// for storing per-request child tasks instead.
93///
94/// ## Usage synopsis
95///
96/// @snippet core/src/concurrent/background_task_storage_test.cpp Sample
97///
98/// ## Lifetime of task's captures
99///
100/// All the advice from utils::Async is applicable here.
101///
102/// BackgroundTaskStorage is always stored as a class field. Tasks that are
103/// launched inside it (or moved inside it, for BackgroundTaskStorageCore)
104/// can safely access fields declared before it, but not after it:
105///
106/// @snippet core/src/concurrent/background_task_storage_test.cpp BtsLifetimeCapturesPitfalls
107///
108/// Generally, it's a good idea to declare `bts_` after most other fields
109/// to avoid lifetime bugs. An example of fool-proof code:
110///
111/// @snippet core/src/concurrent/background_task_storage_test.cpp Bts field ordering
112///
113/// Components and their clients can always be safely captured by reference:
114///
115/// @see @ref scripts/docs/en/userver/component_system.md
116///
117/// So for a BackgroundTaskStorage stored in a component, its tasks can only
118/// safely use the fields declared before the BTS field, as well as everything
119/// from the components, on which the current component depends.
120class BackgroundTaskStorage final {
121public:
122 /// Creates a BTS that launches tasks in the engine::TaskProcessor used at the
123 /// BTS creation.
125
126 /// Creates a BTS that launches tasks in the specified engine::TaskProcessor.
127 explicit BackgroundTaskStorage(engine::TaskProcessor& task_processor);
128
129 BackgroundTaskStorage(const BackgroundTaskStorage&) = delete;
130 BackgroundTaskStorage& operator=(const BackgroundTaskStorage&) = delete;
131
132 /// @brief Explicitly cancel and wait for the tasks.
133 /// New tasks must not be launched after this call returns.
134 ///
135 /// More precisely, new tasks must not be launched once this call is completed, but can be launched in the process
136 /// of waiting for the remaining tasks. This means that one detached task is allowed to spawn another detached
137 /// task into the same BTS, which will immediately be cancelled and for which this call will wait as well.
138 ///
139 /// Can only be called from a coroutine.
140 void CancelAndWait() noexcept;
141
142 /// @brief Wait for the remaining tasks to complete without cancelling them.
143 /// New tasks must not be launched after this call returns.
144 ///
145 /// More precisely, new tasks must not be launched once this call is completed, but can be launched in the process
146 /// of waiting for the remaining tasks. This means that one detached task is allowed to spawn another detached
147 /// task into the same BTS, for which this call will wait as well.
148 ///
149 /// @note Running this method burns some CPU time (a few microseconds). Awaiting the tasks once on service
150 /// shutdown, or even periodically, is okay, but don't use `BackgroundTaskStorage` as a substitute
151 /// for `std::vector<Task>` in handlers, because it is less efficient.
152 ///
153 /// Can only be called from a coroutine.
154 void WaitAndDisposeSlow() noexcept;
155
156 /// @brief Launch a task that will be cancelled and waited for in the BTS
157 /// destructor.
158 ///
159 /// The task is started as non-Critical, it may be cancelled due to
160 /// `TaskProcessor` overload. Only engine::TaskInheritedVariable instances with
161 /// engine::TaskInheritedVariablePriority::kBackground are inherited from the caller.
162 /// See utils::AsyncBackground for details.
163 ///
164 /// If this function throws (due to OOM), the launched task is cancelled and waited for before
165 /// the exception is rethrown. The task may already have started; its side effects
166 /// are not rolled back. After the exception, the task does not keep running.
167 ///
168 /// Can be called from a coroutine or a non-coroutine thread.
169 template <typename... Args>
170 void AsyncDetach(std::string name, Args&&... args) {
171 core_.Detach(utils::AsyncBackground(std::move(name), task_processor_, std::forward<Args>(args)...));
172 }
173
174 /// @brief Launch a task that will be cancelled and waited for in the BTS
175 /// destructor.
176 ///
177 /// Execution of function is guaranteed to start regardless
178 /// of engine::TaskProcessor load limits.
179 /// Only engine::TaskInheritedVariable instances with
180 /// engine::TaskInheritedVariablePriority::kBackground are inherited from the caller.
181 /// See utils::CriticalAsyncBackground for details.
182 ///
183 /// If this function throws (due to OOM), the launched task is cancelled and waited for before
184 /// the exception is rethrown. The task may already have started; its side effects
185 /// are not rolled back. After the exception, the task does not keep running.
186 ///
187 /// Can be called from a coroutine or a non-coroutine thread.
188 template <typename... Args>
189 void CriticalAsyncDetach(std::string name, Args&&... args) {
190 core_.Detach(utils::CriticalAsyncBackground(std::move(name), task_processor_, std::forward<Args>(args)...));
191 }
192
193 /// @returns Approximate number of currently active tasks.
194 ///
195 /// Can be called from a coroutine or a non-coroutine thread.
196 /// Cannot be called after @ref CancelAndWait or @ref WaitAndDisposeSlow has been called.
197 std::int64_t ActiveTasksApprox() const noexcept;
198
199private:
200 BackgroundTaskStorageCore core_;
201 engine::TaskProcessor& task_processor_;
202};
203
204} // namespace concurrent
205
206USERVER_NAMESPACE_END