xref: /aosp_15_r20/external/cronet/net/disk_cache/memory/mem_backend_impl.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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 // See net/disk_cache/disk_cache.h for the public interface of the cache.
6 
7 #ifndef NET_DISK_CACHE_MEMORY_MEM_BACKEND_IMPL_H_
8 #define NET_DISK_CACHE_MEMORY_MEM_BACKEND_IMPL_H_
9 
10 #include <stdint.h>
11 
12 #include <string>
13 #include <unordered_map>
14 
15 #include "base/compiler_specific.h"
16 #include "base/containers/linked_list.h"
17 #include "base/functional/callback_forward.h"
18 #include "base/memory/memory_pressure_listener.h"
19 #include "base/memory/raw_ptr.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/strings/string_split.h"
22 #include "base/time/time.h"
23 #include "net/base/net_export.h"
24 #include "net/disk_cache/disk_cache.h"
25 #include "net/disk_cache/memory/mem_entry_impl.h"
26 
27 namespace base {
28 class Clock;
29 }
30 
31 namespace net {
32 class NetLog;
33 }  // namespace net
34 
35 namespace disk_cache {
36 
37 // This class implements the Backend interface. An object of this class handles
38 // the operations of the cache without writing to disk.
39 class NET_EXPORT_PRIVATE MemBackendImpl final : public Backend {
40  public:
41   explicit MemBackendImpl(net::NetLog* net_log);
42 
43   MemBackendImpl(const MemBackendImpl&) = delete;
44   MemBackendImpl& operator=(const MemBackendImpl&) = delete;
45 
46   ~MemBackendImpl() override;
47 
48   // Returns an instance of a Backend implemented only in memory. The returned
49   // object should be deleted when not needed anymore. max_bytes is the maximum
50   // size the cache can grow to. If zero is passed in as max_bytes, the cache
51   // will determine the value to use based on the available memory. The returned
52   // pointer can be NULL if a fatal error is found.
53   static std::unique_ptr<MemBackendImpl> CreateBackend(int64_t max_bytes,
54                                                        net::NetLog* net_log);
55 
56   // Performs general initialization for this current instance of the cache.
57   bool Init();
58 
59   // Sets the maximum size for the total amount of data stored by this instance.
60   bool SetMaxSize(int64_t max_bytes);
61 
62   // Returns the maximum size for a file to reside on the cache.
63   int64_t MaxFileSize() const override;
64 
65   // These next methods (before the implementation of the Backend interface) are
66   // called by MemEntryImpl to update the state of the backend during the entry
67   // lifecycle.
68 
69   // Signals that new entry has been created, and should be placed in
70   // |lru_list_| so that it is eligable for eviction.
71   void OnEntryInserted(MemEntryImpl* entry);
72 
73   // Signals that an entry has been updated, and thus should be moved to the end
74   // of |lru_list_|.
75   void OnEntryUpdated(MemEntryImpl* entry);
76 
77   // Signals that an entry has been doomed, and so it should be removed from the
78   // list of active entries as appropriate, as well as removed from the
79   // |lru_list_|.
80   void OnEntryDoomed(MemEntryImpl* entry);
81 
82   // Adjust the current size of this backend by |delta|. This is used to
83   // determine if eviction is necessary and when eviction is finished.
84   void ModifyStorageSize(int32_t delta);
85 
86   // Returns true if the cache's size is greater than the maximum allowed
87   // size.
88   bool HasExceededStorageSize() const;
89 
90   // Sets a callback to be posted after we are destroyed. Should be called at
91   // most once.
92   void SetPostCleanupCallback(base::OnceClosure cb);
93 
94   static base::Time Now(const base::WeakPtr<MemBackendImpl>& self);
95   void SetClockForTesting(base::Clock* clock);  // doesn't take ownership.
96 
97   // Backend interface.
98   int32_t GetEntryCount() const override;
99   EntryResult OpenOrCreateEntry(const std::string& key,
100                                 net::RequestPriority request_priority,
101                                 EntryResultCallback callback) override;
102   EntryResult OpenEntry(const std::string& key,
103                         net::RequestPriority request_priority,
104                         EntryResultCallback callback) override;
105   EntryResult CreateEntry(const std::string& key,
106                           net::RequestPriority request_priority,
107                           EntryResultCallback callback) override;
108   net::Error DoomEntry(const std::string& key,
109                        net::RequestPriority priority,
110                        CompletionOnceCallback callback) override;
111   net::Error DoomAllEntries(CompletionOnceCallback callback) override;
112   net::Error DoomEntriesBetween(base::Time initial_time,
113                                 base::Time end_time,
114                                 CompletionOnceCallback callback) override;
115   net::Error DoomEntriesSince(base::Time initial_time,
116                               CompletionOnceCallback callback) override;
117   int64_t CalculateSizeOfAllEntries(
118       Int64CompletionOnceCallback callback) override;
119   int64_t CalculateSizeOfEntriesBetween(
120       base::Time initial_time,
121       base::Time end_time,
122       Int64CompletionOnceCallback callback) override;
123   std::unique_ptr<Iterator> CreateIterator() override;
GetStats(base::StringPairs * stats)124   void GetStats(base::StringPairs* stats) override {}
125   void OnExternalCacheHit(const std::string& key) override;
126 
127  private:
128   class MemIterator;
129   friend class MemIterator;
130 
131   using EntryMap = std::unordered_map<std::string, MemEntryImpl*>;
132 
133   // Deletes entries from the cache until the current size is below the limit.
134   void EvictIfNeeded();
135 
136   // Deletes entries until the current size is below |goal|.
137   void EvictTill(int target_size);
138 
139   // Called when we get low on memory.
140   void OnMemoryPressure(
141       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
142 
143   raw_ptr<base::Clock> custom_clock_for_testing_ = nullptr;  // usually nullptr.
144 
145   EntryMap entries_;
146 
147   // Stored in increasing order of last use time, from least recently used to
148   // most recently used.
149   base::LinkedList<MemEntryImpl> lru_list_;
150 
151   int32_t max_size_ = 0;  // Maximum data size for this instance.
152   int32_t current_size_ = 0;
153 
154   raw_ptr<net::NetLog> net_log_;
155   base::OnceClosure post_cleanup_callback_;
156 
157   base::MemoryPressureListener memory_pressure_listener_;
158 
159   base::WeakPtrFactory<MemBackendImpl> weak_factory_{this};
160 };
161 
162 }  // namespace disk_cache
163 
164 #endif  // NET_DISK_CACHE_MEMORY_MEM_BACKEND_IMPL_H_
165