Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / net / http / http_cache_transaction.h
blob0b4792bd116563c3dea02e2022e766865084d33e
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 HttpCache::Transaction, a private class of HttpCache so
6 // it should only be included by http_cache.cc
8 #ifndef NET_HTTP_HTTP_CACHE_TRANSACTION_H_
9 #define NET_HTTP_HTTP_CACHE_TRANSACTION_H_
11 #include <string>
13 #include "base/time/time.h"
14 #include "net/base/completion_callback.h"
15 #include "net/base/net_log.h"
16 #include "net/base/request_priority.h"
17 #include "net/http/http_cache.h"
18 #include "net/http/http_request_headers.h"
19 #include "net/http/http_response_headers.h"
20 #include "net/http/http_response_info.h"
21 #include "net/http/http_transaction.h"
23 namespace net {
25 class PartialData;
26 struct HttpRequestInfo;
27 struct LoadTimingInfo;
29 // This is the transaction that is returned by the HttpCache transaction
30 // factory.
31 class HttpCache::Transaction : public HttpTransaction {
32 public:
33 // The transaction has the following modes, which apply to how it may access
34 // its cache entry.
36 // o If the mode of the transaction is NONE, then it is in "pass through"
37 // mode and all methods just forward to the inner network transaction.
39 // o If the mode of the transaction is only READ, then it may only read from
40 // the cache entry.
42 // o If the mode of the transaction is only WRITE, then it may only write to
43 // the cache entry.
45 // o If the mode of the transaction is READ_WRITE, then the transaction may
46 // optionally modify the cache entry (e.g., possibly corresponding to
47 // cache validation).
49 // o If the mode of the transaction is UPDATE, then the transaction may
50 // update existing cache entries, but will never create a new entry or
51 // respond using the entry read from the cache.
52 enum Mode {
53 NONE = 0,
54 READ_META = 1 << 0,
55 READ_DATA = 1 << 1,
56 READ = READ_META | READ_DATA,
57 WRITE = 1 << 2,
58 READ_WRITE = READ | WRITE,
59 UPDATE = READ_META | WRITE, // READ_WRITE & ~READ_DATA
62 Transaction(RequestPriority priority,
63 HttpCache* cache);
64 ~Transaction() override;
66 Mode mode() const { return mode_; }
68 const std::string& key() const { return cache_key_; }
70 // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
71 // HTTP cache entry that backs this transaction (if any).
72 // Returns the number of bytes actually written, or a net error code. If the
73 // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
74 // reference to the buffer (until completion), and notifies the caller using
75 // the provided |callback| when the operation finishes.
77 // The first time this method is called for a given transaction, previous
78 // meta-data will be overwritten with the provided data, and subsequent
79 // invocations will keep appending to the cached entry.
81 // In order to guarantee that the metadata is set to the correct entry, the
82 // response (or response info) must be evaluated by the caller, for instance
83 // to make sure that the response_time is as expected, before calling this
84 // method.
85 int WriteMetadata(IOBuffer* buf,
86 int buf_len,
87 const CompletionCallback& callback);
89 // This transaction is being deleted and we are not done writing to the cache.
90 // We need to indicate that the response data was truncated. Returns true on
91 // success. Keep in mind that this operation may have side effects, such as
92 // deleting the active entry.
93 bool AddTruncatedFlag();
95 HttpCache::ActiveEntry* entry() { return entry_; }
97 // Returns the LoadState of the writer transaction of a given ActiveEntry. In
98 // other words, returns the LoadState of this transaction without asking the
99 // http cache, because this transaction should be the one currently writing
100 // to the cache entry.
101 LoadState GetWriterLoadState() const;
103 const CompletionCallback& io_callback() { return io_callback_; }
105 const BoundNetLog& net_log() const;
107 // Bypasses the cache lock whenever there is lock contention.
108 void BypassLockForTest() {
109 bypass_lock_for_test_ = true;
112 // HttpTransaction methods:
113 int Start(const HttpRequestInfo* request_info,
114 const CompletionCallback& callback,
115 const BoundNetLog& net_log) override;
116 int RestartIgnoringLastError(const CompletionCallback& callback) override;
117 int RestartWithCertificate(X509Certificate* client_cert,
118 const CompletionCallback& callback) override;
119 int RestartWithAuth(const AuthCredentials& credentials,
120 const CompletionCallback& callback) override;
121 bool IsReadyToRestartForAuth() override;
122 int Read(IOBuffer* buf,
123 int buf_len,
124 const CompletionCallback& callback) override;
125 void StopCaching() override;
126 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const override;
127 int64 GetTotalReceivedBytes() const override;
128 void DoneReading() override;
129 const HttpResponseInfo* GetResponseInfo() const override;
130 LoadState GetLoadState() const override;
131 UploadProgress GetUploadProgress(void) const override;
132 void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
133 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
134 void SetPriority(RequestPriority priority) override;
135 void SetWebSocketHandshakeStreamCreateHelper(
136 net::WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
137 void SetBeforeNetworkStartCallback(
138 const BeforeNetworkStartCallback& callback) override;
139 void SetBeforeProxyHeadersSentCallback(
140 const BeforeProxyHeadersSentCallback& callback) override;
141 int ResumeNetworkStart() override;
143 private:
144 static const size_t kNumValidationHeaders = 2;
145 // Helper struct to pair a header name with its value, for
146 // headers used to validate cache entries.
147 struct ValidationHeaders {
148 ValidationHeaders() : initialized(false) {}
150 std::string values[kNumValidationHeaders];
151 bool initialized;
154 enum State {
155 STATE_NONE,
156 STATE_GET_BACKEND,
157 STATE_GET_BACKEND_COMPLETE,
158 STATE_SEND_REQUEST,
159 STATE_SEND_REQUEST_COMPLETE,
160 STATE_SUCCESSFUL_SEND_REQUEST,
161 STATE_NETWORK_READ,
162 STATE_NETWORK_READ_COMPLETE,
163 STATE_INIT_ENTRY,
164 STATE_OPEN_ENTRY,
165 STATE_OPEN_ENTRY_COMPLETE,
166 STATE_CREATE_ENTRY,
167 STATE_CREATE_ENTRY_COMPLETE,
168 STATE_DOOM_ENTRY,
169 STATE_DOOM_ENTRY_COMPLETE,
170 STATE_ADD_TO_ENTRY,
171 STATE_ADD_TO_ENTRY_COMPLETE,
172 STATE_START_PARTIAL_CACHE_VALIDATION,
173 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
174 STATE_UPDATE_CACHED_RESPONSE,
175 STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
176 STATE_OVERWRITE_CACHED_RESPONSE,
177 STATE_TRUNCATE_CACHED_DATA,
178 STATE_TRUNCATE_CACHED_DATA_COMPLETE,
179 STATE_TRUNCATE_CACHED_METADATA,
180 STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
181 STATE_PARTIAL_HEADERS_RECEIVED,
182 STATE_CACHE_READ_RESPONSE,
183 STATE_CACHE_READ_RESPONSE_COMPLETE,
184 STATE_CACHE_WRITE_RESPONSE,
185 STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
186 STATE_CACHE_WRITE_RESPONSE_COMPLETE,
187 STATE_CACHE_READ_METADATA,
188 STATE_CACHE_READ_METADATA_COMPLETE,
189 STATE_CACHE_QUERY_DATA,
190 STATE_CACHE_QUERY_DATA_COMPLETE,
191 STATE_CACHE_READ_DATA,
192 STATE_CACHE_READ_DATA_COMPLETE,
193 STATE_CACHE_WRITE_DATA,
194 STATE_CACHE_WRITE_DATA_COMPLETE
197 // Used for categorizing transactions for reporting in histograms. Patterns
198 // cover relatively common use cases being measured and considered for
199 // optimization. Many use cases that are more complex or uncommon are binned
200 // as PATTERN_NOT_COVERED, and details are not reported.
201 // NOTE: This enumeration is used in histograms, so please do not add entries
202 // in the middle.
203 enum TransactionPattern {
204 PATTERN_UNDEFINED,
205 PATTERN_NOT_COVERED,
206 PATTERN_ENTRY_NOT_CACHED,
207 PATTERN_ENTRY_USED,
208 PATTERN_ENTRY_VALIDATED,
209 PATTERN_ENTRY_UPDATED,
210 PATTERN_ENTRY_CANT_CONDITIONALIZE,
211 PATTERN_MAX,
214 // This is a helper function used to trigger a completion callback. It may
215 // only be called if callback_ is non-null.
216 void DoCallback(int rv);
218 // This will trigger the completion callback if appropriate.
219 int HandleResult(int rv);
221 // Runs the state transition loop.
222 int DoLoop(int result);
224 // Each of these methods corresponds to a State value. If there is an
225 // argument, the value corresponds to the return of the previous state or
226 // corresponding callback.
227 int DoGetBackend();
228 int DoGetBackendComplete(int result);
229 int DoSendRequest();
230 int DoSendRequestComplete(int result);
231 int DoSuccessfulSendRequest();
232 int DoNetworkRead();
233 int DoNetworkReadComplete(int result);
234 int DoInitEntry();
235 int DoOpenEntry();
236 int DoOpenEntryComplete(int result);
237 int DoCreateEntry();
238 int DoCreateEntryComplete(int result);
239 int DoDoomEntry();
240 int DoDoomEntryComplete(int result);
241 int DoAddToEntry();
242 int DoAddToEntryComplete(int result);
243 int DoStartPartialCacheValidation();
244 int DoCompletePartialCacheValidation(int result);
245 int DoUpdateCachedResponse();
246 int DoUpdateCachedResponseComplete(int result);
247 int DoOverwriteCachedResponse();
248 int DoTruncateCachedData();
249 int DoTruncateCachedDataComplete(int result);
250 int DoTruncateCachedMetadata();
251 int DoTruncateCachedMetadataComplete(int result);
252 int DoPartialHeadersReceived();
253 int DoCacheReadResponse();
254 int DoCacheReadResponseComplete(int result);
255 int DoCacheWriteResponse();
256 int DoCacheWriteTruncatedResponse();
257 int DoCacheWriteResponseComplete(int result);
258 int DoCacheReadMetadata();
259 int DoCacheReadMetadataComplete(int result);
260 int DoCacheQueryData();
261 int DoCacheQueryDataComplete(int result);
262 int DoCacheReadData();
263 int DoCacheReadDataComplete(int result);
264 int DoCacheWriteData(int num_bytes);
265 int DoCacheWriteDataComplete(int result);
267 // These functions are involved in a field trial testing storing certificates
268 // in seperate entries from the HttpResponseInfo.
269 void ReadCertChain();
270 void WriteCertChain();
272 // Sets request_ and fields derived from it.
273 void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
275 // Returns true if the request should be handled exclusively by the network
276 // layer (skipping the cache entirely).
277 bool ShouldPassThrough();
279 // Called to begin reading from the cache. Returns network error code.
280 int BeginCacheRead();
282 // Called to begin validating the cache entry. Returns network error code.
283 int BeginCacheValidation();
285 // Called to begin validating an entry that stores partial content. Returns
286 // a network error code.
287 int BeginPartialCacheValidation();
289 // Validates the entry headers against the requested range and continues with
290 // the validation of the rest of the entry. Returns a network error code.
291 int ValidateEntryHeadersAndContinue();
293 // Called to start requests which were given an "if-modified-since" or
294 // "if-none-match" validation header by the caller (NOT when the request was
295 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
296 // Returns a network error code.
297 int BeginExternallyConditionalizedRequest();
299 // Called to restart a network transaction after an error. Returns network
300 // error code.
301 int RestartNetworkRequest();
303 // Called to restart a network transaction with a client certificate.
304 // Returns network error code.
305 int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
307 // Called to restart a network transaction with authentication credentials.
308 // Returns network error code.
309 int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
311 // Called to determine if we need to validate the cache entry before using it,
312 // and whether the validation should be synchronous or asynchronous.
313 ValidationType RequiresValidation();
315 // Called to make the request conditional (to ask the server if the cached
316 // copy is valid). Returns true if able to make the request conditional.
317 bool ConditionalizeRequest();
319 // Makes sure that a 206 response is expected. Returns true on success.
320 // On success, handling_206_ will be set to true if we are processing a
321 // partial entry.
322 bool ValidatePartialResponse();
324 // Handles a response validation error by bypassing the cache.
325 void IgnoreRangeRequest();
327 // Removes content-length and byte range related info if needed.
328 void FixHeadersForHead();
330 // Launches an asynchronous revalidation based on this transaction.
331 void TriggerAsyncValidation();
333 // Changes the response code of a range request to be 416 (Requested range not
334 // satisfiable).
335 void FailRangeRequest();
337 // Setups the transaction for reading from the cache entry.
338 int SetupEntryForRead();
340 // Reads data from the network.
341 int ReadFromNetwork(IOBuffer* data, int data_len);
343 // Reads data from the cache entry.
344 int ReadFromEntry(IOBuffer* data, int data_len);
346 // Called to write data to the cache entry. If the write fails, then the
347 // cache entry is destroyed. Future calls to this function will just do
348 // nothing without side-effect. Returns a network error code.
349 int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
350 const CompletionCallback& callback);
352 // Called to write response_ to the cache entry. |truncated| indicates if the
353 // entry should be marked as incomplete.
354 int WriteResponseInfoToEntry(bool truncated);
356 // Called to append response data to the cache entry. Returns a network error
357 // code.
358 int AppendResponseDataToEntry(IOBuffer* data, int data_len,
359 const CompletionCallback& callback);
361 // Called when we are done writing to the cache entry.
362 void DoneWritingToEntry(bool success);
364 // Returns an error to signal the caller that the current read failed. The
365 // current operation |result| is also logged. If |restart| is true, the
366 // transaction should be restarted.
367 int OnCacheReadError(int result, bool restart);
369 // Called when the cache lock timeout fires.
370 void OnAddToEntryTimeout(base::TimeTicks start_time);
372 // Deletes the current partial cache entry (sparse), and optionally removes
373 // the control object (partial_).
374 void DoomPartialEntry(bool delete_object);
376 // Performs the needed work after receiving data from the network, when
377 // working with range requests.
378 int DoPartialNetworkReadCompleted(int result);
380 // Performs the needed work after receiving data from the cache, when
381 // working with range requests.
382 int DoPartialCacheReadCompleted(int result);
384 // Restarts this transaction after deleting the cached data. It is meant to
385 // be used when the current request cannot be fulfilled due to conflicts
386 // between the byte range request and the cached entry.
387 int DoRestartPartialRequest();
389 // Resets |network_trans_|, which must be non-NULL. Also updates
390 // |old_network_trans_load_timing_|, which must be NULL when this is called.
391 void ResetNetworkTransaction();
393 // Returns true if we should bother attempting to resume this request if it
394 // is aborted while in progress. If |has_data| is true, the size of the stored
395 // data is considered for the result.
396 bool CanResume(bool has_data);
398 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
399 void RecordHistograms();
401 // Called to signal completion of asynchronous IO.
402 void OnIOComplete(int result);
404 State next_state_;
405 const HttpRequestInfo* request_;
406 RequestPriority priority_;
407 BoundNetLog net_log_;
408 scoped_ptr<HttpRequestInfo> custom_request_;
409 HttpRequestHeaders request_headers_copy_;
410 // If extra_headers specified a "if-modified-since" or "if-none-match",
411 // |external_validation_| contains the value of those headers.
412 ValidationHeaders external_validation_;
413 base::WeakPtr<HttpCache> cache_;
414 HttpCache::ActiveEntry* entry_;
415 HttpCache::ActiveEntry* new_entry_;
416 scoped_ptr<HttpTransaction> network_trans_;
417 CompletionCallback callback_; // Consumer's callback.
418 HttpResponseInfo response_;
419 HttpResponseInfo auth_response_;
420 const HttpResponseInfo* new_response_;
421 std::string cache_key_;
422 Mode mode_;
423 State target_state_;
424 bool reading_; // We are already reading. Never reverts to false once set.
425 bool invalid_range_; // We may bypass the cache for this request.
426 bool truncated_; // We don't have all the response data.
427 bool is_sparse_; // The data is stored in sparse byte ranges.
428 bool range_requested_; // The user requested a byte range.
429 bool handling_206_; // We must deal with this 206 response.
430 bool cache_pending_; // We are waiting for the HttpCache.
431 bool done_reading_; // All available data was read.
432 bool vary_mismatch_; // The request doesn't match the stored vary data.
433 bool couldnt_conditionalize_request_;
434 bool bypass_lock_for_test_; // A test is exercising the cache lock.
435 scoped_refptr<IOBuffer> read_buf_;
436 int io_buf_len_;
437 int read_offset_;
438 int effective_load_flags_;
439 int write_len_;
440 scoped_ptr<PartialData> partial_; // We are dealing with range requests.
441 UploadProgress final_upload_progress_;
442 CompletionCallback io_callback_;
444 // Members used to track data for histograms.
445 TransactionPattern transaction_pattern_;
446 base::TimeTicks entry_lock_waiting_since_;
447 base::TimeTicks first_cache_access_since_;
448 base::TimeTicks send_request_since_;
450 int64 total_received_bytes_;
452 // Load timing information for the last network request, if any. Set in the
453 // 304 and 206 response cases, as the network transaction may be destroyed
454 // before the caller requests load timing information.
455 scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
457 // The helper object to use to create WebSocketHandshakeStreamBase
458 // objects. Only relevant when establishing a WebSocket connection.
459 // This is passed to the underlying network transaction. It is stored here in
460 // case the transaction does not exist yet.
461 WebSocketHandshakeStreamBase::CreateHelper*
462 websocket_handshake_stream_base_create_helper_;
464 BeforeNetworkStartCallback before_network_start_callback_;
465 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
467 base::WeakPtrFactory<Transaction> weak_factory_;
469 DISALLOW_COPY_AND_ASSIGN(Transaction);
472 } // namespace net
474 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_