Move android_app_version_* into an inner variables dict.
[chromium-blink-merge.git] / net / http / http_cache_transaction.h
blobf230f42e8a1430b17340aa5112470fa721368ccb
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 // Generates a failure when attempting to conditionalize a network request.
113 void FailConditionalizationForTest() {
114 fail_conditionalization_for_test_ = true;
117 // HttpTransaction methods:
118 int Start(const HttpRequestInfo* request_info,
119 const CompletionCallback& callback,
120 const BoundNetLog& net_log) override;
121 int RestartIgnoringLastError(const CompletionCallback& callback) override;
122 int RestartWithCertificate(X509Certificate* client_cert,
123 const CompletionCallback& callback) override;
124 int RestartWithAuth(const AuthCredentials& credentials,
125 const CompletionCallback& callback) override;
126 bool IsReadyToRestartForAuth() override;
127 int Read(IOBuffer* buf,
128 int buf_len,
129 const CompletionCallback& callback) override;
130 void StopCaching() override;
131 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const override;
132 int64 GetTotalReceivedBytes() const override;
133 void DoneReading() override;
134 const HttpResponseInfo* GetResponseInfo() const override;
135 LoadState GetLoadState() const override;
136 UploadProgress GetUploadProgress(void) const override;
137 void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
138 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
139 void SetPriority(RequestPriority priority) override;
140 void SetWebSocketHandshakeStreamCreateHelper(
141 net::WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
142 void SetBeforeNetworkStartCallback(
143 const BeforeNetworkStartCallback& callback) override;
144 void SetBeforeProxyHeadersSentCallback(
145 const BeforeProxyHeadersSentCallback& callback) override;
146 int ResumeNetworkStart() override;
148 private:
149 static const size_t kNumValidationHeaders = 2;
150 // Helper struct to pair a header name with its value, for
151 // headers used to validate cache entries.
152 struct ValidationHeaders {
153 ValidationHeaders() : initialized(false) {}
155 std::string values[kNumValidationHeaders];
156 bool initialized;
159 enum State {
160 STATE_NONE,
161 STATE_GET_BACKEND,
162 STATE_GET_BACKEND_COMPLETE,
163 STATE_SEND_REQUEST,
164 STATE_SEND_REQUEST_COMPLETE,
165 STATE_SUCCESSFUL_SEND_REQUEST,
166 STATE_NETWORK_READ,
167 STATE_NETWORK_READ_COMPLETE,
168 STATE_INIT_ENTRY,
169 STATE_OPEN_ENTRY,
170 STATE_OPEN_ENTRY_COMPLETE,
171 STATE_CREATE_ENTRY,
172 STATE_CREATE_ENTRY_COMPLETE,
173 STATE_DOOM_ENTRY,
174 STATE_DOOM_ENTRY_COMPLETE,
175 STATE_ADD_TO_ENTRY,
176 STATE_ADD_TO_ENTRY_COMPLETE,
177 STATE_START_PARTIAL_CACHE_VALIDATION,
178 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
179 STATE_UPDATE_CACHED_RESPONSE,
180 STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
181 STATE_OVERWRITE_CACHED_RESPONSE,
182 STATE_TRUNCATE_CACHED_DATA,
183 STATE_TRUNCATE_CACHED_DATA_COMPLETE,
184 STATE_TRUNCATE_CACHED_METADATA,
185 STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
186 STATE_PARTIAL_HEADERS_RECEIVED,
187 STATE_CACHE_READ_RESPONSE,
188 STATE_CACHE_READ_RESPONSE_COMPLETE,
189 STATE_CACHE_DISPATCH_VALIDATION,
190 STATE_TOGGLE_UNUSED_SINCE_PREFETCH,
191 STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE,
192 STATE_CACHE_WRITE_RESPONSE,
193 STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
194 STATE_CACHE_WRITE_RESPONSE_COMPLETE,
195 STATE_CACHE_READ_METADATA,
196 STATE_CACHE_READ_METADATA_COMPLETE,
197 STATE_CACHE_QUERY_DATA,
198 STATE_CACHE_QUERY_DATA_COMPLETE,
199 STATE_CACHE_READ_DATA,
200 STATE_CACHE_READ_DATA_COMPLETE,
201 STATE_CACHE_WRITE_DATA,
202 STATE_CACHE_WRITE_DATA_COMPLETE
205 // Used for categorizing transactions for reporting in histograms. Patterns
206 // cover relatively common use cases being measured and considered for
207 // optimization. Many use cases that are more complex or uncommon are binned
208 // as PATTERN_NOT_COVERED, and details are not reported.
209 // NOTE: This enumeration is used in histograms, so please do not add entries
210 // in the middle.
211 enum TransactionPattern {
212 PATTERN_UNDEFINED,
213 PATTERN_NOT_COVERED,
214 PATTERN_ENTRY_NOT_CACHED,
215 PATTERN_ENTRY_USED,
216 PATTERN_ENTRY_VALIDATED,
217 PATTERN_ENTRY_UPDATED,
218 PATTERN_ENTRY_CANT_CONDITIONALIZE,
219 PATTERN_MAX,
222 // This is a helper function used to trigger a completion callback. It may
223 // only be called if callback_ is non-null.
224 void DoCallback(int rv);
226 // This will trigger the completion callback if appropriate.
227 int HandleResult(int rv);
229 // Runs the state transition loop.
230 int DoLoop(int result);
232 // Each of these methods corresponds to a State value. If there is an
233 // argument, the value corresponds to the return of the previous state or
234 // corresponding callback.
235 int DoGetBackend();
236 int DoGetBackendComplete(int result);
237 int DoSendRequest();
238 int DoSendRequestComplete(int result);
239 int DoSuccessfulSendRequest();
240 int DoNetworkRead();
241 int DoNetworkReadComplete(int result);
242 int DoInitEntry();
243 int DoOpenEntry();
244 int DoOpenEntryComplete(int result);
245 int DoCreateEntry();
246 int DoCreateEntryComplete(int result);
247 int DoDoomEntry();
248 int DoDoomEntryComplete(int result);
249 int DoAddToEntry();
250 int DoAddToEntryComplete(int result);
251 int DoStartPartialCacheValidation();
252 int DoCompletePartialCacheValidation(int result);
253 int DoUpdateCachedResponse();
254 int DoUpdateCachedResponseComplete(int result);
255 int DoOverwriteCachedResponse();
256 int DoTruncateCachedData();
257 int DoTruncateCachedDataComplete(int result);
258 int DoTruncateCachedMetadata();
259 int DoTruncateCachedMetadataComplete(int result);
260 int DoPartialHeadersReceived();
261 int DoCacheReadResponse();
262 int DoCacheReadResponseComplete(int result);
263 int DoCacheDispatchValidation();
264 int DoCacheToggleUnusedSincePrefetch();
265 int DoCacheToggleUnusedSincePrefetchComplete(int result);
266 int DoCacheWriteResponse();
267 int DoCacheWriteTruncatedResponse();
268 int DoCacheWriteResponseComplete(int result);
269 int DoCacheReadMetadata();
270 int DoCacheReadMetadataComplete(int result);
271 int DoCacheQueryData();
272 int DoCacheQueryDataComplete(int result);
273 int DoCacheReadData();
274 int DoCacheReadDataComplete(int result);
275 int DoCacheWriteData(int num_bytes);
276 int DoCacheWriteDataComplete(int result);
278 // These functions are involved in a field trial testing storing certificates
279 // in seperate entries from the HttpResponseInfo.
280 void ReadCertChain();
281 void WriteCertChain();
283 // Sets request_ and fields derived from it.
284 void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
286 // Returns true if the request should be handled exclusively by the network
287 // layer (skipping the cache entirely).
288 bool ShouldPassThrough();
290 // Called to begin reading from the cache. Returns network error code.
291 int BeginCacheRead();
293 // Called to begin validating the cache entry. Returns network error code.
294 int BeginCacheValidation();
296 // Called to begin validating an entry that stores partial content. Returns
297 // a network error code.
298 int BeginPartialCacheValidation();
300 // Validates the entry headers against the requested range and continues with
301 // the validation of the rest of the entry. Returns a network error code.
302 int ValidateEntryHeadersAndContinue();
304 // Called to start requests which were given an "if-modified-since" or
305 // "if-none-match" validation header by the caller (NOT when the request was
306 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
307 // Returns a network error code.
308 int BeginExternallyConditionalizedRequest();
310 // Called to restart a network transaction after an error. Returns network
311 // error code.
312 int RestartNetworkRequest();
314 // Called to restart a network transaction with a client certificate.
315 // Returns network error code.
316 int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
318 // Called to restart a network transaction with authentication credentials.
319 // Returns network error code.
320 int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
322 // Called to determine if we need to validate the cache entry before using it,
323 // and whether the validation should be synchronous or asynchronous.
324 ValidationType RequiresValidation();
326 // Called to make the request conditional (to ask the server if the cached
327 // copy is valid). Returns true if able to make the request conditional.
328 bool ConditionalizeRequest();
330 // Makes sure that a 206 response is expected. Returns true on success.
331 // On success, handling_206_ will be set to true if we are processing a
332 // partial entry.
333 bool ValidatePartialResponse();
335 // Handles a response validation error by bypassing the cache.
336 void IgnoreRangeRequest();
338 // Fixes the response headers to match expectations for a HEAD request.
339 void FixHeadersForHead();
341 // Launches an asynchronous revalidation based on this transaction.
342 void TriggerAsyncValidation();
344 // Changes the response code of a range request to be 416 (Requested range not
345 // satisfiable).
346 void FailRangeRequest();
348 // Setups the transaction for reading from the cache entry.
349 int SetupEntryForRead();
351 // Reads data from the network.
352 int ReadFromNetwork(IOBuffer* data, int data_len);
354 // Reads data from the cache entry.
355 int ReadFromEntry(IOBuffer* data, int data_len);
357 // Called to write data to the cache entry. If the write fails, then the
358 // cache entry is destroyed. Future calls to this function will just do
359 // nothing without side-effect. Returns a network error code.
360 int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
361 const CompletionCallback& callback);
363 // Called to write response_ to the cache entry. |truncated| indicates if the
364 // entry should be marked as incomplete.
365 int WriteResponseInfoToEntry(bool truncated);
367 // Called to append response data to the cache entry. Returns a network error
368 // code.
369 int AppendResponseDataToEntry(IOBuffer* data, int data_len,
370 const CompletionCallback& callback);
372 // Called when we are done writing to the cache entry.
373 void DoneWritingToEntry(bool success);
375 // Returns an error to signal the caller that the current read failed. The
376 // current operation |result| is also logged. If |restart| is true, the
377 // transaction should be restarted.
378 int OnCacheReadError(int result, bool restart);
380 // Called when the cache lock timeout fires.
381 void OnAddToEntryTimeout(base::TimeTicks start_time);
383 // Deletes the current partial cache entry (sparse), and optionally removes
384 // the control object (partial_).
385 void DoomPartialEntry(bool delete_object);
387 // Performs the needed work after receiving data from the network, when
388 // working with range requests.
389 int DoPartialNetworkReadCompleted(int result);
391 // Performs the needed work after receiving data from the cache, when
392 // working with range requests.
393 int DoPartialCacheReadCompleted(int result);
395 // Restarts this transaction after deleting the cached data. It is meant to
396 // be used when the current request cannot be fulfilled due to conflicts
397 // between the byte range request and the cached entry.
398 int DoRestartPartialRequest();
400 // Resets the relavant internal state to remove traces of internal processing
401 // related to range requests. Deletes |partial_| if |delete_object| is true.
402 void ResetPartialState(bool delete_object);
404 // Resets |network_trans_|, which must be non-NULL. Also updates
405 // |old_network_trans_load_timing_|, which must be NULL when this is called.
406 void ResetNetworkTransaction();
408 // Returns true if we should bother attempting to resume this request if it
409 // is aborted while in progress. If |has_data| is true, the size of the stored
410 // data is considered for the result.
411 bool CanResume(bool has_data);
413 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
414 void RecordHistograms();
416 // Called to signal completion of asynchronous IO.
417 void OnIOComplete(int result);
419 State next_state_;
420 const HttpRequestInfo* request_;
421 RequestPriority priority_;
422 BoundNetLog net_log_;
423 scoped_ptr<HttpRequestInfo> custom_request_;
424 HttpRequestHeaders request_headers_copy_;
425 // If extra_headers specified a "if-modified-since" or "if-none-match",
426 // |external_validation_| contains the value of those headers.
427 ValidationHeaders external_validation_;
428 base::WeakPtr<HttpCache> cache_;
429 HttpCache::ActiveEntry* entry_;
430 HttpCache::ActiveEntry* new_entry_;
431 scoped_ptr<HttpTransaction> network_trans_;
432 CompletionCallback callback_; // Consumer's callback.
433 HttpResponseInfo response_;
434 HttpResponseInfo auth_response_;
435 const HttpResponseInfo* new_response_;
436 std::string cache_key_;
437 Mode mode_;
438 State target_state_;
439 bool reading_; // We are already reading. Never reverts to false once set.
440 bool invalid_range_; // We may bypass the cache for this request.
441 bool truncated_; // We don't have all the response data.
442 bool is_sparse_; // The data is stored in sparse byte ranges.
443 bool range_requested_; // The user requested a byte range.
444 bool handling_206_; // We must deal with this 206 response.
445 bool cache_pending_; // We are waiting for the HttpCache.
446 bool done_reading_; // All available data was read.
447 bool vary_mismatch_; // The request doesn't match the stored vary data.
448 bool couldnt_conditionalize_request_;
449 bool bypass_lock_for_test_; // A test is exercising the cache lock.
450 bool fail_conditionalization_for_test_; // Fail ConditionalizeRequest.
451 scoped_refptr<IOBuffer> read_buf_;
452 int io_buf_len_;
453 int read_offset_;
454 int effective_load_flags_;
455 int write_len_;
456 scoped_ptr<PartialData> partial_; // We are dealing with range requests.
457 UploadProgress final_upload_progress_;
458 CompletionCallback io_callback_;
460 // Members used to track data for histograms.
461 TransactionPattern transaction_pattern_;
462 base::TimeTicks entry_lock_waiting_since_;
463 base::TimeTicks first_cache_access_since_;
464 base::TimeTicks send_request_since_;
466 int64 total_received_bytes_;
468 // Load timing information for the last network request, if any. Set in the
469 // 304 and 206 response cases, as the network transaction may be destroyed
470 // before the caller requests load timing information.
471 scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
473 // The helper object to use to create WebSocketHandshakeStreamBase
474 // objects. Only relevant when establishing a WebSocket connection.
475 // This is passed to the underlying network transaction. It is stored here in
476 // case the transaction does not exist yet.
477 WebSocketHandshakeStreamBase::CreateHelper*
478 websocket_handshake_stream_base_create_helper_;
480 BeforeNetworkStartCallback before_network_start_callback_;
481 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
483 base::WeakPtrFactory<Transaction> weak_factory_;
485 DISALLOW_COPY_AND_ASSIGN(Transaction);
488 } // namespace net
490 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_