-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathTaskContext.h
More file actions
396 lines (348 loc) · 12 KB
/
TaskContext.h
File metadata and controls
396 lines (348 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include <utility>
#include <olp/core/client/ApiError.h>
#include <olp/core/client/CancellationContext.h>
#include <olp/core/client/CancellationToken.h>
#include <olp/core/client/Condition.h>
#include <olp/core/thread/TaskScheduler.h>
namespace olp {
namespace client {
/**
* @brief Encapsulates the execution of an asynchronous task and invocation of
* a callback in a guaranteed manner.
*
* When the result of the provided task is available, or an error occurs,
* the callback is invoked.
*/
class CORE_API TaskContext {
public:
/**
* @brief Creates the `TaskContext` instance with the provided task and
* callback.
*
* @param execute_func The task that should be executed.
* @param callback Is invoked once the result of `execute_func` is available
* or the task is cancelled.
* @param context The `CancellationContext` instance.
*
* @return The `TaskContext` instance that can be used to run or cancel
* the task.
*/
template <typename Exec, typename Callback>
static TaskContext Create(
Exec execute_func, Callback callback,
client::CancellationContext context = client::CancellationContext(),
std::shared_ptr<thread::TaskScheduler> task_scheduler = nullptr) {
TaskContext task;
task.SetExecutors(std::move(execute_func), std::move(callback),
std::move(context), std::move(task_scheduler));
return task;
}
/**
* @brief Checks for the cancellation, executes the task, and calls
* the callback with the result or error.
*/
void Execute() const { impl_->Execute(); }
/**
* @brief Cancels the operation and waits for the notification.
*
* @param timeout The time (in milliseconds) to wait for the task to finish.
*
* @return True if the notification is returned before the timeout; false
* otherwise.
*/
bool BlockingCancel(
std::chrono::milliseconds timeout = std::chrono::seconds(60)) const {
return impl_->BlockingCancel(timeout);
}
/**
* @brief Provides a token to cancel the task.
*
* @return The `CancellationToken` instance.
*/
client::CancellationToken CancelToken() const { return impl_->CancelToken(); }
/**
* @brief Checks whether the values of the `TaskContext` parameter are
* the same as the values of the `other` parameter.
*
* @param other The `TaskContext` instance.
*
* @return True if the values of the `TaskContext` and `other` parameters are
* equal; false otherwise.
*/
bool operator==(const TaskContext& other) const {
return impl_ == other.impl_;
}
protected:
/// A helper for unordered containers.
friend struct TaskContextHash;
TaskContext() = default;
template <typename Exec, typename Callback,
#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
typename ExecResult =
std::invoke_result_t<Exec, client::CancellationContext>
#else
typename ExecResult =
typename std::result_of<Exec(client::CancellationContext)>::type
#endif
>
/**
* @brief Sets the executors for the request.
*
* @param execute_func The task that should be executed.
* @param callback Is invoked once the result of `execute_func` is available
* or the task is cancelled.
* @param context The `CancellationContext` instance.
*/
void SetExecutors(Exec execute_func, Callback callback,
client::CancellationContext context,
std::shared_ptr<thread::TaskScheduler> task_scheduler) {
auto impl = std::make_shared<TaskContextImpl<ExecResult>>(
std::move(execute_func), std::move(callback), context);
if (task_scheduler) {
std::weak_ptr<TaskContextImpl<ExecResult>> weak_impl = impl;
auto cancellation_scheduler = task_scheduler;
context.ExecuteOrCancelled(
[weak_impl, cancellation_scheduler]() -> CancellationToken {
return CancellationToken([weak_impl, cancellation_scheduler]() {
auto impl = weak_impl.lock();
if (impl && cancellation_scheduler) {
cancellation_scheduler->ScheduleCancellationTask([weak_impl]() {
auto impl = weak_impl.lock();
if (impl) {
impl->PreExecuteCancel();
}
});
return;
}
});
},
[]() {});
}
impl_ = std::move(impl);
}
/**
* @brief An implementation helper interface used to declare the `Execute`,
* `BlockingCancel`, and `CancelToken` functions used by the `TaskContext`
* instance.
*/
class Impl {
public:
virtual ~Impl() = default;
/**
* @brief Checks for the cancellation, executes the task, and calls
* the callback with the result or error.
*/
virtual void Execute() = 0;
/**
* @brief Cancels the operation and waits for the notification.
*
* @param timeout The time (in milliseconds) to wait for the task to finish.
*
* @return True if the notification is returned before the timeout; false
* otherwise.
*/
virtual bool BlockingCancel(std::chrono::milliseconds timeout) = 0;
/**
* @brief Provides a token to cancel the task.
*
* @return The `CancellationToken` instance.
*/
virtual client::CancellationToken CancelToken() = 0;
};
/**
* @brief Implements the `Impl` interface.
*
* Erases the type of the `Result` object produced by the `ExecuteFunc`
* function and passes it to the `UserCallback` instance.
*
* @tparam T The result type.
*/
template <typename Response>
class TaskContextImpl : public Impl {
public:
/// The task that produces the `Response` instance.
using ExecuteFunc = std::function<Response(client::CancellationContext)>;
/// Consumes the `Response` instance.
using UserCallback = std::function<void(Response)>;
/**
* @brief Creates the `TaskContextImpl` instance.
*
* @param execute_func The task that should be executed.
* @param callback Is invoked once the result of `execute_func` is available
* or the task is cancelled.
* @param context The `CancellationContext` instance.
*/
TaskContextImpl(ExecuteFunc execute_func, UserCallback callback,
client::CancellationContext context)
: execute_func_(std::move(execute_func)),
callback_(std::move(callback)),
context_(std::move(context)),
state_{State::PENDING} {}
~TaskContextImpl() override{};
/**
* @brief Checks for the cancellation, executes the task, and calls
* the callback with the result or error.
*/
void Execute() override {
State expected_state = State::PENDING;
if (!state_.compare_exchange_strong(expected_state, State::IN_PROGRESS)) {
return;
}
// Moving the user callback and function guarantee that they are
// executed exactly once
ExecuteFunc function = nullptr;
UserCallback callback = nullptr;
{
std::lock_guard<std::mutex> lock(mutex_);
function = std::move(execute_func_);
callback = std::move(callback_);
}
Response user_response =
client::ApiError(client::ErrorCode::Cancelled, "Cancelled");
if (function && !context_.IsCancelled()) {
auto response = function(context_);
// Cancel could occur during the function execution. In that case,
// ignore the response.
if (!context_.IsCancelled() ||
(!response.IsSuccessful() &&
response.GetError().GetErrorCode() == ErrorCode::RequestTimeout)) {
user_response = std::move(response);
}
}
// Reset the context after the task is finished.
context_.ExecuteOrCancelled([]() { return CancellationToken(); });
if (callback) {
callback(std::move(user_response));
}
// Resources need to be released before the notification, else lambas
// would have captured resources like network or `TaskScheduler`.
function = nullptr;
callback = nullptr;
condition_.Notify();
state_.store(State::COMPLETED);
}
void PreExecuteCancel() {
State expected_state = State::PENDING;
if (!state_.compare_exchange_strong(expected_state, State::IN_PROGRESS)) {
return;
}
// Moving the user callback and function guarantee that they are
// executed exactly once
ExecuteFunc function = nullptr;
UserCallback callback = nullptr;
{
std::lock_guard<std::mutex> lock(mutex_);
function = std::move(execute_func_);
callback = std::move(callback_);
}
Response user_response =
client::ApiError(client::ErrorCode::Cancelled, "Cancelled");
if (callback) {
callback(std::move(user_response));
}
// Resources need to be released before the notification, else lambas
// would have captured resources like network or `TaskScheduler`.
function = nullptr;
callback = nullptr;
condition_.Notify();
state_.store(State::COMPLETED);
}
/**
* @brief Cancels the operation and waits for the notification.
*
* @param timeout The time (in milliseconds) to wait for the task to finish.
*
* @return True if the notification is returned before the timeout; false
* otherwise.
*/
bool BlockingCancel(std::chrono::milliseconds timeout) override {
if (state_.load() == State::COMPLETED) {
return true;
}
// Cancels the operation and waits for the notification.
if (!context_.IsCancelled()) {
context_.CancelOperation();
}
{
std::lock_guard<std::mutex> lock(mutex_);
execute_func_ = nullptr;
}
return condition_.Wait(timeout);
}
/**
* @brief Provides a token to cancel the task.
*
* @return The `CancellationToken` instance.
*/
client::CancellationToken CancelToken() override {
auto context = context_;
return client::CancellationToken(
[context]() mutable { context.CancelOperation(); });
}
/**
* @brief Indicates the state of the request.
*/
enum class State {
/// The request waits to be executed.
PENDING,
/// The request is being executed.
IN_PROGRESS,
/// The request execution finished.
COMPLETED
};
/// The mutex lock used to protect from the concurrent read and write
/// operations.
std::mutex mutex_;
/// The `ExecuteFunc` instance.
ExecuteFunc execute_func_;
/// The `UserCallback` instance.
UserCallback callback_;
/// The `CancellationContext` instance.
client::CancellationContext context_;
/// The `Condition` instance.
client::Condition condition_;
/// The `State` enum of the atomic type.
std::atomic<State> state_;
};
/// The `Impl` instance.
std::shared_ptr<Impl> impl_;
};
/**
* @brief A helper for unordered containers.
*/
struct CORE_API TaskContextHash {
/**
* @brief The hash function for the `TaskContext` instance.
*
* @param task_context The `TaskContext` instance.
*
* @return The hash for the `TaskContext` instance.
*/
size_t operator()(const TaskContext& task_context) const {
return std::hash<std::shared_ptr<TaskContext::Impl>>()(task_context.impl_);
} // namespace client
}; // namespace olp
} // namespace client
} // namespace olp