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).
9 // The HttpCache takes a disk_cache::Backend as a parameter, and uses that for
12 // See HttpTransactionFactory and HttpTransaction for more details.
14 #ifndef NET_HTTP_HTTP_CACHE_H_
15 #define NET_HTTP_HTTP_CACHE_H_
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"
41 class SingleThreadTaskRunner
;
44 namespace disk_cache
{
47 } // namespace disk_cache
52 class ChannelIDService
;
53 class DiskBasedCertCache
;
55 class HttpAuthHandlerFactory
;
56 class HttpNetworkSession
;
57 class HttpResponseInfo
;
58 class HttpServerProperties
;
61 class NetworkDelegate
;
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
) {
71 // The cache mode of operation.
73 // Normal mode just behaves like a standard web cache.
75 // Disables reads and writes from the cache.
76 // Equivalent to setting LOAD_DISABLE_CACHE on every request.
80 // A BackendFactory creates a backend object to be used by the HttpCache.
81 class NET_EXPORT BackendFactory
{
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
{
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
,
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
;
119 BackendType backend_type_
;
120 const base::FilePath path_
;
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
,
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
,
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 // Causes all transactions created after this point to effectively bypass
203 // the cache lock whenever there is lock contention.
204 void BypassLockForTest() {
205 bypass_lock_for_test_
= true;
208 // Causes all transactions created after this point to generate a failure
209 // when attempting to conditionalize a network request.
210 void FailConditionalizationForTest() {
211 fail_conditionalization_for_test_
= true;
214 bool use_stale_while_revalidate() const {
215 return use_stale_while_revalidate_
;
218 // Enable stale_while_revalidate functionality for testing purposes.
219 void set_use_stale_while_revalidate_for_testing(
220 bool use_stale_while_revalidate
) {
221 use_stale_while_revalidate_
= use_stale_while_revalidate
;
224 // HttpTransactionFactory implementation:
225 int CreateTransaction(RequestPriority priority
,
226 scoped_ptr
<HttpTransaction
>* trans
) override
;
227 HttpCache
* GetCache() override
;
228 HttpNetworkSession
* GetSession() override
;
230 base::WeakPtr
<HttpCache
> GetWeakPtr() { return weak_factory_
.GetWeakPtr(); }
232 // Resets the network layer to allow for tests that probe
233 // network changes (e.g. host unreachable). The old network layer is
234 // returned to allow for filter patterns that only intercept
235 // some creation requests. Note ownership exchange.
236 scoped_ptr
<HttpTransactionFactory
>
237 SetHttpNetworkTransactionFactoryForTesting(
238 scoped_ptr
<HttpTransactionFactory
> new_network_layer
);
241 // Types --------------------------------------------------------------------
243 // Disk cache entry data indices.
245 kResponseInfoIndex
= 0,
246 kResponseContentIndex
,
249 // Must remain at the end of the enum.
250 kNumCacheEntryDataIndices
253 class MetadataWriter
;
254 class QuicServerInfoFactoryAdaptor
;
257 friend class Transaction
;
258 friend class ViewCacheHelper
;
259 struct PendingOp
; // Info for an entry under construction.
260 class AsyncValidation
; // Encapsulates a single async revalidation.
262 typedef std::list
<Transaction
*> TransactionList
;
263 typedef std::list
<WorkItem
*> WorkItemList
;
264 typedef std::map
<std::string
, AsyncValidation
*> AsyncValidationMap
;
267 explicit ActiveEntry(disk_cache::Entry
* entry
);
270 disk_cache::Entry
* disk_entry
;
272 TransactionList readers
;
273 TransactionList pending_queue
;
274 bool will_process_pending_queue
;
278 typedef base::hash_map
<std::string
, ActiveEntry
*> ActiveEntriesMap
;
279 typedef base::hash_map
<std::string
, PendingOp
*> PendingOpsMap
;
280 typedef std::set
<ActiveEntry
*> ActiveEntriesSet
;
281 typedef base::hash_map
<std::string
, int> PlaybackCacheMap
;
283 // Methods ------------------------------------------------------------------
285 // Creates the |backend| object and notifies the |callback| when the operation
286 // completes. Returns an error code.
287 int CreateBackend(disk_cache::Backend
** backend
,
288 const net::CompletionCallback
& callback
);
290 // Makes sure that the backend creation is complete before allowing the
291 // provided transaction to use the object. Returns an error code. |trans|
292 // will be notified via its IO callback if this method returns ERR_IO_PENDING.
293 // The transaction is free to use the backend directly at any time after
294 // receiving the notification.
295 int GetBackendForTransaction(Transaction
* trans
);
297 // Generates the cache key for this request.
298 std::string
GenerateCacheKey(const HttpRequestInfo
*);
300 // Dooms the entry selected by |key|, if it is currently in the list of active
302 void DoomActiveEntry(const std::string
& key
);
304 // Dooms the entry selected by |key|. |trans| will be notified via its IO
305 // callback if this method returns ERR_IO_PENDING. The entry can be
306 // currently in use or not.
307 int DoomEntry(const std::string
& key
, Transaction
* trans
);
309 // Dooms the entry selected by |key|. |trans| will be notified via its IO
310 // callback if this method returns ERR_IO_PENDING. The entry should not
311 // be currently in use.
312 int AsyncDoomEntry(const std::string
& key
, Transaction
* trans
);
314 // Dooms the entry associated with a GET for a given |url|.
315 void DoomMainEntryForUrl(const GURL
& url
);
317 // Closes a previously doomed entry.
318 void FinalizeDoomedEntry(ActiveEntry
* entry
);
320 // Returns an entry that is currently in use and not doomed, or NULL.
321 ActiveEntry
* FindActiveEntry(const std::string
& key
);
323 // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
325 ActiveEntry
* ActivateEntry(disk_cache::Entry
* disk_entry
);
327 // Deletes an ActiveEntry.
328 void DeactivateEntry(ActiveEntry
* entry
);
330 // Deletes an ActiveEntry using an exhaustive search.
331 void SlowDeactivateEntry(ActiveEntry
* entry
);
333 // Returns the PendingOp for the desired |key|. If an entry is not under
334 // construction already, a new PendingOp structure is created.
335 PendingOp
* GetPendingOp(const std::string
& key
);
337 // Deletes a PendingOp.
338 void DeletePendingOp(PendingOp
* pending_op
);
340 // Opens the disk cache entry associated with |key|, returning an ActiveEntry
341 // in |*entry|. |trans| will be notified via its IO callback if this method
342 // returns ERR_IO_PENDING.
343 int OpenEntry(const std::string
& key
, ActiveEntry
** entry
,
346 // Creates the disk cache entry associated with |key|, returning an
347 // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
348 // this method returns ERR_IO_PENDING.
349 int CreateEntry(const std::string
& key
, ActiveEntry
** entry
,
352 // Destroys an ActiveEntry (active or doomed).
353 void DestroyEntry(ActiveEntry
* entry
);
355 // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
356 // the transaction will be notified about completion via its IO callback. This
357 // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
358 // added to the provided entry, and it should retry the process with another
359 // one (in this case, the entry is no longer valid).
360 int AddTransactionToEntry(ActiveEntry
* entry
, Transaction
* trans
);
362 // Called when the transaction has finished working with this entry. |cancel|
363 // is true if the operation was cancelled by the caller instead of running
365 void DoneWithEntry(ActiveEntry
* entry
, Transaction
* trans
, bool cancel
);
367 // Called when the transaction has finished writing to this entry. |success|
368 // is false if the cache entry should be deleted.
369 void DoneWritingToEntry(ActiveEntry
* entry
, bool success
);
371 // Called when the transaction has finished reading from this entry.
372 void DoneReadingFromEntry(ActiveEntry
* entry
, Transaction
* trans
);
374 // Converts the active writer transaction to a reader so that other
375 // transactions can start reading from this entry.
376 void ConvertWriterToReader(ActiveEntry
* entry
);
378 // Returns the LoadState of the provided pending transaction.
379 LoadState
GetLoadStateForPendingTransaction(const Transaction
* trans
);
381 // Removes the transaction |trans|, from the pending list of an entry
382 // (PendingOp, active or doomed entry).
383 void RemovePendingTransaction(Transaction
* trans
);
385 // Removes the transaction |trans|, from the pending list of |entry|.
386 bool RemovePendingTransactionFromEntry(ActiveEntry
* entry
,
389 // Removes the transaction |trans|, from the pending list of |pending_op|.
390 bool RemovePendingTransactionFromPendingOp(PendingOp
* pending_op
,
393 // Instantiates and sets QUIC server info factory.
394 void SetupQuicServerInfoFactory(HttpNetworkSession
* session
);
396 // Resumes processing the pending list of |entry|.
397 void ProcessPendingQueue(ActiveEntry
* entry
);
399 // Called by Transaction to perform an asynchronous revalidation. Creates a
400 // new independent transaction as a copy of the original.
401 void PerformAsyncValidation(const HttpRequestInfo
& original_request
,
402 const BoundNetLog
& net_log
);
404 // Remove the AsyncValidation with url |url| from the |async_validations_| set
406 void DeleteAsyncValidation(const std::string
& url
);
408 // Events (called via PostTask) ---------------------------------------------
410 void OnProcessPendingQueue(ActiveEntry
* entry
);
412 // Callbacks ----------------------------------------------------------------
414 // Processes BackendCallback notifications.
415 void OnIOComplete(int result
, PendingOp
* entry
);
417 // Helper to conditionally delete |pending_op| if the HttpCache object it
418 // is meant for has been deleted.
420 // TODO(ajwong): The PendingOp lifetime management is very tricky. It might
421 // be possible to simplify it using either base::Owned() or base::Passed()
422 // with the callback.
423 static void OnPendingOpComplete(const base::WeakPtr
<HttpCache
>& cache
,
424 PendingOp
* pending_op
,
427 // Processes the backend creation notification.
428 void OnBackendCreated(int result
, PendingOp
* pending_op
);
430 // Variables ----------------------------------------------------------------
434 // Used when lazily constructing the disk_cache_.
435 scoped_ptr
<BackendFactory
> backend_factory_
;
436 bool building_backend_
;
437 bool bypass_lock_for_test_
;
438 bool fail_conditionalization_for_test_
;
440 // true if the implementation of Cache-Control: stale-while-revalidate
441 // directive is enabled (either via command-line flag or experiment).
442 bool use_stale_while_revalidate_
;
446 scoped_ptr
<QuicServerInfoFactoryAdaptor
> quic_server_info_factory_
;
448 scoped_ptr
<HttpTransactionFactory
> network_layer_
;
450 scoped_ptr
<disk_cache::Backend
> disk_cache_
;
452 scoped_ptr
<DiskBasedCertCache
> cert_cache_
;
454 // The set of active entries indexed by cache key.
455 ActiveEntriesMap active_entries_
;
457 // The set of doomed entries.
458 ActiveEntriesSet doomed_entries_
;
460 // The set of entries "under construction".
461 PendingOpsMap pending_ops_
;
463 scoped_ptr
<PlaybackCacheMap
> playback_cache_map_
;
465 // The async validations currently in progress, keyed by URL.
466 AsyncValidationMap async_validations_
;
468 // A clock that can be swapped out for testing.
469 scoped_ptr
<base::Clock
> clock_
;
471 base::WeakPtrFactory
<HttpCache
> weak_factory_
;
473 DISALLOW_COPY_AND_ASSIGN(HttpCache
);
478 #endif // NET_HTTP_HTTP_CACHE_H_