79 lines
1.8 KiB
C++
79 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include "kv_store.hpp"
|
|
#include <random>
|
|
#include <unordered_map>
|
|
#include <mutex>
|
|
|
|
class SessionStore {
|
|
public:
|
|
SessionStore() : rng_(std::random_device{}()) {}
|
|
|
|
std::string create() {
|
|
std::string id = generate_id();
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
sessions_[id] = {};
|
|
return id;
|
|
}
|
|
|
|
std::optional<std::string> get(const std::string& id, const std::string& key) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
auto it = sessions_.find(id);
|
|
if (it == sessions_.end()) return std::nullopt;
|
|
|
|
auto data_it = it->second.find(key);
|
|
return data_it != it->second.end() ? std::optional<std::string>{data_it->second} : std::nullopt;
|
|
}
|
|
|
|
void set(const std::string& id, const std::string& key, const std::string& value) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
sessions_[id][key] = value;
|
|
}
|
|
|
|
bool del(const std::string& id) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
return sessions_.erase(id) > 0;
|
|
}
|
|
|
|
size_t size() {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
return sessions_.size();
|
|
}
|
|
|
|
void set_file(const std::string& filename) {
|
|
store_.set_file(filename);
|
|
}
|
|
|
|
void load() {
|
|
store_.load();
|
|
}
|
|
|
|
void save() {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
for (const auto& [id, data] : sessions_) {
|
|
for (const auto& [key, value] : data) {
|
|
store_.set(id + ":" + key, value);
|
|
}
|
|
}
|
|
store_.save();
|
|
}
|
|
|
|
private:
|
|
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> sessions_;
|
|
mutable std::mutex mutex_;
|
|
KeyValueStore store_;
|
|
std::mt19937 rng_;
|
|
|
|
std::string generate_id() {
|
|
static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
std::string id;
|
|
id.reserve(16);
|
|
|
|
for (int i = 0; i < 16; ++i) {
|
|
id += chars[rng_() % (sizeof(chars) - 1)];
|
|
}
|
|
|
|
return id;
|
|
}
|
|
};
|