blob: 037579b714bed87619077846e11a4dbfbde4b313 (
plain) (
blame)
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
|
#include "database.h"
#include <include/uuid.h>
#include <stdexcept>
std::string database::create(std::mt19937& rng) {
std::lock_guard state_guard(mutex_);
std::string token = uuids::to_string(uuids::uuid_random_generator{rng}());
requests_[token] = request{};
return token;
}
void database::subscribe(const std::string& token,
subscribe_callback_type callback) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
request& req = requests_[token];
size_t nextId = req.subscribers.size();
req.subscribers.push_back(callback);
}
void database::post(const std::string& token, const std::string& msg) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
request& req = requests_.at(token);
for (std::optional<subscribe_callback_type>& callback : req.subscribers) {
if (callback) {
try {
(*callback)(msg);
} catch (const std::exception& ex) {
callback = std::nullopt;
}
}
}
}
void database::setResult(const std::string& token, const std::string& result) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
request& req = requests_[token];
req.result = result;
}
const std::string& database::getResult(const std::string& token) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
const request& req = requests_.at(token);
return req.result;
}
void database::mark_done(const std::string& token) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
request& req = requests_[token];
req.done = true;
}
bool database::is_done(const std::string& token) {
std::lock_guard state_guard(mutex_);
if (!requests_.count(token)) {
throw std::invalid_argument("Could not find request.");
}
const request& req = requests_.at(token);
return req.done;
}
|