network_service_memory_cache.h 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // Copyright 2022 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_H_
  5. #define SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_H_
  6. #include <inttypes.h>
  7. #include <memory>
  8. #include <string>
  9. #include "base/component_export.h"
  10. #include "base/containers/lru_cache.h"
  11. #include "base/containers/unique_ptr_adapters.h"
  12. #include "base/memory/memory_pressure_listener.h"
  13. #include "base/memory/raw_ptr.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/time/time.h"
  16. #include "mojo/public/cpp/bindings/pending_receiver.h"
  17. #include "mojo/public/cpp/bindings/pending_remote.h"
  18. #include "services/network/public/mojom/url_loader.mojom.h"
  19. #include "services/network/public/mojom/url_loader_completion_status.mojom.h"
  20. #include "services/network/public/mojom/url_response_head.mojom.h"
  21. #include "third_party/abseil-cpp/absl/types/optional.h"
  22. namespace net {
  23. class HttpVaryData;
  24. class NetLogWithSource;
  25. class NetworkIsolationKey;
  26. class URLRequest;
  27. struct TransportInfo;
  28. } // namespace net
  29. namespace network {
  30. class NetworkContext;
  31. class NetworkServiceMemoryCacheURLLoader;
  32. class NetworkServiceMemoryCacheWriter;
  33. struct CrossOriginEmbedderPolicy;
  34. struct ResourceRequest;
  35. // An in-memory HTTP cache. NetworkContext owns the in-memory cache.
  36. // TODO(https://crbug.com/1339708): Add more descriptions once the network
  37. // service starts serving response from the in-memory cache.
  38. class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkServiceMemoryCache {
  39. public:
  40. explicit NetworkServiceMemoryCache(NetworkContext* network_context);
  41. ~NetworkServiceMemoryCache();
  42. NetworkServiceMemoryCache(const NetworkServiceMemoryCache&) = delete;
  43. NetworkServiceMemoryCache& operator=(const NetworkServiceMemoryCache&) =
  44. delete;
  45. base::WeakPtr<NetworkServiceMemoryCache> GetWeakPtr();
  46. size_t total_bytes() const { return total_bytes_; }
  47. // Clears all cache entries.
  48. void Clear();
  49. // Creates a NetworkServiceMemoryCacheWriter when the response is 200 and it
  50. // can be cacheable.
  51. std::unique_ptr<NetworkServiceMemoryCacheWriter> MaybeCreateWriter(
  52. net::URLRequest* url_request,
  53. mojom::RequestDestination request_destination,
  54. const net::TransportInfo& transport_info,
  55. const mojom::URLResponseHeadPtr& response);
  56. // Stores an HTTP response into `this`. Called when a writer finished reading
  57. // response body.
  58. void StoreResponse(const std::string& cache_key,
  59. const URLLoaderCompletionStatus& status,
  60. mojom::RequestDestination request_destination,
  61. const net::HttpVaryData& vary_data,
  62. const net::TransportInfo& transport_info,
  63. mojom::URLResponseHeadPtr response_head,
  64. std::vector<unsigned char> data);
  65. // Returns a cache key if `this` has a fresh response for `resource_request`.
  66. // The returned cache key is valid only for the current call stack. It must be
  67. // used synchronously.
  68. absl::optional<std::string> CanServe(
  69. uint32_t load_options,
  70. const ResourceRequest& resource_request,
  71. const net::NetworkIsolationKey& network_isolation_key,
  72. const CrossOriginEmbedderPolicy& cross_origin_embedder_policy,
  73. const mojom::ClientSecurityState* client_security_state);
  74. // Creates and starts a custom URLLoader that serves a response from the
  75. // in-memory cache, instead of creating a network::URLLoader. Must be called
  76. // immediately after CanServe().
  77. void CreateLoaderAndStart(mojo::PendingReceiver<mojom::URLLoader> receiver,
  78. int32_t request_id,
  79. uint32_t options,
  80. const std::string& cache_key,
  81. const ResourceRequest& resource_request,
  82. const net::NetLogWithSource net_log,
  83. mojo::PendingRemote<mojom::URLLoaderClient> client);
  84. // Returns a suitable capacity for a data pipe that is used to serve a
  85. // response from `this`.
  86. uint32_t GetDataPipeCapacity(size_t content_length);
  87. // Called when a custom URLLoader is completed.
  88. void OnLoaderCompleted(NetworkServiceMemoryCacheURLLoader* loader);
  89. // Called when a redirect happens for a request.
  90. void OnRedirect(const net::URLRequest* url_request,
  91. mojom::RequestDestination request_destination);
  92. void SetCurrentTimeForTesting(base::Time current_time);
  93. mojom::URLResponseHeadPtr GetResponseHeadForTesting(
  94. const std::string& cache_key);
  95. void SetDataPipeCapacityForTesting(uint32_t capacity);
  96. private:
  97. struct Entry;
  98. using CacheMap = base::LRUCache<std::string, std::unique_ptr<Entry>>;
  99. // Returns the current time for cache freshness checks.
  100. base::Time GetCurrentTime();
  101. // Used for tracing.
  102. uint64_t GetNextTraceId();
  103. // Erases a single entry.
  104. void EraseEntry(CacheMap::iterator it);
  105. // Erases least recently used entries from the in-memory cache until
  106. // `total_bytes_` becomes less than `max_total_bytes_`.
  107. void ShrinkToTotalBytes();
  108. void OnMemoryPressure(
  109. base::MemoryPressureListener::MemoryPressureLevel level);
  110. // `network_context_` onws `this`.
  111. const raw_ptr<NetworkContext> network_context_;
  112. uint32_t next_trace_id_ = 0;
  113. CacheMap entries_;
  114. const size_t max_total_bytes_;
  115. const size_t max_per_entry_bytes_;
  116. size_t total_bytes_ = 0;
  117. std::set<std::unique_ptr<NetworkServiceMemoryCacheURLLoader>,
  118. base::UniquePtrComparator>
  119. url_loaders_;
  120. std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
  121. base::Time current_time_for_testing_;
  122. absl::optional<uint32_t> data_pipe_capacity_for_testing_;
  123. base::WeakPtrFactory<NetworkServiceMemoryCache> weak_ptr_factory_{this};
  124. };
  125. } // namespace network
  126. #endif // SERVICES_NETWORK_NETWORK_SERVICE_MEMORY_CACHE_H_