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 7234 (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_
21 #include "base/basictypes.h"
22 #include "base/containers/hash_tables.h"
23 #include "base/files/file_path.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/memory/weak_ptr.h"
26 #include "base/threading/non_thread_safe.h"
27 #include "base/time/clock.h"
28 #include "base/time/time.h"
29 #include "net/base/cache_type.h"
30 #include "net/base/completion_callback.h"
31 #include "net/base/load_states.h"
32 #include "net/base/net_export.h"
33 #include "net/base/request_priority.h"
34 #include "net/http/http_network_session.h"
35 #include "net/http/http_transaction_factory.h"
40 class SingleThreadTaskRunner
;
43 namespace disk_cache
{
46 } // namespace disk_cache
51 class ChannelIDService
;
52 class DiskBasedCertCache
;
54 class HttpAuthHandlerFactory
;
55 class HttpNetworkSession
;
56 class HttpResponseInfo
;
57 class HttpServerProperties
;
60 class NetworkDelegate
;
62 class SSLConfigService
;
63 class TransportSecurityState
;
64 class ViewCacheHelper
;
65 struct HttpRequestInfo
;
67 class NET_EXPORT HttpCache
: public HttpTransactionFactory
,
68 NON_EXPORTED_BASE(public base::NonThreadSafe
) {
70 // The cache mode of operation.
72 // Normal mode just behaves like a standard web cache.
74 // Disables reads and writes from the cache.
75 // Equivalent to setting LOAD_DISABLE_CACHE on every request.
79 // A BackendFactory creates a backend object to be used by the HttpCache.
80 class NET_EXPORT BackendFactory
{
82 virtual ~BackendFactory() {}
84 // The actual method to build the backend. Returns a net error code. If
85 // ERR_IO_PENDING is returned, the |callback| will be notified when the
86 // operation completes, and |backend| must remain valid until the
87 // notification arrives.
88 // The implementation must not access the factory object after invoking the
89 // |callback| because the object can be deleted from within the callback.
90 virtual int CreateBackend(NetLog
* net_log
,
91 scoped_ptr
<disk_cache::Backend
>* backend
,
92 const CompletionCallback
& callback
) = 0;
95 // A default backend factory for the common use cases.
96 class NET_EXPORT DefaultBackend
: public BackendFactory
{
98 // |path| is the destination for any files used by the backend, and
99 // |thread| is the thread where disk operations should take place. If
100 // |max_bytes| is zero, a default value will be calculated automatically.
101 DefaultBackend(CacheType type
,
102 BackendType backend_type
,
103 const base::FilePath
& path
,
105 const scoped_refptr
<base::SingleThreadTaskRunner
>& thread
);
106 ~DefaultBackend() override
;
108 // Returns a factory for an in-memory cache.
109 static BackendFactory
* InMemory(int max_bytes
);
111 // BackendFactory implementation.
112 int CreateBackend(NetLog
* net_log
,
113 scoped_ptr
<disk_cache::Backend
>* backend
,
114 const CompletionCallback
& callback
) override
;
118 BackendType backend_type_
;
119 const base::FilePath path_
;
121 scoped_refptr
<base::SingleThreadTaskRunner
> thread_
;
124 // The number of minutes after a resource is prefetched that it can be used
125 // again without validation.
126 static const int kPrefetchReuseMins
= 5;
128 // The disk cache is initialized lazily (by CreateTransaction) in this case.
129 // The HttpCache takes ownership of the |backend_factory|.
130 HttpCache(const HttpNetworkSession::Params
& params
,
131 BackendFactory
* backend_factory
);
133 // The disk cache is initialized lazily (by CreateTransaction) in this case.
134 // Provide an existing HttpNetworkSession, the cache can construct a
135 // network layer with a shared HttpNetworkSession in order for multiple
136 // network layers to share information (e.g. authentication data). The
137 // HttpCache takes ownership of the |backend_factory|.
138 HttpCache(HttpNetworkSession
* session
, BackendFactory
* backend_factory
);
140 // Initialize the cache from its component parts. The lifetime of the
141 // |network_layer| and |backend_factory| are managed by the HttpCache and
142 // will be destroyed using |delete| when the HttpCache is destroyed.
143 HttpCache(HttpTransactionFactory
* network_layer
,
145 BackendFactory
* backend_factory
);
147 ~HttpCache() override
;
149 HttpTransactionFactory
* network_layer() { return network_layer_
.get(); }
151 DiskBasedCertCache
* cert_cache() const { return cert_cache_
.get(); }
153 // Retrieves the cache backend for this HttpCache instance. If the backend
154 // is not initialized yet, this method will initialize it. The return value is
155 // a network error code, and it could be ERR_IO_PENDING, in which case the
156 // |callback| will be notified when the operation completes. The pointer that
157 // receives the |backend| must remain valid until the operation completes.
158 int GetBackend(disk_cache::Backend
** backend
,
159 const CompletionCallback
& callback
);
161 // Returns the current backend (can be NULL).
162 disk_cache::Backend
* GetCurrentBackend() const;
164 // Given a header data blob, convert it to a response info object.
165 static bool ParseResponseInfo(const char* data
, int len
,
166 HttpResponseInfo
* response_info
,
167 bool* response_truncated
);
169 // Writes |buf_len| bytes of metadata stored in |buf| to the cache entry
170 // referenced by |url|, as long as the entry's |expected_response_time| has
171 // not changed. This method returns without blocking, and the operation will
172 // be performed asynchronously without any completion notification.
173 // Takes ownership of |buf|.
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 // HttpTransactionFactory implementation:
215 int CreateTransaction(RequestPriority priority
,
216 scoped_ptr
<HttpTransaction
>* trans
) override
;
217 HttpCache
* GetCache() override
;
218 HttpNetworkSession
* GetSession() override
;
220 base::WeakPtr
<HttpCache
> GetWeakPtr() { return weak_factory_
.GetWeakPtr(); }
222 // Resets the network layer to allow for tests that probe
223 // network changes (e.g. host unreachable). The old network layer is
224 // returned to allow for filter patterns that only intercept
225 // some creation requests. Note ownership exchange.
226 scoped_ptr
<HttpTransactionFactory
>
227 SetHttpNetworkTransactionFactoryForTesting(
228 scoped_ptr
<HttpTransactionFactory
> new_network_layer
);
231 // Types --------------------------------------------------------------------
233 // Disk cache entry data indices.
235 kResponseInfoIndex
= 0,
236 kResponseContentIndex
,
239 // Must remain at the end of the enum.
240 kNumCacheEntryDataIndices
243 class MetadataWriter
;
244 class QuicServerInfoFactoryAdaptor
;
247 friend class Transaction
;
248 friend class ViewCacheHelper
;
249 struct PendingOp
; // Info for an entry under construction.
251 typedef std::list
<Transaction
*> TransactionList
;
252 typedef std::list
<WorkItem
*> WorkItemList
;
255 explicit ActiveEntry(disk_cache::Entry
* entry
);
258 disk_cache::Entry
* disk_entry
;
260 TransactionList readers
;
261 TransactionList pending_queue
;
262 bool will_process_pending_queue
;
266 typedef base::hash_map
<std::string
, ActiveEntry
*> ActiveEntriesMap
;
267 typedef base::hash_map
<std::string
, PendingOp
*> PendingOpsMap
;
268 typedef std::set
<ActiveEntry
*> ActiveEntriesSet
;
269 typedef base::hash_map
<std::string
, int> PlaybackCacheMap
;
271 // Methods ------------------------------------------------------------------
273 // Creates the |backend| object and notifies the |callback| when the operation
274 // completes. Returns an error code.
275 int CreateBackend(disk_cache::Backend
** backend
,
276 const CompletionCallback
& callback
);
278 // Makes sure that the backend creation is complete before allowing the
279 // provided transaction to use the object. Returns an error code. |trans|
280 // will be notified via its IO callback if this method returns ERR_IO_PENDING.
281 // The transaction is free to use the backend directly at any time after
282 // receiving the notification.
283 int GetBackendForTransaction(Transaction
* trans
);
285 // Generates the cache key for this request.
286 std::string
GenerateCacheKey(const HttpRequestInfo
*);
288 // Dooms the entry selected by |key|, if it is currently in the list of active
290 void DoomActiveEntry(const std::string
& key
);
292 // Dooms the entry selected by |key|. |trans| will be notified via its IO
293 // callback if this method returns ERR_IO_PENDING. The entry can be
294 // currently in use or not.
295 int DoomEntry(const std::string
& key
, Transaction
* trans
);
297 // Dooms the entry selected by |key|. |trans| will be notified via its IO
298 // callback if this method returns ERR_IO_PENDING. The entry should not
299 // be currently in use.
300 int AsyncDoomEntry(const std::string
& key
, Transaction
* trans
);
302 // Dooms the entry associated with a GET for a given |url|.
303 void DoomMainEntryForUrl(const GURL
& url
);
305 // Closes a previously doomed entry.
306 void FinalizeDoomedEntry(ActiveEntry
* entry
);
308 // Returns an entry that is currently in use and not doomed, or NULL.
309 ActiveEntry
* FindActiveEntry(const std::string
& key
);
311 // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
313 ActiveEntry
* ActivateEntry(disk_cache::Entry
* disk_entry
);
315 // Deletes an ActiveEntry.
316 void DeactivateEntry(ActiveEntry
* entry
);
318 // Deletes an ActiveEntry using an exhaustive search.
319 void SlowDeactivateEntry(ActiveEntry
* entry
);
321 // Returns the PendingOp for the desired |key|. If an entry is not under
322 // construction already, a new PendingOp structure is created.
323 PendingOp
* GetPendingOp(const std::string
& key
);
325 // Deletes a PendingOp.
326 void DeletePendingOp(PendingOp
* pending_op
);
328 // Opens the disk cache entry associated with |key|, returning an ActiveEntry
329 // in |*entry|. |trans| will be notified via its IO callback if this method
330 // returns ERR_IO_PENDING.
331 int OpenEntry(const std::string
& key
, ActiveEntry
** entry
,
334 // Creates the disk cache entry associated with |key|, returning an
335 // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
336 // this method returns ERR_IO_PENDING.
337 int CreateEntry(const std::string
& key
, ActiveEntry
** entry
,
340 // Destroys an ActiveEntry (active or doomed).
341 void DestroyEntry(ActiveEntry
* entry
);
343 // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
344 // the transaction will be notified about completion via its IO callback. This
345 // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
346 // added to the provided entry, and it should retry the process with another
347 // one (in this case, the entry is no longer valid).
348 int AddTransactionToEntry(ActiveEntry
* entry
, Transaction
* trans
);
350 // Called when the transaction has finished working with this entry. |cancel|
351 // is true if the operation was cancelled by the caller instead of running
353 void DoneWithEntry(ActiveEntry
* entry
, Transaction
* trans
, bool cancel
);
355 // Called when the transaction has finished writing to this entry. |success|
356 // is false if the cache entry should be deleted.
357 void DoneWritingToEntry(ActiveEntry
* entry
, bool success
);
359 // Called when the transaction has finished reading from this entry.
360 void DoneReadingFromEntry(ActiveEntry
* entry
, Transaction
* trans
);
362 // Converts the active writer transaction to a reader so that other
363 // transactions can start reading from this entry.
364 void ConvertWriterToReader(ActiveEntry
* entry
);
366 // Returns the LoadState of the provided pending transaction.
367 LoadState
GetLoadStateForPendingTransaction(const Transaction
* trans
);
369 // Removes the transaction |trans|, from the pending list of an entry
370 // (PendingOp, active or doomed entry).
371 void RemovePendingTransaction(Transaction
* trans
);
373 // Removes the transaction |trans|, from the pending list of |entry|.
374 bool RemovePendingTransactionFromEntry(ActiveEntry
* entry
,
377 // Removes the transaction |trans|, from the pending list of |pending_op|.
378 bool RemovePendingTransactionFromPendingOp(PendingOp
* pending_op
,
381 // Instantiates and sets QUIC server info factory.
382 void SetupQuicServerInfoFactory(HttpNetworkSession
* session
);
384 // Resumes processing the pending list of |entry|.
385 void ProcessPendingQueue(ActiveEntry
* entry
);
387 // Events (called via PostTask) ---------------------------------------------
389 void OnProcessPendingQueue(ActiveEntry
* entry
);
391 // Callbacks ----------------------------------------------------------------
393 // Processes BackendCallback notifications.
394 void OnIOComplete(int result
, PendingOp
* entry
);
396 // Helper to conditionally delete |pending_op| if the HttpCache object it
397 // is meant for has been deleted.
399 // TODO(ajwong): The PendingOp lifetime management is very tricky. It might
400 // be possible to simplify it using either base::Owned() or base::Passed()
401 // with the callback.
402 static void OnPendingOpComplete(const base::WeakPtr
<HttpCache
>& cache
,
403 PendingOp
* pending_op
,
406 // Processes the backend creation notification.
407 void OnBackendCreated(int result
, PendingOp
* pending_op
);
409 // Variables ----------------------------------------------------------------
413 // Used when lazily constructing the disk_cache_.
414 scoped_ptr
<BackendFactory
> backend_factory_
;
415 bool building_backend_
;
416 bool bypass_lock_for_test_
;
417 bool fail_conditionalization_for_test_
;
421 scoped_ptr
<QuicServerInfoFactoryAdaptor
> quic_server_info_factory_
;
423 scoped_ptr
<HttpTransactionFactory
> network_layer_
;
425 scoped_ptr
<disk_cache::Backend
> disk_cache_
;
427 scoped_ptr
<DiskBasedCertCache
> cert_cache_
;
429 // The set of active entries indexed by cache key.
430 ActiveEntriesMap active_entries_
;
432 // The set of doomed entries.
433 ActiveEntriesSet doomed_entries_
;
435 // The set of entries "under construction".
436 PendingOpsMap pending_ops_
;
438 scoped_ptr
<PlaybackCacheMap
> playback_cache_map_
;
440 // A clock that can be swapped out for testing.
441 scoped_ptr
<base::Clock
> clock_
;
443 base::WeakPtrFactory
<HttpCache
> weak_factory_
;
445 DISALLOW_COPY_AND_ASSIGN(HttpCache
);
450 #endif // NET_HTTP_HTTP_CACHE_H_