Files
spark/src/lib/persistence/IDGenerator.cpp
T

73 lines
2.0 KiB
C++

#include "IDGenerator.h"
#include "lib/logging/logging.h"
#include "lib/persistence/SqliteStore.h"
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
namespace bts::persistence {
IDGenerator *IDGenerator::_instance = nullptr;
std::mutex IDGenerator::_instance_mx;
struct IDGenerator::PImpl {
std::unique_ptr<persistence::IStore> kv_store;
PImpl() : kv_store(std::make_unique<persistence::SqliteStore>("key_ids")) {}
};
IDGenerator::IDGenerator() : me(new PImpl()) {}
IDGenerator &IDGenerator::insance() {
std::lock_guard<std::mutex> myLock(_instance_mx);
if (!_instance) {
_instance = new IDGenerator();
}
return *_instance;
}
inline uint64_t str_to_id(const std::string id_str) {
return std::stoull(id_str);
}
uint64_t get_next_id(
const std::map<std::string, std::map<std::string, std::string>> &all) {
uint64_t rv = 0;
for (const auto &kv1 : all) {
for (const auto &kv2 : kv1.second) {
uint64_t v = str_to_id(kv2.second);
if (v > rv) {
rv = v;
}
}
}
return rv + 1;
}
std::optional<uint64_t> IDGenerator::get_id(
const std::string &ns, const std::string &key, bool add_if_new) {
std::lock_guard<std::mutex> myLock(_instance_mx);
auto [exists, val] = me->kv_store->retrieve_one(ns, key);
if (exists) {
uint64_t rv = str_to_id(val);
LOG(Gen, Info, "IDGenerator::get_id ns: {} key: id: {}", ns, key, rv);
return std::optional<uint64_t>(rv);
} else {
if (add_if_new) {
auto all = me->kv_store->retrieve_all();
uint64_t new_id = get_next_id(all);
me->kv_store->insert(ns, key, std::to_string(new_id));
LOG(Gen, Info, "IDGenerator::get_id ns: {} key: id: {}", ns, key,
new_id);
return std::optional<uint64_t>(new_id);
}
LOG(Gen, Info, "IDGenerator::get_id ns: {} key: id: {}", ns, key,
std::string("nullopt"));
return std::nullopt;
}
}
IDGenerator::~IDGenerator() {}
} // namespace bts::persistence