-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncEngine.cpp
More file actions
260 lines (226 loc) · 8.66 KB
/
AsyncEngine.cpp
File metadata and controls
260 lines (226 loc) · 8.66 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
/*
PrivMX Endpoint.
Copyright © 2024 Simplito sp. z o.o.
This file is part of the PrivMX Platform (https://privmx.dev).
This software is Licensed under the PrivMX Free License.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "AsyncEngine.hpp"
static constexpr size_t WORKER_COUNT_MIN = 2;
static constexpr size_t WORKER_COUNT_DEFAULT = 4;
#include <Poco/JSON/Object.h>
#include <Pson/pson.h>
#include <emscripten/eventloop.h>
#include <Pson/BinaryString.hpp>
#include <stdexcept>
#include "Mapper.hpp"
#include "WorkerPool.hpp"
using namespace privmx::webendpoint;
extern "C" {
EMSCRIPTEN_KEEPALIVE
void AsyncEngine_onSuccess(int id, emscripten::EM_VAL result_handle) {
auto instance = AsyncEngine::getInstance();
if (instance) instance->handleJsResult(id, emscripten::val::take_ownership(result_handle));
}
EMSCRIPTEN_KEEPALIVE
void AsyncEngine_onError(int id, emscripten::EM_VAL error_handle) {
auto instance = AsyncEngine::getInstance();
if (instance) instance->handleJsError(id, emscripten::val::take_ownership(error_handle));
}
}
// clang-format off
namespace privmx {
namespace webendpoint {
EM_JS(void, pushToJsCallbackQueue,(emscripten::EM_VAL callbackHandle, emscripten::EM_VAL valueHandle), {
const callback = Emval.toValue(callbackHandle);
const value = Emval.toValue(valueHandle);
setTimeout(()=>callback(value), 0);
});
// Reads window.__privmxWorkerCount (set by TypeScript before module init).
// Returns 0 when the global is absent or not a positive integer.
EM_JS(int, readWorkerCountFromJs, (), {
const v = (typeof window !== 'undefined') && window.__privmxWorkerCount;
return (typeof v === 'number' && v > 0) ? (v | 0) : 0;
});
}
}
// clang-format on
AsyncEngine* AsyncEngine::_instance = nullptr;
std::mutex AsyncEngine::_instanceMutex;
pthread_t AsyncEngine::_mainThread = pthread_self();
AsyncEngine* AsyncEngine::getInstance() {
if (_instance == nullptr) {
_instance = new AsyncEngine();
}
return _instance;
}
AsyncEngine::AsyncEngine() {
int requested = readWorkerCountFromJs();
size_t numWorkers =
(static_cast<size_t>(requested) >= WORKER_COUNT_MIN) ? static_cast<size_t>(requested) : WORKER_COUNT_DEFAULT;
_pool = std::make_unique<WorkerPool>(numWorkers);
_taskManagerThread = std::thread([=] { emscripten_runtime_keepalive_push(); });
}
AsyncEngine::~AsyncEngine() {}
void AsyncEngine::_postWorkerTaskVar(int taskId, const std::function<Poco::Dynamic::Var(void)>& task) {
_proxingQueue.proxyAsync(_taskManagerThread.native_handle(),
[&, taskId, task] { executeWorkerTask(taskId, task); });
}
void AsyncEngine::_postWorkerTaskVoid(int taskId, const std::function<void(void)>& task) {
_proxingQueue.proxyAsync(_taskManagerThread.native_handle(),
[&, taskId, task] { executeWorkerTask(taskId, task); });
}
void AsyncEngine::setResultsCallback(emscripten::val callback) {
_callback = callback;
}
void AsyncEngine::executeWorkerTask(int taskId, const std::function<Poco::Dynamic::Var(void)>& task) {
auto errorHandler = _errorHandler;
_pool->enqueue([=] {
Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
result->set("taskId", taskId);
try {
result->set("result", task());
result->set("status", true);
} catch (...) {
result->set("status", false);
Poco::JSON::Object::Ptr errorObj = new Poco::JSON::Object();
bool handled = false;
if (errorHandler) {
try {
errorHandler(std::current_exception(), errorObj);
handled = true;
} catch (...) {
errorObj->set("error", "Error handler crashed");
}
}
if (!handled || errorObj->size() == 0) {
try {
throw;
} catch (const std::exception& e) {
errorObj->set("error", e.what());
} catch (...) {
errorObj->set("error", "Unknown Error");
}
}
result->set("error", errorObj);
}
postResultToMain(result);
});
}
void AsyncEngine::executeWorkerTask(int taskId, const std::function<void(void)>& task) {
auto errorHandler = _errorHandler;
_pool->enqueue([=] {
Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
result->set("taskId", taskId);
try {
result->set("result", "");
result->set("status", true);
task();
} catch (...) {
result->set("status", false);
Poco::JSON::Object::Ptr errorObj = new Poco::JSON::Object();
bool handled = false;
if (errorHandler) {
try {
errorHandler(std::current_exception(), errorObj);
handled = true;
} catch (...) {
errorObj->set("error", "Error handler crashed");
}
}
if (!handled || errorObj->size() == 0) {
try {
throw;
} catch (const std::exception& e) {
errorObj->set("error", e.what());
} catch (...) {
errorObj->set("error", "Unknown Error");
}
}
result->set("error", errorObj);
}
postResultToMain(result);
});
}
void AsyncEngine::postResultToMain(const Poco::Dynamic::Var& result) {
dispatchToMainThread([&, result] {
if (!_callback.isUndefined()) {
Poco::Dynamic::Var localResult = result;
emscripten::val valResult = Mapper::map((pson_value*)&localResult);
pushToJsCallbackQueue(_callback.as_handle(), valResult.as_handle());
}
});
}
void AsyncEngine::dispatchToMainThread(const std::function<void(void)>& task) {
if (pthread_self() != _mainThread) {
_proxingQueue.proxySync(_mainThread, [&] { task(); });
} else {
task();
}
}
void AsyncEngine::dispatchToThread(const std::function<void(void)>& task, pthread_t target) {
_proxingQueue.proxySync(target, [&] { task(); });
}
std::future<Poco::Dynamic::Var> AsyncEngine::callJsAsync(std::function<void(int callId)> starterFunc,
ThreadTarget target) {
auto prms = std::make_shared<std::promise<Poco::Dynamic::Var>>();
std::future<Poco::Dynamic::Var> ftr = prms->get_future();
int id = _nextCallId++;
{
std::lock_guard<std::mutex> lock(_promiseMutex);
_promises[id] = prms;
}
if (target == ThreadTarget::Main) {
_proxingQueue.proxyAsync(_mainThread, [starterFunc, id] { starterFunc(id); });
} else {
_proxingQueue.proxyAsync(_taskManagerThread.native_handle(), [starterFunc, id] { starterFunc(id); });
}
return ftr;
}
void AsyncEngine::handleJsResult(int callId, emscripten::val result) {
std::shared_ptr<std::promise<Poco::Dynamic::Var>> prms = nullptr;
{
std::lock_guard<std::mutex> lock(_promiseMutex);
auto it = _promises.find(callId);
if (it != _promises.end()) {
prms = it->second;
_promises.erase(it);
}
}
if (prms) {
try {
Poco::Dynamic::Var converted = Mapper::map(result);
prms->set_value(converted);
} catch (const std::exception& e) {
prms->set_exception(std::make_exception_ptr(e));
} catch (...) {
prms->set_exception(std::make_exception_ptr(std::runtime_error("Unknown mapping error")));
}
} else {
std::cerr << "[AsyncEngine] Warning: Unknown CallID " << callId << " in handleJsResult" << std::endl;
}
}
void AsyncEngine::handleJsError(int callId, emscripten::val error) {
std::shared_ptr<std::promise<Poco::Dynamic::Var>> prms = nullptr;
{
std::lock_guard<std::mutex> lock(_promiseMutex);
auto it = _promises.find(callId);
if (it != _promises.end()) {
prms = it->second;
_promises.erase(it);
}
}
if (prms) {
std::string msg = "Unknown JS Error";
try {
if (error.isString())
msg = error.as<std::string>();
else
msg = error.call<std::string>("toString");
} catch (...) {}
prms->set_exception(std::make_exception_ptr(std::runtime_error(msg)));
} else {
std::cerr << "[AsyncEngine] Warning: Unknown CallID " << callId << " in handleJsError" << std::endl;
}
}