-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathPromise.hpp
413 lines (377 loc) · 11.9 KB
/
Promise.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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//
// Created by Marc Rousavy on 18.11.24.
//
#pragma once
#include "AssertPromiseState.hpp"
#include "NitroDefines.hpp"
#include "NitroTypeInfo.hpp"
#include "ThreadPool.hpp"
#include <exception>
#include <future>
#include <jsi/jsi.h>
#include <memory>
#include <mutex>
#include <variant>
namespace margelo::nitro {
using namespace facebook;
template <typename TResult>
class Promise final {
public:
using OnResolvedFunc = std::function<void(const TResult&)>;
using OnRejectedFunc = std::function<void(const std::exception_ptr&)>;
public:
// Promise cannot be copied.
Promise(const Promise&) = delete;
private:
Promise() {}
public:
~Promise() {
if (isPending()) [[unlikely]] {
auto message = std::string("Timeouted: Promise<") + TypeInfo::getFriendlyTypename<TResult>() + "> was destroyed!";
reject(std::make_exception_ptr(std::runtime_error(message)));
}
}
public:
/**
* Creates a new pending Promise that has to be resolved
* or rejected with `resolve(..)` or `reject(..)`.
*/
static std::shared_ptr<Promise> create() {
return std::shared_ptr<Promise>(new Promise());
}
/**
* Creates a Promise that runs the given function `run` on a separate Thread pool.
*/
static std::shared_ptr<Promise> async(std::function<TResult()>&& run) {
auto promise = create();
ThreadPool::shared().run([run = std::move(run), promise]() {
try {
// Run the code, then resolve.
TResult result = run();
promise->resolve(std::move(result));
} catch (...) {
// It threw an error.
promise->reject(std::current_exception());
}
});
return promise;
}
/**
* Creates a Promise and awaits the given future on a background Thread.
* Once the future resolves or rejects, the Promise resolves or rejects.
*/
static std::shared_ptr<Promise> awaitFuture(std::future<TResult>&& future) {
auto sharedFuture = std::make_shared<std::future<TResult>>(std::move(future));
return async([sharedFuture = std::move(sharedFuture)]() { return sharedFuture->get(); });
}
/**
* Creates an immediately resolved Promise.
*/
static std::shared_ptr<Promise> resolved(TResult&& result) {
auto promise = create();
promise->resolve(std::move(result));
return promise;
}
/**
* Creates an immediately rejected Promise.
*/
static std::shared_ptr<Promise> rejected(const std::exception_ptr& error) {
auto promise = create();
promise->reject(error);
return promise;
}
public:
/**
* Resolves this Promise with the given result, and calls any pending listeners.
*/
void resolve(TResult&& result) {
std::unique_lock lock(_mutex);
#ifdef NITRO_DEBUG
assertPromiseState(*this, PromiseTask::WANTS_TO_RESOLVE);
#endif
_state = std::move(result);
for (const auto& onResolved : _onResolvedListeners) {
onResolved(std::get<TResult>(_state));
}
}
void resolve(const TResult& result) {
std::unique_lock lock(_mutex);
#ifdef NITRO_DEBUG
assertPromiseState(*this, PromiseTask::WANTS_TO_RESOLVE);
#endif
_state = result;
for (const auto& onResolved : _onResolvedListeners) {
onResolved(std::get<TResult>(_state));
}
}
/**
* Rejects this Promise with the given error, and calls any pending listeners.
*/
void reject(const std::exception_ptr& exception) {
if (exception == nullptr) [[unlikely]] {
throw std::runtime_error("Cannot reject Promise with a null exception_ptr!");
}
std::unique_lock lock(_mutex);
#ifdef NITRO_DEBUG
assertPromiseState(*this, PromiseTask::WANTS_TO_REJECT);
#endif
_state = exception;
for (const auto& onRejected : _onRejectedListeners) {
onRejected(exception);
}
}
public:
/**
* Add a listener that will be called when the Promise gets resolved.
* If the Promise is already resolved, the listener will be immediately called.
*/
void addOnResolvedListener(OnResolvedFunc&& onResolved) {
std::unique_lock lock(_mutex);
if (std::holds_alternative<TResult>(_state)) {
// Promise is already resolved! Call the callback immediately
onResolved(std::get<TResult>(_state));
} else {
// Promise is not yet resolved, put the listener in our queue.
_onResolvedListeners.push_back(std::move(onResolved));
}
}
void addOnResolvedListener(const OnResolvedFunc& onResolved) {
std::unique_lock lock(_mutex);
if (std::holds_alternative<TResult>(_state)) {
// Promise is already resolved! Call the callback immediately
onResolved(std::get<TResult>(_state));
} else {
// Promise is not yet resolved, put the listener in our queue.
_onResolvedListeners.push_back(onResolved);
}
}
[[deprecated("Upgrade Nitro to use PromiseHolder<T> instead.")]]
void addOnResolvedListenerCopy(const std::function<void(TResult)>& onResolved) {
addOnResolvedListener([=](const TResult& value) { onResolved(value); });
}
/**
* Add a listener that will be called when the Promise gets rejected.
* If the Promise is already rejected, the listener will be immediately called.
*/
void addOnRejectedListener(OnRejectedFunc&& onRejected) {
std::unique_lock lock(_mutex);
if (std::holds_alternative<std::exception_ptr>(_state)) {
// Promise is already rejected! Call the callback immediately
onRejected(std::get<std::exception_ptr>(_state));
} else {
// Promise is not yet rejected, put the listener in our queue.
_onRejectedListeners.push_back(std::move(onRejected));
}
}
void addOnRejectedListener(const OnRejectedFunc& onRejected) {
std::unique_lock lock(_mutex);
if (std::holds_alternative<std::exception_ptr>(_state)) {
// Promise is already rejected! Call the callback immediately
onRejected(std::get<std::exception_ptr>(_state));
} else {
// Promise is not yet rejected, put the listener in our queue.
_onRejectedListeners.push_back(onRejected);
}
}
public:
/**
* Gets an awaitable `std::future<T>` for this `Promise<T>`.
*/
std::future<TResult> await() {
auto promise = std::make_shared<std::promise<TResult>>();
addOnResolvedListener([promise](const TResult& result) { promise->set_value(result); });
addOnRejectedListener([promise](const std::exception_ptr& error) { promise->set_exception(error); });
return promise->get_future();
}
public:
/**
* Get the result of the Promise if it has been resolved.
* If the Promise is not resolved, this will throw.
*/
inline const TResult& getResult() {
if (!isResolved()) {
throw std::runtime_error("Cannot get result when Promise is not yet resolved!");
}
return std::get<TResult>(_state);
}
/**
* Get the error of the Promise if it has been rejected.
* If the Promise is not rejected, this will throw.
*/
inline const std::exception_ptr& getError() {
if (!isRejected()) {
throw std::runtime_error("Cannot get error when Promise is not yet rejected!");
}
return std::get<std::exception_ptr>(_state);
}
public:
/**
* Gets whether this Promise has been successfully resolved with a result, or not.
*/
[[nodiscard]]
inline bool isResolved() const noexcept {
return std::holds_alternative<TResult>(_state);
}
/**
* Gets whether this Promise has been rejected with an error, or not.
*/
[[nodiscard]]
inline bool isRejected() const noexcept {
return std::holds_alternative<std::exception_ptr>(_state);
}
/**
* Gets whether this Promise has not yet been resolved nor rejected.
*/
[[nodiscard]]
inline bool isPending() const noexcept {
return std::holds_alternative<std::monostate>(_state);
}
private:
std::variant<std::monostate, TResult, std::exception_ptr> _state;
std::vector<OnResolvedFunc> _onResolvedListeners;
std::vector<OnRejectedFunc> _onRejectedListeners;
std::mutex _mutex;
};
// Specialization for void
template <>
class Promise<void> final {
public:
using OnResolvedFunc = std::function<void()>;
using OnRejectedFunc = std::function<void(const std::exception_ptr&)>;
public:
Promise(const Promise&) = delete;
private:
Promise() {}
public:
~Promise() {
if (isPending()) [[unlikely]] {
std::runtime_error error("Timeouted: Promise<void> was destroyed!");
reject(std::make_exception_ptr(std::move(error)));
}
}
public:
static std::shared_ptr<Promise> create() {
return std::shared_ptr<Promise>(new Promise());
}
static std::shared_ptr<Promise> async(std::function<void()>&& run) {
auto promise = create();
ThreadPool::shared().run([run = std::move(run), promise]() {
try {
// Run the code, then resolve.
run();
promise->resolve();
} catch (...) {
// It threw an error.
promise->reject(std::current_exception());
}
});
return promise;
}
static std::shared_ptr<Promise> awaitFuture(std::future<void>&& future) {
auto sharedFuture = std::make_shared<std::future<void>>(std::move(future));
return async([sharedFuture = std::move(sharedFuture)]() { sharedFuture->get(); });
}
static std::shared_ptr<Promise> resolved() {
auto promise = create();
promise->resolve();
return promise;
}
static std::shared_ptr<Promise> rejected(const std::exception_ptr& error) {
auto promise = create();
promise->reject(error);
return promise;
}
public:
void resolve() {
std::unique_lock lock(_mutex);
#ifdef NITRO_DEBUG
assertPromiseState(*this, PromiseTask::WANTS_TO_RESOLVE);
#endif
_isResolved = true;
for (const auto& onResolved : _onResolvedListeners) {
onResolved();
}
}
void reject(const std::exception_ptr& exception) {
if (exception == nullptr) [[unlikely]] {
throw std::runtime_error("Cannot reject Promise with a null exception_ptr!");
}
std::unique_lock lock(_mutex);
#ifdef NITRO_DEBUG
assertPromiseState(*this, PromiseTask::WANTS_TO_REJECT);
#endif
_error = exception;
for (const auto& onRejected : _onRejectedListeners) {
onRejected(exception);
}
}
public:
void addOnResolvedListener(OnResolvedFunc&& onResolved) {
std::unique_lock lock(_mutex);
if (_isResolved) {
onResolved();
} else {
_onResolvedListeners.push_back(std::move(onResolved));
}
}
void addOnResolvedListener(const OnResolvedFunc& onResolved) {
std::unique_lock lock(_mutex);
if (_isResolved) {
onResolved();
} else {
_onResolvedListeners.push_back(onResolved);
}
}
void addOnRejectedListener(OnRejectedFunc&& onRejected) {
std::unique_lock lock(_mutex);
if (_error) {
onRejected(_error);
} else {
// Promise is not yet rejected, put the listener in our queue.
_onRejectedListeners.push_back(std::move(onRejected));
}
}
void addOnRejectedListener(const OnRejectedFunc& onRejected) {
std::unique_lock lock(_mutex);
if (_error) {
onRejected(_error);
} else {
// Promise is not yet rejected, put the listener in our queue.
_onRejectedListeners.push_back(onRejected);
}
}
public:
std::future<void> await() {
auto promise = std::make_shared<std::promise<void>>();
addOnResolvedListener([promise]() { promise->set_value(); });
addOnRejectedListener([promise](const std::exception_ptr& error) { promise->set_exception(error); });
return promise->get_future();
}
public:
inline const std::exception_ptr& getError() {
if (!isRejected()) {
throw std::runtime_error("Cannot get error when Promise is not yet rejected!");
}
return _error;
}
public:
[[nodiscard]]
inline bool isResolved() const noexcept {
return _isResolved;
}
[[nodiscard]]
inline bool isRejected() const noexcept {
return _error != nullptr;
}
[[nodiscard]]
inline bool isPending() const noexcept {
return !isResolved() && !isRejected();
}
private:
std::mutex _mutex;
bool _isResolved = false;
std::exception_ptr _error;
std::vector<OnResolvedFunc> _onResolvedListeners;
std::vector<OnRejectedFunc> _onRejectedListeners;
};
} // namespace margelo::nitro