My Project 3.7.1
C++ Distributed Hash Table
Loading...
Searching...
No Matches
node_cache.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "node.h"
6
7#include <list>
8#include <memory>
9
10namespace dht {
11
12struct NodeCache
13{
14 size_t size(sa_family_t family) const { return cache(family).count(); }
15 size_t size() const { return size(AF_INET) + size(AF_INET6); }
16
17 Sp<Node> getNode(const InfoHash& id, sa_family_t family);
18 Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client = false);
19 std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) const;
20
26 void clearBadNodes(sa_family_t family = 0);
27
28 NodeCache(std::mt19937_64& r)
29 : rd(r) {};
30 ~NodeCache();
31
32private:
33 class NodeMap : private std::map<InfoHash, std::weak_ptr<Node>>
34 {
35 public:
36 Sp<Node> getNode(const InfoHash& id);
37 Sp<Node> getNode(
38 const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd);
39 std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, size_t count) const;
40 void clearBadNodes();
41 void setExpired();
42 void cleanup();
43 size_t count() const { return size(); }
44
45 private:
46 size_t cleanup_counter {0};
47 };
48
49 const NodeMap& cache(sa_family_t af) const { return af == AF_INET ? cache_4 : cache_6; }
50 NodeMap& cache(sa_family_t af) { return af == AF_INET ? cache_4 : cache_6; }
51 NodeMap cache_4;
52 NodeMap cache_6;
53 std::mt19937_64& rd;
54};
55
56} // namespace dht
void clearBadNodes(sa_family_t family=0)