cronet_context.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // Copyright 2014 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 COMPONENTS_CRONET_CRONET_CONTEXT_H_
  5. #define COMPONENTS_CRONET_CRONET_CONTEXT_H_
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <string>
  9. #include "base/callback.h"
  10. #include "base/containers/flat_map.h"
  11. #include "base/containers/queue.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/threading/thread.h"
  15. #include "base/threading/thread_checker.h"
  16. #include "base/values.h"
  17. #include "components/prefs/json_pref_store.h"
  18. #include "net/base/network_change_notifier.h"
  19. #include "net/base/network_handle.h"
  20. #include "net/nqe/effective_connection_type.h"
  21. #include "net/nqe/effective_connection_type_observer.h"
  22. #include "net/nqe/network_quality_estimator.h"
  23. #include "net/nqe/network_quality_observation_source.h"
  24. #include "net/nqe/rtt_throughput_estimates_observer.h"
  25. class PrefService;
  26. namespace base {
  27. class SingleThreadTaskRunner;
  28. class TimeTicks;
  29. } // namespace base
  30. namespace net {
  31. enum EffectiveConnectionType;
  32. class ProxyConfigService;
  33. class NetLog;
  34. class URLRequestContext;
  35. class URLRequestContextBuilder;
  36. class URLRequestContextGetter;
  37. class FileNetLogObserver;
  38. } // namespace net
  39. namespace cronet {
  40. class CronetPrefsManager;
  41. class TestUtil;
  42. struct URLRequestContextConfig;
  43. // Wrapper around net::URLRequestContext.
  44. class CronetContext {
  45. public:
  46. // Callback implemented by CronetContext() caller and owned by
  47. // CronetContext::NetworkTasks.
  48. class Callback {
  49. public:
  50. virtual ~Callback() = default;
  51. // Invoked on network thread when initialized.
  52. virtual void OnInitNetworkThread() = 0;
  53. // Invoked on network thread immediately prior to destruction.
  54. virtual void OnDestroyNetworkThread() = 0;
  55. // net::NetworkQualityEstimator::EffectiveConnectionTypeObserver forwarder.
  56. virtual void OnEffectiveConnectionTypeChanged(
  57. net::EffectiveConnectionType effective_connection_type) = 0;
  58. // net::NetworkQualityEstimator::RTTAndThroughputEstimatesObserver
  59. // forwarder.
  60. virtual void OnRTTOrThroughputEstimatesComputed(
  61. int32_t http_rtt_ms,
  62. int32_t transport_rtt_ms,
  63. int32_t downstream_throughput_kbps) = 0;
  64. // net::NetworkQualityEstimator::RTTObserver forwarder.
  65. virtual void OnRTTObservation(
  66. int32_t rtt_ms,
  67. int32_t timestamp_ms,
  68. net::NetworkQualityObservationSource source) = 0;
  69. // net::NetworkQualityEstimator::RTTObserver forwarder.
  70. virtual void OnThroughputObservation(
  71. int32_t throughput_kbps,
  72. int32_t timestamp_ms,
  73. net::NetworkQualityObservationSource source) = 0;
  74. // Callback for StopNetLog() that signals that it is safe to access
  75. // the NetLog files.
  76. virtual void OnStopNetLogCompleted() = 0;
  77. };
  78. // Constructs CronetContext using |context_config|. The |callback|
  79. // is owned by |this| and is deleted on network thread.
  80. // All |callback| methods are invoked on network thread.
  81. // If the network_task_runner is not assigned, a network thread would be
  82. // created for network tasks. Otherwise the tasks would be running on the
  83. // assigned task runner.
  84. CronetContext(std::unique_ptr<URLRequestContextConfig> context_config,
  85. std::unique_ptr<Callback> callback,
  86. scoped_refptr<base::SingleThreadTaskRunner>
  87. network_task_runner = nullptr);
  88. CronetContext(const CronetContext&) = delete;
  89. CronetContext& operator=(const CronetContext&) = delete;
  90. // Releases all resources for the request context and deletes the object.
  91. // Blocks until network thread is destroyed after running all pending tasks.
  92. virtual ~CronetContext();
  93. // Called on init thread to initialize URLRequestContext.
  94. void InitRequestContextOnInitThread();
  95. // Posts a task that might depend on the context being initialized
  96. // to the network thread.
  97. void PostTaskToNetworkThread(const base::Location& posted_from,
  98. base::OnceClosure callback);
  99. // Returns true if running on network thread.
  100. bool IsOnNetworkThread() const;
  101. // Returns the net::URLRequestContext associated with `network`.
  102. // kInvalidNetworkHandle represent the default context: this one will always
  103. // be present and used whenever a requests doesn't specify a target network
  104. // (currently the only possible behavior).
  105. net::URLRequestContext* GetURLRequestContext(
  106. net::handles::NetworkHandle network =
  107. net::handles::kInvalidNetworkHandle);
  108. // Returns a new instance of net::URLRequestContextGetter.
  109. // The net::URLRequestContext and base::SingleThreadTaskRunner that
  110. // net::URLRequestContextGetter returns are owned by `this`.
  111. // The returned getter will always return the default context of `this`.
  112. net::URLRequestContextGetter* CreateURLRequestContextGetter();
  113. // TODO(xunjieli): Keep only one version of StartNetLog().
  114. // Starts NetLog logging to file. This can be called on any thread.
  115. // Return false if |file_name| cannot be opened.
  116. bool StartNetLogToFile(const std::string& file_name, bool log_all);
  117. // Starts NetLog logging to disk with a bounded amount of disk space. This
  118. // can be called on any thread.
  119. void StartNetLogToDisk(const std::string& dir_name,
  120. bool log_all,
  121. int max_size);
  122. // Stops NetLog logging to file. This can be called on any thread. This will
  123. // flush any remaining writes to disk.
  124. void StopNetLog();
  125. // Destroys the URLRequestContext associated to `network` if `network` has
  126. // disconnected and it has no pending URLRequests. This must be called on
  127. // the network thread while destroying a CronetURLRequest as that might
  128. // mark a URLRequestContext as eligible for destruction.
  129. void MaybeDestroyURLRequestContext(net::handles::NetworkHandle network);
  130. // Default net::LOAD flags used to create requests.
  131. int default_load_flags() const;
  132. // Configures the network quality estimator to observe requests to localhost,
  133. // to use smaller responses when estimating throughput, and to disable the
  134. // device offline checks when computing the effective connection type or when
  135. // writing the prefs. This should only be used for testing. This can be
  136. // called only after the network quality estimator has been enabled.
  137. void ConfigureNetworkQualityEstimatorForTesting(bool use_local_host_requests,
  138. bool use_smaller_responses,
  139. bool disable_offline_check);
  140. bool URLRequestContextExistsForTesting(net::handles::NetworkHandle network);
  141. // Request that RTT and/or throughput observations should or should not be
  142. // provided by the network quality estimator.
  143. void ProvideRTTObservations(bool should);
  144. void ProvideThroughputObservations(bool should);
  145. bool bidi_stream_detect_broken_connection() const {
  146. return bidi_stream_detect_broken_connection_;
  147. }
  148. base::TimeDelta heartbeat_interval() const { return heartbeat_interval_; }
  149. bool skip_logging() const { return skip_logging_; }
  150. // NetworkTasks performs tasks on the network thread and owns objects that
  151. // live on the network thread.
  152. class NetworkTasks : public net::EffectiveConnectionTypeObserver,
  153. public net::RTTAndThroughputEstimatesObserver,
  154. public net::NetworkQualityEstimator::RTTObserver,
  155. public net::NetworkQualityEstimator::ThroughputObserver,
  156. public net::NetworkChangeNotifier::NetworkObserver {
  157. public:
  158. // Invoked off the network thread.
  159. // `listen_to_network_changes` is a temporary parameter to allow
  160. // multi-network testing for the time being.
  161. NetworkTasks(std::unique_ptr<URLRequestContextConfig> config,
  162. std::unique_ptr<CronetContext::Callback> callback);
  163. NetworkTasks(const NetworkTasks&) = delete;
  164. NetworkTasks& operator=(const NetworkTasks&) = delete;
  165. // Invoked on the network thread.
  166. ~NetworkTasks() override;
  167. // Initializes |context_| on the network thread.
  168. void Initialize(
  169. scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
  170. scoped_refptr<base::SequencedTaskRunner> file_task_runner,
  171. std::unique_ptr<net::ProxyConfigService> proxy_config_service);
  172. // Runs a task that might depend on the context being initialized.
  173. void RunTaskAfterContextInit(
  174. base::OnceClosure task_to_run_after_context_init);
  175. // Configures the network quality estimator to observe requests to
  176. // localhost, to use smaller responses when estimating throughput, and to
  177. // disable the device offline checks when computing the effective connection
  178. // type or when writing the prefs. This should only be used for testing.
  179. void ConfigureNetworkQualityEstimatorForTesting(
  180. bool use_local_host_requests,
  181. bool use_smaller_responses,
  182. bool disable_offline_check);
  183. void ProvideRTTObservations(bool should);
  184. void ProvideThroughputObservations(bool should);
  185. // net::NetworkQualityEstimator::EffectiveConnectionTypeObserver
  186. // implementation.
  187. void OnEffectiveConnectionTypeChanged(
  188. net::EffectiveConnectionType effective_connection_type) override;
  189. // net::NetworkQualityEstimator::RTTAndThroughputEstimatesObserver
  190. // implementation.
  191. void OnRTTOrThroughputEstimatesComputed(
  192. base::TimeDelta http_rtt,
  193. base::TimeDelta transport_rtt,
  194. int32_t downstream_throughput_kbps) override;
  195. // net::NetworkQualityEstimator::RTTObserver implementation.
  196. void OnRTTObservation(int32_t rtt_ms,
  197. const base::TimeTicks& timestamp,
  198. net::NetworkQualityObservationSource source) override;
  199. // net::NetworkQualityEstimator::ThroughputObserver implementation.
  200. void OnThroughputObservation(
  201. int32_t throughput_kbps,
  202. const base::TimeTicks& timestamp,
  203. net::NetworkQualityObservationSource source) override;
  204. // net::NetworkChangeNotifier::NetworkObserver implementation.
  205. void OnNetworkDisconnected(net::handles::NetworkHandle network) override;
  206. void OnNetworkConnected(net::handles::NetworkHandle network) override;
  207. void OnNetworkSoonToDisconnect(
  208. net::handles::NetworkHandle network) override;
  209. void OnNetworkMadeDefault(net::handles::NetworkHandle network) override;
  210. net::URLRequestContext* GetURLRequestContext(
  211. net::handles::NetworkHandle network);
  212. // Same as StartNetLogToDisk.
  213. void StartNetLogToBoundedFile(const std::string& dir_path,
  214. bool include_socket_bytes,
  215. int size);
  216. // Same as StartNetLogToFile, but called only on the network thread.
  217. void StartNetLog(const base::FilePath& file_path,
  218. bool include_socket_bytes);
  219. // Stops NetLog logging.
  220. void StopNetLog();
  221. void MaybeDestroyURLRequestContext(net::handles::NetworkHandle network);
  222. // Callback for StopObserving() that unblocks the client thread and
  223. // signals that it is safe to access the NetLog files.
  224. void StopNetLogCompleted();
  225. // Initializes Network Quality Estimator (NQE) prefs manager on network
  226. // thread.
  227. void InitializeNQEPrefs() const;
  228. void SpawnNetworkBoundURLRequestContextForTesting(
  229. net::handles::NetworkHandle network);
  230. bool URLRequestContextExistsForTesting(net::handles::NetworkHandle network);
  231. private:
  232. friend class TestUtil;
  233. base::Value GetNetLogInfo() const;
  234. // Configures `context_builder` with the settings shared between default
  235. // context and network bound contexts.
  236. void SetSharedURLRequestContextBuilderConfig(
  237. net::URLRequestContextBuilder* context_builder);
  238. // Configures `context` with the settings shared between default context
  239. // and network bound contexts.
  240. void SetSharedURLRequestContextConfig(net::URLRequestContext* context);
  241. // Builds a URLRequestContext specifically bound to `network`.
  242. std::unique_ptr<net::URLRequestContext> BuildNetworkBoundURLRequestContext(
  243. net::handles::NetworkHandle network);
  244. // Builds a URLRequestContext to be used a default context for `this`.
  245. // `proxy_config_service` is injected as it currently cannot be built on the
  246. // network thread.
  247. std::unique_ptr<net::URLRequestContext> BuildDefaultURLRequestContext(
  248. std::unique_ptr<net::ProxyConfigService> proxy_config_service);
  249. std::unique_ptr<net::FileNetLogObserver> net_log_file_observer_;
  250. // A network quality estimator. This member variable has to be destroyed
  251. // after destroying |cronet_prefs_manager_|, which owns
  252. // NetworkQualityPrefsManager that weakly references
  253. // |network_quality_estimator_|.
  254. std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator_;
  255. // Manages the PrefService and all associated persistence managers
  256. // such as NetworkQualityPrefsManager, HostCachePersistenceManager, etc.
  257. // It should be destroyed before |network_quality_estimator_| and
  258. // after |context_|.
  259. std::unique_ptr<CronetPrefsManager> cronet_prefs_manager_;
  260. // The mapping between networks and their URLRequestContext. The only
  261. // context guaranteed to exist for the entire lifetime of `this` is default
  262. // one, which is associated to kInvalidNetworkHandle.
  263. // For requests not requiring a specific network the default context must be
  264. // used.
  265. base::flat_map<net::handles::NetworkHandle,
  266. std::unique_ptr<net::URLRequestContext>>
  267. contexts_;
  268. // Shorthand for the default context (needed by
  269. // components/cronet/android/test/cronet_test_util.cc).
  270. raw_ptr<net::URLRequestContext> default_context_;
  271. bool is_default_context_initialized_;
  272. // Context config is only valid until context is initialized.
  273. std::unique_ptr<URLRequestContextConfig> context_config_;
  274. // Effective experimental options. Kept for NetLog.
  275. base::Value::Dict effective_experimental_options_;
  276. // A queue of tasks that need to be run after context has been initialized.
  277. base::queue<base::OnceClosure> tasks_waiting_for_context_;
  278. // Task runner that runs network tasks.
  279. scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
  280. // Task runner that runs file tasks.
  281. scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
  282. // Callback implemented by the client.
  283. std::unique_ptr<CronetContext::Callback> callback_;
  284. THREAD_CHECKER(network_thread_checker_);
  285. };
  286. private:
  287. friend class TestUtil;
  288. class ContextGetter;
  289. scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const;
  290. // Gets the file thread. Create one if there is none.
  291. base::Thread* GetFileThread();
  292. // Whether the connection status of active bidirectional streams should be
  293. // monitored.
  294. bool bidi_stream_detect_broken_connection_;
  295. // If |bidi_stream_detect_broken_connection_| is true, this suggests the
  296. // period of the heartbeat signal.
  297. base::TimeDelta heartbeat_interval_;
  298. // Whether Cronet's logging should be skipped or not.
  299. bool skip_logging_;
  300. const int default_load_flags_;
  301. // File thread should be destroyed last.
  302. std::unique_ptr<base::Thread> file_thread_;
  303. // |network_tasks_| is owned by |this|. It is created off the network thread,
  304. // but invoked and destroyed on network thread.
  305. raw_ptr<NetworkTasks> network_tasks_;
  306. // Network thread is destroyed from client thread.
  307. std::unique_ptr<base::Thread> network_thread_;
  308. // Task runner that runs network tasks.
  309. scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
  310. };
  311. } // namespace cronet
  312. #endif // COMPONENTS_CRONET_CRONET_CONTEXT_H_