| #pragma once |
|
|
| #include <string> |
| #include <map> |
| #include <fstream> |
| #include <cstdio> |
| #include "json.hpp" |
| #include "Constants.h" |
|
|
| |
| |
| |
| |
|
|
| namespace InstanceRegistry { |
|
|
| inline std::map<std::string, int> readAll() |
| { |
| std::map<std::string, int> result; |
| std::ifstream file(PluginBridgeConstants::kRegistryPath); |
| if (!file.is_open()) return result; |
|
|
| try |
| { |
| nlohmann::json j; |
| file >> j; |
| for (auto& [key, val] : j.items()) |
| { |
| if (val.is_number_integer()) |
| result[key] = val.get<int>(); |
| } |
| } |
| catch (...) {} |
|
|
| return result; |
| } |
|
|
| inline void registerInstance(const std::string& channelName, int port) |
| { |
| |
| auto registry = readAll(); |
|
|
| |
| registry[channelName] = port; |
|
|
| |
| std::string tmpPath = std::string(PluginBridgeConstants::kRegistryPath) + ".tmp"; |
|
|
| nlohmann::json j(registry); |
| std::ofstream tmp(tmpPath); |
| if (tmp.is_open()) |
| { |
| tmp << j.dump(2); |
| tmp.close(); |
| std::rename(tmpPath.c_str(), PluginBridgeConstants::kRegistryPath); |
| } |
| } |
|
|
| inline void unregisterInstance(const std::string& channelName) |
| { |
| auto registry = readAll(); |
|
|
| auto it = registry.find(channelName); |
| if (it == registry.end()) return; |
|
|
| registry.erase(it); |
|
|
| std::string tmpPath = std::string(PluginBridgeConstants::kRegistryPath) + ".tmp"; |
|
|
| if (registry.empty()) |
| { |
| |
| std::remove(PluginBridgeConstants::kRegistryPath); |
| return; |
| } |
|
|
| nlohmann::json j(registry); |
| std::ofstream tmp(tmpPath); |
| if (tmp.is_open()) |
| { |
| tmp << j.dump(2); |
| tmp.close(); |
| std::rename(tmpPath.c_str(), PluginBridgeConstants::kRegistryPath); |
| } |
| } |
|
|
| } |
|
|