From 8375f92802d3aa7667bfc6f22f6d2a72361c9808 Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Mon, 4 Nov 2024 11:46:24 -0500 Subject: Websockets server! --- database.cpp | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 database.cpp (limited to 'database.cpp') diff --git a/database.cpp b/database.cpp new file mode 100644 index 0000000..037579b --- /dev/null +++ b/database.cpp @@ -0,0 +1,91 @@ +#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; +} -- cgit 1.4.1