summaryrefslogtreecommitdiffhomepage
path: root/connectionregistry.h
blob: e41e4f297feff9671b4dcca499addbc84757ba15 (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
#pragma once

#include <algorithm>
#include <memory>
#include <unordered_map>
#include <unordered_set>

#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/websocket.hpp>

// map connection <-> user id

class ConnectionRegistry
{
public:
 using connection = std::shared_ptr<boost::beast::websocket::stream<boost::asio::ip::tcp::socket>>;

 ConnectionRegistry() = default;
 ~ConnectionRegistry() = default;

 void setId(connection c, const std::string& id);

 // used via RegistryGuard
 void addConnection(connection c);
 void delConnection(connection c);

 // iterate over all connections associated with a certain id
 std::unordered_set<connection>::iterator begin(const std::string& id);
 std::unordered_set<connection>::iterator end(const std::string& id);

 // iterate over all connections
 std::unordered_map<connection, std::string>::iterator begin();
 std::unordered_map<connection, std::string>::iterator end();
 
 void dump() const;

 size_t number_of_connections() const;

private:
 // map connection to id
 std::unordered_map<connection, std::string> m_connections;
 // map id to list of related connections, used for iteration over connections to notify about changes
 std::unordered_map<std::string, std::unordered_set<connection>> m_ids;

public:
 class RegistryGuard
 {
 public:
  RegistryGuard(ConnectionRegistry& registry, connection c);
  ~RegistryGuard();
 private:
  ConnectionRegistry& m_registry;
  connection m_connection;
 };

};