C++ Distributed Hash Table
node_cache.h
1 /*
2  * Copyright (C) 2014-2022 Savoir-faire Linux Inc.
3  * Author(s) : Adrien BĂ©raud <adrien.beraud@savoirfairelinux.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 #pragma once
20 
21 #include "node.h"
22 
23 #include <list>
24 #include <memory>
25 
26 namespace dht {
27 
28 struct NodeCache {
29  size_t size(sa_family_t family) const {
30  return cache(family).count();
31  }
32  size_t size() const {
33  return size(AF_INET) + size(AF_INET6);
34  }
35 
36  Sp<Node> getNode(const InfoHash& id, sa_family_t family);
37  Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client=false);
38  std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) const;
39 
45  void clearBadNodes(sa_family_t family = 0);
46 
47  NodeCache(std::mt19937_64& r) : rd(r) {};
48  ~NodeCache();
49 
50 private:
51  class NodeMap : private std::map<InfoHash, std::weak_ptr<Node>> {
52  public:
53  Sp<Node> getNode(const InfoHash& id);
54  Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd);
55  std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, size_t count) const;
56  void clearBadNodes();
57  void setExpired();
58  void cleanup();
59  size_t count() const { return size(); }
60  private:
61  size_t cleanup_counter {0};
62  };
63 
64  const NodeMap& cache(sa_family_t af) const { return af == AF_INET ? cache_4 : cache_6; }
65  NodeMap& cache(sa_family_t af) { return af == AF_INET ? cache_4 : cache_6; }
66  NodeMap cache_4;
67  NodeMap cache_6;
68  std::mt19937_64& rd;
69 };
70 
71 }
void clearBadNodes(sa_family_t family=0)
Definition: callbacks.h:35