[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / net / http / http_cache.h
blobe459475afa6e92d9c801302bb51b109bf57cda8c
1 // Copyright (c) 2012 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.
5 // This file declares a HttpTransactionFactory implementation that can be
6 // layered on top of another HttpTransactionFactory to add HTTP caching. The
7 // caching logic follows RFC 2616 (any exceptions are called out in the code).
8 //
9 // The HttpCache takes a disk_cache::Backend as a parameter, and uses that for
10 // the cache storage.
12 // See HttpTransactionFactory and HttpTransaction for more details.
14 #ifndef NET_HTTP_HTTP_CACHE_H_
15 #define NET_HTTP_HTTP_CACHE_H_
17 #include <list>
18 #include <map>
19 #include <set>
20 #include <string>
22 #include "base/basictypes.h"
23 #include "base/containers/hash_tables.h"
24 #include "base/files/file_path.h"
25 #include "base/memory/scoped_ptr.h"
26 #include "base/memory/weak_ptr.h"
27 #include "base/threading/non_thread_safe.h"
28 #include "base/time/clock.h"
29 #include "base/time/time.h"
30 #include "net/base/cache_type.h"
31 #include "net/base/completion_callback.h"
32 #include "net/base/load_states.h"
33 #include "net/base/net_export.h"
34 #include "net/base/request_priority.h"
35 #include "net/http/http_network_session.h"
36 #include "net/http/http_transaction_factory.h"
38 class GURL;
40 namespace base {
41 class SingleThreadTaskRunner;
42 } // namespace base
44 namespace disk_cache {
45 class Backend;
46 class Entry;
47 } // namespace disk_cache
49 namespace net {
51 class CertVerifier;
52 class ChannelIDService;
53 class DiskBasedCertCache;
54 class HostResolver;
55 class HttpAuthHandlerFactory;
56 class HttpNetworkSession;
57 class HttpResponseInfo;
58 class HttpServerProperties;
59 class IOBuffer;
60 class NetLog;
61 class NetworkDelegate;
62 class ProxyService;
63 class SSLConfigService;
64 class TransportSecurityState;
65 class ViewCacheHelper;
66 struct HttpRequestInfo;
68 class NET_EXPORT HttpCache : public HttpTransactionFactory,
69 NON_EXPORTED_BASE(public base::NonThreadSafe) {
70 public:
71 // The cache mode of operation.
72 enum Mode {
73 // Normal mode just behaves like a standard web cache.
74 NORMAL = 0,
75 // Disables reads and writes from the cache.
76 // Equivalent to setting LOAD_DISABLE_CACHE on every request.
77 DISABLE
80 // A BackendFactory creates a backend object to be used by the HttpCache.
81 class NET_EXPORT BackendFactory {
82 public:
83 virtual ~BackendFactory() {}
85 // The actual method to build the backend. Returns a net error code. If
86 // ERR_IO_PENDING is returned, the |callback| will be notified when the
87 // operation completes, and |backend| must remain valid until the
88 // notification arrives.
89 // The implementation must not access the factory object after invoking the
90 // |callback| because the object can be deleted from within the callback.
91 virtual int CreateBackend(NetLog* net_log,
92 scoped_ptr<disk_cache::Backend>* backend,
93 const CompletionCallback& callback) = 0;
96 // A default backend factory for the common use cases.
97 class NET_EXPORT DefaultBackend : public BackendFactory {
98 public:
99 // |path| is the destination for any files used by the backend, and
100 // |thread| is the thread where disk operations should take place. If
101 // |max_bytes| is zero, a default value will be calculated automatically.
102 DefaultBackend(CacheType type,
103 BackendType backend_type,
104 const base::FilePath& path,
105 int max_bytes,
106 const scoped_refptr<base::SingleThreadTaskRunner>& thread);
107 ~DefaultBackend() override;
109 // Returns a factory for an in-memory cache.
110 static BackendFactory* InMemory(int max_bytes);
112 // BackendFactory implementation.
113 int CreateBackend(NetLog* net_log,
114 scoped_ptr<disk_cache::Backend>* backend,
115 const CompletionCallback& callback) override;
117 private:
118 CacheType type_;
119 BackendType backend_type_;
120 const base::FilePath path_;
121 int max_bytes_;
122 scoped_refptr<base::SingleThreadTaskRunner> thread_;
125 // The number of minutes after a resource is prefetched that it can be used
126 // again without validation.
127 static const int kPrefetchReuseMins = 5;
129 // The disk cache is initialized lazily (by CreateTransaction) in this case.
130 // The HttpCache takes ownership of the |backend_factory|.
131 HttpCache(const net::HttpNetworkSession::Params& params,
132 BackendFactory* backend_factory);
134 // The disk cache is initialized lazily (by CreateTransaction) in this case.
135 // Provide an existing HttpNetworkSession, the cache can construct a
136 // network layer with a shared HttpNetworkSession in order for multiple
137 // network layers to share information (e.g. authentication data). The
138 // HttpCache takes ownership of the |backend_factory|.
139 HttpCache(HttpNetworkSession* session, BackendFactory* backend_factory);
141 // Initialize the cache from its component parts. The lifetime of the
142 // |network_layer| and |backend_factory| are managed by the HttpCache and
143 // will be destroyed using |delete| when the HttpCache is destroyed.
144 HttpCache(HttpTransactionFactory* network_layer,
145 NetLog* net_log,
146 BackendFactory* backend_factory);
148 ~HttpCache() override;
150 HttpTransactionFactory* network_layer() { return network_layer_.get(); }
152 DiskBasedCertCache* cert_cache() const { return cert_cache_.get(); }
154 // Retrieves the cache backend for this HttpCache instance. If the backend
155 // is not initialized yet, this method will initialize it. The return value is
156 // a network error code, and it could be ERR_IO_PENDING, in which case the
157 // |callback| will be notified when the operation completes. The pointer that
158 // receives the |backend| must remain valid until the operation completes.
159 int GetBackend(disk_cache::Backend** backend,
160 const net::CompletionCallback& callback);
162 // Returns the current backend (can be NULL).
163 disk_cache::Backend* GetCurrentBackend() const;
165 // Given a header data blob, convert it to a response info object.
166 static bool ParseResponseInfo(const char* data, int len,
167 HttpResponseInfo* response_info,
168 bool* response_truncated);
170 // Writes |buf_len| bytes of metadata stored in |buf| to the cache entry
171 // referenced by |url|, as long as the entry's |expected_response_time| has
172 // not changed. This method returns without blocking, and the operation will
173 // be performed asynchronously without any completion notification.
174 void WriteMetadata(const GURL& url,
175 RequestPriority priority,
176 base::Time expected_response_time,
177 IOBuffer* buf,
178 int buf_len);
180 // Get/Set the cache's mode.
181 void set_mode(Mode value) { mode_ = value; }
182 Mode mode() { return mode_; }
184 // Get/Set the cache's clock. These are public only for testing.
185 void SetClockForTesting(scoped_ptr<base::Clock> clock) {
186 clock_.reset(clock.release());
188 base::Clock* clock() const { return clock_.get(); }
190 // Close currently active sockets so that fresh page loads will not use any
191 // recycled connections. For sockets currently in use, they may not close
192 // immediately, but they will not be reusable. This is for debugging.
193 void CloseAllConnections();
195 // Close all idle connections. Will close all sockets not in active use.
196 void CloseIdleConnections();
198 // Called whenever an external cache in the system reuses the resource
199 // referred to by |url| and |http_method|.
200 void OnExternalCacheHit(const GURL& url, const std::string& http_method);
202 // Initializes the Infinite Cache, if selected by the field trial.
203 void InitializeInfiniteCache(const base::FilePath& path);
205 // Causes all transactions created after this point to effectively bypass
206 // the cache lock whenever there is lock contention.
207 void BypassLockForTest() {
208 bypass_lock_for_test_ = true;
211 // Causes all transactions created after this point to generate a failure
212 // when attempting to conditionalize a network request.
213 void FailConditionalizationForTest() {
214 fail_conditionalization_for_test_ = true;
217 bool use_stale_while_revalidate() const {
218 return use_stale_while_revalidate_;
221 // Enable stale_while_revalidate functionality for testing purposes.
222 void set_use_stale_while_revalidate_for_testing(
223 bool use_stale_while_revalidate) {
224 use_stale_while_revalidate_ = use_stale_while_revalidate;
227 // HttpTransactionFactory implementation:
228 int CreateTransaction(RequestPriority priority,
229 scoped_ptr<HttpTransaction>* trans) override;
230 HttpCache* GetCache() override;
231 HttpNetworkSession* GetSession() override;
233 base::WeakPtr<HttpCache> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
235 // Resets the network layer to allow for tests that probe
236 // network changes (e.g. host unreachable). The old network layer is
237 // returned to allow for filter patterns that only intercept
238 // some creation requests. Note ownership exchange.
239 scoped_ptr<HttpTransactionFactory>
240 SetHttpNetworkTransactionFactoryForTesting(
241 scoped_ptr<HttpTransactionFactory> new_network_layer);
243 private:
244 // Types --------------------------------------------------------------------
246 // Disk cache entry data indices.
247 enum {
248 kResponseInfoIndex = 0,
249 kResponseContentIndex,
250 kMetadataIndex,
252 // Must remain at the end of the enum.
253 kNumCacheEntryDataIndices
256 class MetadataWriter;
257 class QuicServerInfoFactoryAdaptor;
258 class Transaction;
259 class WorkItem;
260 friend class Transaction;
261 friend class ViewCacheHelper;
262 struct PendingOp; // Info for an entry under construction.
263 class AsyncValidation; // Encapsulates a single async revalidation.
265 typedef std::list<Transaction*> TransactionList;
266 typedef std::list<WorkItem*> WorkItemList;
267 typedef std::map<std::string, AsyncValidation*> AsyncValidationMap;
269 struct ActiveEntry {
270 explicit ActiveEntry(disk_cache::Entry* entry);
271 ~ActiveEntry();
273 disk_cache::Entry* disk_entry;
274 Transaction* writer;
275 TransactionList readers;
276 TransactionList pending_queue;
277 bool will_process_pending_queue;
278 bool doomed;
281 typedef base::hash_map<std::string, ActiveEntry*> ActiveEntriesMap;
282 typedef base::hash_map<std::string, PendingOp*> PendingOpsMap;
283 typedef std::set<ActiveEntry*> ActiveEntriesSet;
284 typedef base::hash_map<std::string, int> PlaybackCacheMap;
286 // Methods ------------------------------------------------------------------
288 // Creates the |backend| object and notifies the |callback| when the operation
289 // completes. Returns an error code.
290 int CreateBackend(disk_cache::Backend** backend,
291 const net::CompletionCallback& callback);
293 // Makes sure that the backend creation is complete before allowing the
294 // provided transaction to use the object. Returns an error code. |trans|
295 // will be notified via its IO callback if this method returns ERR_IO_PENDING.
296 // The transaction is free to use the backend directly at any time after
297 // receiving the notification.
298 int GetBackendForTransaction(Transaction* trans);
300 // Generates the cache key for this request.
301 std::string GenerateCacheKey(const HttpRequestInfo*);
303 // Dooms the entry selected by |key|, if it is currently in the list of active
304 // entries.
305 void DoomActiveEntry(const std::string& key);
307 // Dooms the entry selected by |key|. |trans| will be notified via its IO
308 // callback if this method returns ERR_IO_PENDING. The entry can be
309 // currently in use or not.
310 int DoomEntry(const std::string& key, Transaction* trans);
312 // Dooms the entry selected by |key|. |trans| will be notified via its IO
313 // callback if this method returns ERR_IO_PENDING. The entry should not
314 // be currently in use.
315 int AsyncDoomEntry(const std::string& key, Transaction* trans);
317 // Dooms the entry associated with a GET for a given |url|.
318 void DoomMainEntryForUrl(const GURL& url);
320 // Closes a previously doomed entry.
321 void FinalizeDoomedEntry(ActiveEntry* entry);
323 // Returns an entry that is currently in use and not doomed, or NULL.
324 ActiveEntry* FindActiveEntry(const std::string& key);
326 // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
327 // cache entry.
328 ActiveEntry* ActivateEntry(disk_cache::Entry* disk_entry);
330 // Deletes an ActiveEntry.
331 void DeactivateEntry(ActiveEntry* entry);
333 // Deletes an ActiveEntry using an exhaustive search.
334 void SlowDeactivateEntry(ActiveEntry* entry);
336 // Returns the PendingOp for the desired |key|. If an entry is not under
337 // construction already, a new PendingOp structure is created.
338 PendingOp* GetPendingOp(const std::string& key);
340 // Deletes a PendingOp.
341 void DeletePendingOp(PendingOp* pending_op);
343 // Opens the disk cache entry associated with |key|, returning an ActiveEntry
344 // in |*entry|. |trans| will be notified via its IO callback if this method
345 // returns ERR_IO_PENDING.
346 int OpenEntry(const std::string& key, ActiveEntry** entry,
347 Transaction* trans);
349 // Creates the disk cache entry associated with |key|, returning an
350 // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
351 // this method returns ERR_IO_PENDING.
352 int CreateEntry(const std::string& key, ActiveEntry** entry,
353 Transaction* trans);
355 // Destroys an ActiveEntry (active or doomed).
356 void DestroyEntry(ActiveEntry* entry);
358 // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
359 // the transaction will be notified about completion via its IO callback. This
360 // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
361 // added to the provided entry, and it should retry the process with another
362 // one (in this case, the entry is no longer valid).
363 int AddTransactionToEntry(ActiveEntry* entry, Transaction* trans);
365 // Called when the transaction has finished working with this entry. |cancel|
366 // is true if the operation was cancelled by the caller instead of running
367 // to completion.
368 void DoneWithEntry(ActiveEntry* entry, Transaction* trans, bool cancel);
370 // Called when the transaction has finished writing to this entry. |success|
371 // is false if the cache entry should be deleted.
372 void DoneWritingToEntry(ActiveEntry* entry, bool success);
374 // Called when the transaction has finished reading from this entry.
375 void DoneReadingFromEntry(ActiveEntry* entry, Transaction* trans);
377 // Converts the active writer transaction to a reader so that other
378 // transactions can start reading from this entry.
379 void ConvertWriterToReader(ActiveEntry* entry);
381 // Returns the LoadState of the provided pending transaction.
382 LoadState GetLoadStateForPendingTransaction(const Transaction* trans);
384 // Removes the transaction |trans|, from the pending list of an entry
385 // (PendingOp, active or doomed entry).
386 void RemovePendingTransaction(Transaction* trans);
388 // Removes the transaction |trans|, from the pending list of |entry|.
389 bool RemovePendingTransactionFromEntry(ActiveEntry* entry,
390 Transaction* trans);
392 // Removes the transaction |trans|, from the pending list of |pending_op|.
393 bool RemovePendingTransactionFromPendingOp(PendingOp* pending_op,
394 Transaction* trans);
396 // Instantiates and sets QUIC server info factory.
397 void SetupQuicServerInfoFactory(HttpNetworkSession* session);
399 // Resumes processing the pending list of |entry|.
400 void ProcessPendingQueue(ActiveEntry* entry);
402 // Called by Transaction to perform an asynchronous revalidation. Creates a
403 // new independent transaction as a copy of the original.
404 void PerformAsyncValidation(const HttpRequestInfo& original_request,
405 const BoundNetLog& net_log);
407 // Remove the AsyncValidation with url |url| from the |async_validations_| set
408 // and delete it.
409 void DeleteAsyncValidation(const std::string& url);
411 // Events (called via PostTask) ---------------------------------------------
413 void OnProcessPendingQueue(ActiveEntry* entry);
415 // Callbacks ----------------------------------------------------------------
417 // Processes BackendCallback notifications.
418 void OnIOComplete(int result, PendingOp* entry);
420 // Helper to conditionally delete |pending_op| if the HttpCache object it
421 // is meant for has been deleted.
423 // TODO(ajwong): The PendingOp lifetime management is very tricky. It might
424 // be possible to simplify it using either base::Owned() or base::Passed()
425 // with the callback.
426 static void OnPendingOpComplete(const base::WeakPtr<HttpCache>& cache,
427 PendingOp* pending_op,
428 int result);
430 // Processes the backend creation notification.
431 void OnBackendCreated(int result, PendingOp* pending_op);
433 // Variables ----------------------------------------------------------------
435 NetLog* net_log_;
437 // Used when lazily constructing the disk_cache_.
438 scoped_ptr<BackendFactory> backend_factory_;
439 bool building_backend_;
440 bool bypass_lock_for_test_;
441 bool fail_conditionalization_for_test_;
443 // true if the implementation of Cache-Control: stale-while-revalidate
444 // directive is enabled (either via command-line flag or experiment).
445 bool use_stale_while_revalidate_;
447 Mode mode_;
449 scoped_ptr<QuicServerInfoFactoryAdaptor> quic_server_info_factory_;
451 scoped_ptr<HttpTransactionFactory> network_layer_;
453 scoped_ptr<disk_cache::Backend> disk_cache_;
455 scoped_ptr<DiskBasedCertCache> cert_cache_;
457 // The set of active entries indexed by cache key.
458 ActiveEntriesMap active_entries_;
460 // The set of doomed entries.
461 ActiveEntriesSet doomed_entries_;
463 // The set of entries "under construction".
464 PendingOpsMap pending_ops_;
466 scoped_ptr<PlaybackCacheMap> playback_cache_map_;
468 // The async validations currently in progress, keyed by URL.
469 AsyncValidationMap async_validations_;
471 // A clock that can be swapped out for testing.
472 scoped_ptr<base::Clock> clock_;
474 base::WeakPtrFactory<HttpCache> weak_factory_;
476 DISALLOW_COPY_AND_ASSIGN(HttpCache);
479 } // namespace net
481 #endif // NET_HTTP_HTTP_CACHE_H_