Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / net / http / http_cache.h
blob1c1338b0d75d8019b82a5964609008b58d85ae0d
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/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"
37 class GURL;
39 namespace base {
40 class SingleThreadTaskRunner;
41 } // namespace base
43 namespace disk_cache {
44 class Backend;
45 class Entry;
46 } // namespace disk_cache
48 namespace net {
50 class CertVerifier;
51 class ChannelIDService;
52 class DiskBasedCertCache;
53 class HostResolver;
54 class HttpAuthHandlerFactory;
55 class HttpNetworkSession;
56 class HttpResponseInfo;
57 class HttpServerProperties;
58 class IOBuffer;
59 class NetLog;
60 class NetworkDelegate;
61 class ProxyService;
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) {
69 public:
70 // The cache mode of operation.
71 enum Mode {
72 // Normal mode just behaves like a standard web cache.
73 NORMAL = 0,
74 // Record mode caches everything for purposes of offline playback.
75 RECORD,
76 // Playback mode replays from a cache without considering any
77 // standard invalidations.
78 PLAYBACK,
79 // Disables reads and writes from the cache.
80 // Equivalent to setting LOAD_DISABLE_CACHE on every request.
81 DISABLE
84 // A BackendFactory creates a backend object to be used by the HttpCache.
85 class NET_EXPORT BackendFactory {
86 public:
87 virtual ~BackendFactory() {}
89 // The actual method to build the backend. Returns a net error code. If
90 // ERR_IO_PENDING is returned, the |callback| will be notified when the
91 // operation completes, and |backend| must remain valid until the
92 // notification arrives.
93 // The implementation must not access the factory object after invoking the
94 // |callback| because the object can be deleted from within the callback.
95 virtual int CreateBackend(NetLog* net_log,
96 scoped_ptr<disk_cache::Backend>* backend,
97 const CompletionCallback& callback) = 0;
100 // A default backend factory for the common use cases.
101 class NET_EXPORT DefaultBackend : public BackendFactory {
102 public:
103 // |path| is the destination for any files used by the backend, and
104 // |thread| is the thread where disk operations should take place. If
105 // |max_bytes| is zero, a default value will be calculated automatically.
106 DefaultBackend(CacheType type,
107 BackendType backend_type,
108 const base::FilePath& path,
109 int max_bytes,
110 const scoped_refptr<base::SingleThreadTaskRunner>& thread);
111 ~DefaultBackend() override;
113 // Returns a factory for an in-memory cache.
114 static BackendFactory* InMemory(int max_bytes);
116 // BackendFactory implementation.
117 int CreateBackend(NetLog* net_log,
118 scoped_ptr<disk_cache::Backend>* backend,
119 const CompletionCallback& callback) override;
121 private:
122 CacheType type_;
123 BackendType backend_type_;
124 const base::FilePath path_;
125 int max_bytes_;
126 scoped_refptr<base::SingleThreadTaskRunner> thread_;
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 // Close currently active sockets so that fresh page loads will not use any
185 // recycled connections. For sockets currently in use, they may not close
186 // immediately, but they will not be reusable. This is for debugging.
187 void CloseAllConnections();
189 // Close all idle connections. Will close all sockets not in active use.
190 void CloseIdleConnections();
192 // Called whenever an external cache in the system reuses the resource
193 // referred to by |url| and |http_method|.
194 void OnExternalCacheHit(const GURL& url, const std::string& http_method);
196 // Initializes the Infinite Cache, if selected by the field trial.
197 void InitializeInfiniteCache(const base::FilePath& path);
199 // Causes all transactions created after this point to effectively bypass
200 // the cache lock whenever there is lock contention.
201 void BypassLockForTest() {
202 bypass_lock_for_test_ = true;
205 bool use_stale_while_revalidate() const {
206 return use_stale_while_revalidate_;
209 // Enable stale_while_revalidate functionality for testing purposes.
210 void set_use_stale_while_revalidate_for_testing(
211 bool use_stale_while_revalidate) {
212 use_stale_while_revalidate_ = use_stale_while_revalidate;
215 // HttpTransactionFactory implementation:
216 int CreateTransaction(RequestPriority priority,
217 scoped_ptr<HttpTransaction>* trans) override;
218 HttpCache* GetCache() override;
219 HttpNetworkSession* GetSession() override;
221 base::WeakPtr<HttpCache> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
223 // Resets the network layer to allow for tests that probe
224 // network changes (e.g. host unreachable). The old network layer is
225 // returned to allow for filter patterns that only intercept
226 // some creation requests. Note ownership exchange.
227 scoped_ptr<HttpTransactionFactory>
228 SetHttpNetworkTransactionFactoryForTesting(
229 scoped_ptr<HttpTransactionFactory> new_network_layer);
231 private:
232 // Types --------------------------------------------------------------------
234 // Disk cache entry data indices.
235 enum {
236 kResponseInfoIndex = 0,
237 kResponseContentIndex,
238 kMetadataIndex,
240 // Must remain at the end of the enum.
241 kNumCacheEntryDataIndices
244 class MetadataWriter;
245 class QuicServerInfoFactoryAdaptor;
246 class Transaction;
247 class WorkItem;
248 friend class Transaction;
249 friend class ViewCacheHelper;
250 struct PendingOp; // Info for an entry under construction.
251 class AsyncValidation; // Encapsulates a single async revalidation.
253 typedef std::list<Transaction*> TransactionList;
254 typedef std::list<WorkItem*> WorkItemList;
255 typedef std::map<std::string, AsyncValidation*> AsyncValidationMap;
257 struct ActiveEntry {
258 explicit ActiveEntry(disk_cache::Entry* entry);
259 ~ActiveEntry();
261 disk_cache::Entry* disk_entry;
262 Transaction* writer;
263 TransactionList readers;
264 TransactionList pending_queue;
265 bool will_process_pending_queue;
266 bool doomed;
269 typedef base::hash_map<std::string, ActiveEntry*> ActiveEntriesMap;
270 typedef base::hash_map<std::string, PendingOp*> PendingOpsMap;
271 typedef std::set<ActiveEntry*> ActiveEntriesSet;
272 typedef base::hash_map<std::string, int> PlaybackCacheMap;
274 // Methods ------------------------------------------------------------------
276 // Creates the |backend| object and notifies the |callback| when the operation
277 // completes. Returns an error code.
278 int CreateBackend(disk_cache::Backend** backend,
279 const net::CompletionCallback& callback);
281 // Makes sure that the backend creation is complete before allowing the
282 // provided transaction to use the object. Returns an error code. |trans|
283 // will be notified via its IO callback if this method returns ERR_IO_PENDING.
284 // The transaction is free to use the backend directly at any time after
285 // receiving the notification.
286 int GetBackendForTransaction(Transaction* trans);
288 // Generates the cache key for this request.
289 std::string GenerateCacheKey(const HttpRequestInfo*);
291 // Dooms the entry selected by |key|, if it is currently in the list of active
292 // entries.
293 void DoomActiveEntry(const std::string& key);
295 // Dooms the entry selected by |key|. |trans| will be notified via its IO
296 // callback if this method returns ERR_IO_PENDING. The entry can be
297 // currently in use or not.
298 int DoomEntry(const std::string& key, Transaction* trans);
300 // Dooms the entry selected by |key|. |trans| will be notified via its IO
301 // callback if this method returns ERR_IO_PENDING. The entry should not
302 // be currently in use.
303 int AsyncDoomEntry(const std::string& key, Transaction* trans);
305 // Dooms the entry associated with a GET for a given |url|.
306 void DoomMainEntryForUrl(const GURL& url);
308 // Closes a previously doomed entry.
309 void FinalizeDoomedEntry(ActiveEntry* entry);
311 // Returns an entry that is currently in use and not doomed, or NULL.
312 ActiveEntry* FindActiveEntry(const std::string& key);
314 // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
315 // cache entry.
316 ActiveEntry* ActivateEntry(disk_cache::Entry* disk_entry);
318 // Deletes an ActiveEntry.
319 void DeactivateEntry(ActiveEntry* entry);
321 // Deletes an ActiveEntry using an exhaustive search.
322 void SlowDeactivateEntry(ActiveEntry* entry);
324 // Returns the PendingOp for the desired |key|. If an entry is not under
325 // construction already, a new PendingOp structure is created.
326 PendingOp* GetPendingOp(const std::string& key);
328 // Deletes a PendingOp.
329 void DeletePendingOp(PendingOp* pending_op);
331 // Opens the disk cache entry associated with |key|, returning an ActiveEntry
332 // in |*entry|. |trans| will be notified via its IO callback if this method
333 // returns ERR_IO_PENDING.
334 int OpenEntry(const std::string& key, ActiveEntry** entry,
335 Transaction* trans);
337 // Creates the disk cache entry associated with |key|, returning an
338 // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
339 // this method returns ERR_IO_PENDING.
340 int CreateEntry(const std::string& key, ActiveEntry** entry,
341 Transaction* trans);
343 // Destroys an ActiveEntry (active or doomed).
344 void DestroyEntry(ActiveEntry* entry);
346 // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
347 // the transaction will be notified about completion via its IO callback. This
348 // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
349 // added to the provided entry, and it should retry the process with another
350 // one (in this case, the entry is no longer valid).
351 int AddTransactionToEntry(ActiveEntry* entry, Transaction* trans);
353 // Called when the transaction has finished working with this entry. |cancel|
354 // is true if the operation was cancelled by the caller instead of running
355 // to completion.
356 void DoneWithEntry(ActiveEntry* entry, Transaction* trans, bool cancel);
358 // Called when the transaction has finished writing to this entry. |success|
359 // is false if the cache entry should be deleted.
360 void DoneWritingToEntry(ActiveEntry* entry, bool success);
362 // Called when the transaction has finished reading from this entry.
363 void DoneReadingFromEntry(ActiveEntry* entry, Transaction* trans);
365 // Converts the active writer transaction to a reader so that other
366 // transactions can start reading from this entry.
367 void ConvertWriterToReader(ActiveEntry* entry);
369 // Returns the LoadState of the provided pending transaction.
370 LoadState GetLoadStateForPendingTransaction(const Transaction* trans);
372 // Removes the transaction |trans|, from the pending list of an entry
373 // (PendingOp, active or doomed entry).
374 void RemovePendingTransaction(Transaction* trans);
376 // Removes the transaction |trans|, from the pending list of |entry|.
377 bool RemovePendingTransactionFromEntry(ActiveEntry* entry,
378 Transaction* trans);
380 // Removes the transaction |trans|, from the pending list of |pending_op|.
381 bool RemovePendingTransactionFromPendingOp(PendingOp* pending_op,
382 Transaction* trans);
384 // Instantiates and sets QUIC server info factory.
385 void SetupQuicServerInfoFactory(HttpNetworkSession* session);
387 // Resumes processing the pending list of |entry|.
388 void ProcessPendingQueue(ActiveEntry* entry);
390 // Called by Transaction to perform an asynchronous revalidation. Creates a
391 // new independent transaction as a copy of the original.
392 void PerformAsyncValidation(const HttpRequestInfo& original_request,
393 const BoundNetLog& net_log);
395 // Remove the AsyncValidation with url |url| from the |async_validations_| set
396 // and delete it.
397 void DeleteAsyncValidation(const std::string& url);
399 // Events (called via PostTask) ---------------------------------------------
401 void OnProcessPendingQueue(ActiveEntry* entry);
403 // Callbacks ----------------------------------------------------------------
405 // Processes BackendCallback notifications.
406 void OnIOComplete(int result, PendingOp* entry);
408 // Helper to conditionally delete |pending_op| if the HttpCache object it
409 // is meant for has been deleted.
411 // TODO(ajwong): The PendingOp lifetime management is very tricky. It might
412 // be possible to simplify it using either base::Owned() or base::Passed()
413 // with the callback.
414 static void OnPendingOpComplete(const base::WeakPtr<HttpCache>& cache,
415 PendingOp* pending_op,
416 int result);
418 // Processes the backend creation notification.
419 void OnBackendCreated(int result, PendingOp* pending_op);
421 // Variables ----------------------------------------------------------------
423 NetLog* net_log_;
425 // Used when lazily constructing the disk_cache_.
426 scoped_ptr<BackendFactory> backend_factory_;
427 bool building_backend_;
428 bool bypass_lock_for_test_;
430 // true if the implementation of Cache-Control: stale-while-revalidate
431 // directive is enabled (either via command-line flag or experiment).
432 bool use_stale_while_revalidate_;
434 Mode mode_;
436 scoped_ptr<QuicServerInfoFactoryAdaptor> quic_server_info_factory_;
438 scoped_ptr<HttpTransactionFactory> network_layer_;
440 scoped_ptr<disk_cache::Backend> disk_cache_;
442 scoped_ptr<DiskBasedCertCache> cert_cache_;
444 // The set of active entries indexed by cache key.
445 ActiveEntriesMap active_entries_;
447 // The set of doomed entries.
448 ActiveEntriesSet doomed_entries_;
450 // The set of entries "under construction".
451 PendingOpsMap pending_ops_;
453 scoped_ptr<PlaybackCacheMap> playback_cache_map_;
455 // The async validations currently in progress, keyed by URL.
456 AsyncValidationMap async_validations_;
458 base::WeakPtrFactory<HttpCache> weak_factory_;
460 DISALLOW_COPY_AND_ASSIGN(HttpCache);
463 } // namespace net
465 #endif // NET_HTTP_HTTP_CACHE_H_