aboutsummaryrefslogtreecommitdiff
path: root/include/sibs/BootstrapConnection.hpp
blob: e77222df432b03534a14d82557625a87c73ebdb3 (plain)
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
#pragma once

#include "../utils.hpp"
#include "DirectConnection.hpp"
#include "PubsubKey.hpp"
#include <mutex>

namespace sibs
{
    class BootstrapConnectionException : public std::runtime_error
    {
    public:
        BootstrapConnectionException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    class PubsubKeyAlreadyListeningException : public std::runtime_error
    {
    public:
        PubsubKeyAlreadyListeningException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    using BoostrapConnectionListenCallbackFunc = std::function<void(const void *data, const usize size)>;
    
    class BootstrapConnection
    {
        DISABLE_COPY(BootstrapConnection)
    public:
        // Throws BootstrapConnectionException on error
        BootstrapConnection(const Ipv4 &bootstrapAddress);
        
        // Throws PubsubKeyAlreadyListeningException if we are already listening on the key @pubsubKey
        void listen(const PubsubKey &pubsubKey, BoostrapConnectionListenCallbackFunc callbackFunc);
        void put(const PubsubKey &pubsubKey, std::shared_ptr<std::vector<u8>> data);
    private:
        void receiveDataFromServer(std::shared_ptr<DirectConnectionPeer> peer, const void *data, const usize size);
        void receiveDataFromPeer(BoostrapConnectionListenCallbackFunc listenCallbackFunc, std::shared_ptr<DirectConnectionPeer> peer, const void *data, const usize size);
    private:
        DirectConnections connections;
        std::shared_ptr<DirectConnectionPeer> serverPeer;
        PubsubKeyMap<BoostrapConnectionListenCallbackFunc> listenCallbackFuncs;
        PubsubKeyMap<std::vector<std::shared_ptr<DirectConnectionPeer>>> subscribedPeers;
        std::mutex listenerCallbackFuncMutex;
        std::mutex subscribedPeersMutex;
    };
}