-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathpool_handler_ready_make.hpp
77 lines (73 loc) · 2.23 KB
/
pool_handler_ready_make.hpp
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
/**
* Copyright Quadrivium LLC
* All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "application/app_state_manager.hpp"
#include "log/logger.hpp"
#include "utils/pool_handler_ready.hpp"
#include "utils/thread_pool.hpp"
namespace kagome {
/**
* Make `PoolHandlerReady` for `Component` with `tryStart`.
* Calls `tryStart` on `ThreadPool`.
* Calls `setReady` if `tryStart` was successful.
* Calls `shutdown` if `tryStart` returned error.
*/
template <typename Component>
auto poolHandlerReadyMake(Component *component,
std::shared_ptr<application::AppStateManager> app,
const ThreadPool &thread_pool,
const log::Logger &log) {
auto thread = std::make_shared<PoolHandlerReady>(thread_pool.io_context());
app->atLaunch([component,
weak_app{std::weak_ptr{app}},
log,
weak_thread{std::weak_ptr{thread}}] {
auto thread = weak_thread.lock();
if (not thread) {
return;
}
thread->postAlways([weak_component{component->weak_from_this()},
weak_app,
log,
weak_thread] {
auto thread = weak_thread.lock();
if (not thread) {
return;
}
auto component = weak_component.lock();
if (not component) {
return;
}
if (component->tryStart()) {
thread->setReady();
return;
}
SL_CRITICAL(log, "start failed");
if (auto app = weak_app.lock()) {
app->shutdown();
}
});
});
app->takeControl(*thread);
return thread;
}
/**
* Make `PoolHandlerReady`.
*/
inline auto poolHandlerReadyMake(application::AppStateManager &app,
const ThreadPool &thread_pool) {
auto thread = std::make_shared<PoolHandlerReady>(thread_pool.io_context());
app.atLaunch([weak_thread{std::weak_ptr{thread}}] {
auto thread = weak_thread.lock();
if (not thread) {
return;
}
thread->setReady();
});
app.takeControl(*thread);
return thread;
}
} // namespace kagome