xref: /aosp_15_r20/external/cronet/net/base/address_map_cache_linux.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_BASE_ADDRESS_MAP_CACHE_LINUX_H_
6 #define NET_BASE_ADDRESS_MAP_CACHE_LINUX_H_
7 
8 #include <map>
9 #include <string>
10 #include <unordered_set>
11 
12 #include "base/synchronization/lock.h"
13 #include "base/thread_annotations.h"
14 #include "net/base/address_map_linux.h"
15 #include "net/base/net_export.h"
16 
17 namespace net {
18 
19 // This caches AddressMap and the set of online links (see AddressMapOwnerLinux)
20 // so AddressTrackerLinux doesn't need to always be running in every process.
21 // This class is thread-safe.
22 class NET_EXPORT AddressMapCacheLinux : public AddressMapOwnerLinux {
23  public:
24   AddressMapCacheLinux();
25 
26   AddressMapCacheLinux(const AddressMapCacheLinux&) = delete;
27   AddressMapCacheLinux& operator=(const AddressMapCacheLinux&) = delete;
28 
29   ~AddressMapCacheLinux() override;
30 
31   // AddressMapOwnerLinux implementation:
32   AddressMap GetAddressMap() const override;
33   std::unordered_set<int> GetOnlineLinks() const override;
34 
35   AddressMapCacheLinux* GetAddressMapCacheLinux() override;
36 
37   // Sets `cached_address_map_` and `cached_online_links_`. This should normally
38   // only be used to set the initial AddressMap and set of online links.
39   void SetCachedInfo(AddressMap address_map,
40                      std::unordered_set<int> online_links);
41 
42   // Takes the diffs and applies them (atomically) to `cached_address_map_` and
43   // `cached_online_links_`.
44   // Once this method returns, calls on other threads to GetAddressMap() and
45   // GetOnlineLinks() that happen-after this call should return the updated
46   // data.
47   void ApplyDiffs(const AddressMapDiff& addr_diff,
48                   const OnlineLinksDiff& links_diff);
49 
50  private:
51   mutable base::Lock lock_;
52   AddressMap cached_address_map_ GUARDED_BY(lock_);
53   std::unordered_set<int> cached_online_links_ GUARDED_BY(lock_);
54 };
55 
56 }  // namespace net
57 
58 #endif  // NET_BASE_ADDRESS_MAP_CACHE_LINUX_H_
59