File size: 2,114 Bytes
a02f9a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#pragma once

#include <string>
#include <map>
#include <fstream>
#include <cstdio>
#include "json.hpp"
#include "Constants.h"

// Header-only instance registry.
// Stores {channelName: port} in a JSON file at /tmp/pluginbridge-registry.json
// Multiple PluginBridge instances write to this file (one per track).
// Atomic writes via write-to-temp + rename (POSIX rename is atomic on same filesystem).

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)
{
    // Read existing
    auto registry = readAll();

    // Update entry
    registry[channelName] = port;

    // Write to temp file, then atomic rename
    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())
    {
        // Remove the file entirely
        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);
    }
}

} // namespace InstanceRegistry