#include "database.h" #include #include 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& 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; }