#include "IDGenerator.h" #include "lib/logging/logging.h" #include "lib/persistence/SqliteStore.h" #include #include #include #include namespace bts::persistence { IDGenerator *IDGenerator::_instance = nullptr; std::mutex IDGenerator::_instance_mx; struct IDGenerator::PImpl { std::unique_ptr kv_store; PImpl() : kv_store(std::make_unique("key_ids")) {} }; IDGenerator::IDGenerator() : me(new PImpl()) {} IDGenerator &IDGenerator::insance() { std::lock_guard 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> &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 IDGenerator::get_id( const std::string &ns, const std::string &key, bool add_if_new) { std::lock_guard 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(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(new_id); } LOG(Gen, Info, "IDGenerator::get_id ns: {} key: id: {}", ns, key, std::string("nullopt")); return std::nullopt; } } IDGenerator::~IDGenerator() {} } // namespace bts::persistence