aboutsummaryrefslogtreecommitdiff
path: root/include/sibs/BootstrapConnection.hpp
blob: 9e2dfff6bbfdaef5f27cd87c9e5269a8f8eb2cd9 (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#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) {}
    };
    
    // @peer is nullptr is data was sent by local user.
    // Return false if you want to stop listening on the key
    using BoostrapConnectionListenCallbackFunc = std::function<bool(const DirectConnectionPeer *peer, const void *data, const usize size)>;

    struct ListenHandle
    {
        PubsubKey key;
    };
    
    class BootstrapConnection
    {
        DISABLE_COPY(BootstrapConnection)
    public:
        // Throws BootstrapConnectionException on error
        BootstrapConnection(const Ipv4 &bootstrapAddress);
        
        // If we are already listening on the key @pubsubKey then the callback function is overwritten
        ListenHandle listen(const PubsubKey &pubsubKey, BoostrapConnectionListenCallbackFunc callbackFunc);
        // Returns false if data is larger than 800kb.
        // Note: @data is copied in this function.
        // Note: You can't put data on a pubsubkey that you are not listening on. Call @listen first.
        bool put(const PubsubKey &pubsubKey, const void *data, const usize size);
        bool cancelListen(const ListenHandle &listener);
        bool areWeListeningOnKey(const PubsubKey &pubsubKey);

        std::vector<std::shared_ptr<DirectConnectionPeer>> getPeers();
    private:
        void receiveDataFromServer(std::shared_ptr<DirectConnectionPeer> peer, MessageType messageType, const void *data, const usize size);
        void receiveDataFromPeer(std::shared_ptr<DirectConnectionPeer> peer, MessageType messageType, 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::recursive_mutex listenerCallbackFuncMutex;
        std::recursive_mutex subscribedPeersMutex;
    };
}