[SyncFS] Add completion callback to PromoteDemotedChanges
[chromium-blink-merge.git] / net / http / http_cache.h
blob5bdda8a1f9c89a1d18f71c920183c8bd69c4c188
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 <set>
19 #include <string>
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/message_loop/message_loop_proxy.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 disk_cache {
40 class Backend;
41 class Entry;
44 namespace net {
46 class CertVerifier;
47 class DiskBasedCertCache;
48 class HostResolver;
49 class HttpAuthHandlerFactory;
50 class HttpNetworkSession;
51 class HttpResponseInfo;
52 class HttpServerProperties;
53 class IOBuffer;
54 class NetLog;
55 class NetworkDelegate;
56 class ServerBoundCertService;
57 class ProxyService;
58 class SSLConfigService;
59 class TransportSecurityState;
60 class ViewCacheHelper;
61 struct HttpRequestInfo;
63 class NET_EXPORT HttpCache : public HttpTransactionFactory,
64 NON_EXPORTED_BASE(public base::NonThreadSafe) {
65 public:
66 // The cache mode of operation.
67 enum Mode {
68 // Normal mode just behaves like a standard web cache.
69 NORMAL = 0,
70 // Record mode caches everything for purposes of offline playback.
71 RECORD,
72 // Playback mode replays from a cache without considering any
73 // standard invalidations.
74 PLAYBACK,
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 // |cache_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, BackendType backend_type,
103 const base::FilePath& path, int max_bytes,
104 base::MessageLoopProxy* thread);
105 virtual ~DefaultBackend();
107 // Returns a factory for an in-memory cache.
108 static BackendFactory* InMemory(int max_bytes);
110 // BackendFactory implementation.
111 virtual int CreateBackend(NetLog* net_log,
112 scoped_ptr<disk_cache::Backend>* backend,
113 const CompletionCallback& callback) OVERRIDE;
115 private:
116 CacheType type_;
117 BackendType backend_type_;
118 const base::FilePath path_;
119 int max_bytes_;
120 scoped_refptr<base::MessageLoopProxy> thread_;
123 // The disk cache is initialized lazily (by CreateTransaction) in this case.
124 // The HttpCache takes ownership of the |backend_factory|.
125 HttpCache(const net::HttpNetworkSession::Params& params,
126 BackendFactory* backend_factory);
128 // The disk cache is initialized lazily (by CreateTransaction) in this case.
129 // Provide an existing HttpNetworkSession, the cache can construct a
130 // network layer with a shared HttpNetworkSession in order for multiple
131 // network layers to share information (e.g. authentication data). The
132 // HttpCache takes ownership of the |backend_factory|.
133 HttpCache(HttpNetworkSession* session, BackendFactory* backend_factory);
135 // Initialize the cache from its component parts. The lifetime of the
136 // |network_layer| and |backend_factory| are managed by the HttpCache and
137 // will be destroyed using |delete| when the HttpCache is destroyed.
138 HttpCache(HttpTransactionFactory* network_layer,
139 NetLog* net_log,
140 BackendFactory* backend_factory);
142 virtual ~HttpCache();
144 HttpTransactionFactory* network_layer() { return network_layer_.get(); }
146 DiskBasedCertCache* cert_cache() const { return cert_cache_.get(); }
148 // Retrieves the cache backend for this HttpCache instance. If the backend
149 // is not initialized yet, this method will initialize it. The return value is
150 // a network error code, and it could be ERR_IO_PENDING, in which case the
151 // |callback| will be notified when the operation completes. The pointer that
152 // receives the |backend| must remain valid until the operation completes.
153 int GetBackend(disk_cache::Backend** backend,
154 const net::CompletionCallback& callback);
156 // Returns the current backend (can be NULL).
157 disk_cache::Backend* GetCurrentBackend() const;
159 // Given a header data blob, convert it to a response info object.
160 static bool ParseResponseInfo(const char* data, int len,
161 HttpResponseInfo* response_info,
162 bool* response_truncated);
164 // Writes |buf_len| bytes of metadata stored in |buf| to the cache entry
165 // referenced by |url|, as long as the entry's |expected_response_time| has
166 // not changed. This method returns without blocking, and the operation will
167 // be performed asynchronously without any completion notification.
168 void WriteMetadata(const GURL& url,
169 RequestPriority priority,
170 base::Time expected_response_time,
171 IOBuffer* buf,
172 int buf_len);
174 // Get/Set the cache's mode.
175 void set_mode(Mode value) { mode_ = value; }
176 Mode mode() { return mode_; }
178 // Close currently active sockets so that fresh page loads will not use any
179 // recycled connections. For sockets currently in use, they may not close
180 // immediately, but they will not be reusable. This is for debugging.
181 void CloseAllConnections();
183 // Close all idle connections. Will close all sockets not in active use.
184 void CloseIdleConnections();
186 // Called whenever an external cache in the system reuses the resource
187 // referred to by |url| and |http_method|.
188 void OnExternalCacheHit(const GURL& url, const std::string& http_method);
190 // Initializes the Infinite Cache, if selected by the field trial.
191 void InitializeInfiniteCache(const base::FilePath& path);
193 // Causes all transactions created after this point to effectively bypass
194 // the cache lock whenever there is lock contention.
195 void BypassLockForTest() {
196 bypass_lock_for_test_ = true;
199 // HttpTransactionFactory implementation:
200 virtual int CreateTransaction(RequestPriority priority,
201 scoped_ptr<HttpTransaction>* trans) OVERRIDE;
202 virtual HttpCache* GetCache() OVERRIDE;
203 virtual HttpNetworkSession* GetSession() OVERRIDE;
205 base::WeakPtr<HttpCache> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
207 // Resets the network layer to allow for tests that probe
208 // network changes (e.g. host unreachable). The old network layer is
209 // returned to allow for filter patterns that only intercept
210 // some creation requests. Note ownership exchange.
211 scoped_ptr<HttpTransactionFactory>
212 SetHttpNetworkTransactionFactoryForTesting(
213 scoped_ptr<HttpTransactionFactory> new_network_layer);
215 private:
216 // Types --------------------------------------------------------------------
218 // Disk cache entry data indices.
219 enum {
220 kResponseInfoIndex = 0,
221 kResponseContentIndex,
222 kMetadataIndex,
224 // Must remain at the end of the enum.
225 kNumCacheEntryDataIndices
228 class MetadataWriter;
229 class QuicServerInfoFactoryAdaptor;
230 class Transaction;
231 class WorkItem;
232 friend class Transaction;
233 friend class ViewCacheHelper;
234 struct PendingOp; // Info for an entry under construction.
236 typedef std::list<Transaction*> TransactionList;
237 typedef std::list<WorkItem*> WorkItemList;
239 struct ActiveEntry {
240 explicit ActiveEntry(disk_cache::Entry* entry);
241 ~ActiveEntry();
243 disk_cache::Entry* disk_entry;
244 Transaction* writer;
245 TransactionList readers;
246 TransactionList pending_queue;
247 bool will_process_pending_queue;
248 bool doomed;
251 typedef base::hash_map<std::string, ActiveEntry*> ActiveEntriesMap;
252 typedef base::hash_map<std::string, PendingOp*> PendingOpsMap;
253 typedef std::set<ActiveEntry*> ActiveEntriesSet;
254 typedef base::hash_map<std::string, int> PlaybackCacheMap;
256 // Methods ------------------------------------------------------------------
258 // Creates the |backend| object and notifies the |callback| when the operation
259 // completes. Returns an error code.
260 int CreateBackend(disk_cache::Backend** backend,
261 const net::CompletionCallback& callback);
263 // Makes sure that the backend creation is complete before allowing the
264 // provided transaction to use the object. Returns an error code. |trans|
265 // will be notified via its IO callback if this method returns ERR_IO_PENDING.
266 // The transaction is free to use the backend directly at any time after
267 // receiving the notification.
268 int GetBackendForTransaction(Transaction* trans);
270 // Generates the cache key for this request.
271 std::string GenerateCacheKey(const HttpRequestInfo*);
273 // Dooms the entry selected by |key|, if it is currently in the list of active
274 // entries.
275 void DoomActiveEntry(const std::string& key);
277 // Dooms the entry selected by |key|. |trans| will be notified via its IO
278 // callback if this method returns ERR_IO_PENDING. The entry can be
279 // currently in use or not.
280 int DoomEntry(const std::string& key, Transaction* trans);
282 // Dooms the entry selected by |key|. |trans| will be notified via its IO
283 // callback if this method returns ERR_IO_PENDING. The entry should not
284 // be currently in use.
285 int AsyncDoomEntry(const std::string& key, Transaction* trans);
287 // Dooms the entry associated with a GET for a given |url|.
288 void DoomMainEntryForUrl(const GURL& url);
290 // Closes a previously doomed entry.
291 void FinalizeDoomedEntry(ActiveEntry* entry);
293 // Returns an entry that is currently in use and not doomed, or NULL.
294 ActiveEntry* FindActiveEntry(const std::string& key);
296 // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
297 // cache entry.
298 ActiveEntry* ActivateEntry(disk_cache::Entry* disk_entry);
300 // Deletes an ActiveEntry.
301 void DeactivateEntry(ActiveEntry* entry);
303 // Deletes an ActiveEntry using an exhaustive search.
304 void SlowDeactivateEntry(ActiveEntry* entry);
306 // Returns the PendingOp for the desired |key|. If an entry is not under
307 // construction already, a new PendingOp structure is created.
308 PendingOp* GetPendingOp(const std::string& key);
310 // Deletes a PendingOp.
311 void DeletePendingOp(PendingOp* pending_op);
313 // Opens the disk cache entry associated with |key|, returning an ActiveEntry
314 // in |*entry|. |trans| will be notified via its IO callback if this method
315 // returns ERR_IO_PENDING.
316 int OpenEntry(const std::string& key, ActiveEntry** entry,
317 Transaction* trans);
319 // Creates the disk cache entry associated with |key|, returning an
320 // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
321 // this method returns ERR_IO_PENDING.
322 int CreateEntry(const std::string& key, ActiveEntry** entry,
323 Transaction* trans);
325 // Destroys an ActiveEntry (active or doomed).
326 void DestroyEntry(ActiveEntry* entry);
328 // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
329 // the transaction will be notified about completion via its IO callback. This
330 // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
331 // added to the provided entry, and it should retry the process with another
332 // one (in this case, the entry is no longer valid).
333 int AddTransactionToEntry(ActiveEntry* entry, Transaction* trans);
335 // Called when the transaction has finished working with this entry. |cancel|
336 // is true if the operation was cancelled by the caller instead of running
337 // to completion.
338 void DoneWithEntry(ActiveEntry* entry, Transaction* trans, bool cancel);
340 // Called when the transaction has finished writing to this entry. |success|
341 // is false if the cache entry should be deleted.
342 void DoneWritingToEntry(ActiveEntry* entry, bool success);
344 // Called when the transaction has finished reading from this entry.
345 void DoneReadingFromEntry(ActiveEntry* entry, Transaction* trans);
347 // Converts the active writer transaction to a reader so that other
348 // transactions can start reading from this entry.
349 void ConvertWriterToReader(ActiveEntry* entry);
351 // Returns the LoadState of the provided pending transaction.
352 LoadState GetLoadStateForPendingTransaction(const Transaction* trans);
354 // Removes the transaction |trans|, from the pending list of an entry
355 // (PendingOp, active or doomed entry).
356 void RemovePendingTransaction(Transaction* trans);
358 // Removes the transaction |trans|, from the pending list of |entry|.
359 bool RemovePendingTransactionFromEntry(ActiveEntry* entry,
360 Transaction* trans);
362 // Removes the transaction |trans|, from the pending list of |pending_op|.
363 bool RemovePendingTransactionFromPendingOp(PendingOp* pending_op,
364 Transaction* trans);
366 // Instantiates and sets QUIC server info factory.
367 void SetupQuicServerInfoFactory(HttpNetworkSession* session);
369 // Resumes processing the pending list of |entry|.
370 void ProcessPendingQueue(ActiveEntry* entry);
372 // Events (called via PostTask) ---------------------------------------------
374 void OnProcessPendingQueue(ActiveEntry* entry);
376 // Callbacks ----------------------------------------------------------------
378 // Processes BackendCallback notifications.
379 void OnIOComplete(int result, PendingOp* entry);
381 // Helper to conditionally delete |pending_op| if the HttpCache object it
382 // is meant for has been deleted.
384 // TODO(ajwong): The PendingOp lifetime management is very tricky. It might
385 // be possible to simplify it using either base::Owned() or base::Passed()
386 // with the callback.
387 static void OnPendingOpComplete(const base::WeakPtr<HttpCache>& cache,
388 PendingOp* pending_op,
389 int result);
391 // Processes the backend creation notification.
392 void OnBackendCreated(int result, PendingOp* pending_op);
394 // Variables ----------------------------------------------------------------
396 NetLog* net_log_;
398 // Used when lazily constructing the disk_cache_.
399 scoped_ptr<BackendFactory> backend_factory_;
400 bool building_backend_;
401 bool bypass_lock_for_test_;
403 Mode mode_;
405 scoped_ptr<QuicServerInfoFactoryAdaptor> quic_server_info_factory_;
407 scoped_ptr<HttpTransactionFactory> network_layer_;
409 scoped_ptr<disk_cache::Backend> disk_cache_;
411 scoped_ptr<DiskBasedCertCache> cert_cache_;
413 // The set of active entries indexed by cache key.
414 ActiveEntriesMap active_entries_;
416 // The set of doomed entries.
417 ActiveEntriesSet doomed_entries_;
419 // The set of entries "under construction".
420 PendingOpsMap pending_ops_;
422 scoped_ptr<PlaybackCacheMap> playback_cache_map_;
424 base::WeakPtrFactory<HttpCache> weak_factory_;
426 DISALLOW_COPY_AND_ASSIGN(HttpCache);
429 } // namespace net
431 #endif // NET_HTTP_HTTP_CACHE_H_