1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  *     Copyright 2017 Couchbase, Inc.
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License");
6  *   you may not use this file except in compliance with the License.
7  *   You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS,
13  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *   See the License for the specific language governing permissions and
15  *   limitations under the License.
16  */
17 #pragma once
18 
19 #include "client_connection.h"
20 
21 #include <nlohmann/json_fwd.hpp>
22 #include <functional>
23 
24 class ConnectionMap {
25 public:
26     /**
27      * Initialize the connection map with connections matching the ports
28      * opened from Memcached
29      */
30     void initialize(const nlohmann::json& ports);
31 
32     /**
33      * Invalidate all of the connections
34      */
35     void invalidate();
36 
37     /**
38      * Get a connection object matching the given attributes
39      *
40      * @param ssl If ssl should be enabled or not
41      * @param family the network family (IPv4 / IPv6)
42      * @param port (optional) The specific port number to use..
43      * @return A connection object to use
44      * @throws std::runtime_error if the request can't be served
45      */
46     MemcachedConnection& getConnection(bool ssl,
47                                        sa_family_t family = AF_INET,
48                                        in_port_t port = 0);
49 
50     /// Get a connection mapped to the given tag
51     MemcachedConnection& getConnection(const std::string& tag,
52                                        sa_family_t family = AF_INET);
53 
54     /**
55      * Just get a connection to the server (protocol / ssl etc
56      * doesn't matter)
57      *
58      * @return A connection to the server
59      */
getConnection()60     MemcachedConnection& getConnection() {
61         return *connections.front().get();
62     }
63 
64     /**
65      * Do we have a connection matching the requested attributes
66      */
67     bool contains(bool ssl, sa_family_t family);
68 
69     /**
70      * Iterate over all of the connections
71      */
iterate(std::function<void(MemcachedConnection&)> fn)72     void iterate(std::function<void(MemcachedConnection&)> fn) {
73         for (auto& connection : connections) {
74             fn(*connection);
75         }
76     }
77 
78 private:
79     std::vector<std::unique_ptr<MemcachedConnection>> connections;
80 };
81