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_
15 #include "base/basictypes.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/time/time.h"
20 #include "net/base/completion_callback.h"
21 #include "net/base/io_buffer.h"
22 #include "net/base/load_states.h"
23 #include "net/base/request_priority.h"
24 #include "net/base/upload_progress.h"
25 #include "net/http/http_cache.h"
26 #include "net/http/http_request_headers.h"
27 #include "net/http/http_response_headers.h"
28 #include "net/http/http_response_info.h"
29 #include "net/http/http_transaction.h"
30 #include "net/http/partial_data.h"
31 #include "net/log/net_log.h"
32 #include "net/socket/connection_attempts.h"
33 #include "net/websockets/websocket_handshake_stream_base.h"
38 struct HttpRequestInfo
;
39 struct LoadTimingInfo
;
41 // This is the transaction that is returned by the HttpCache transaction
43 class HttpCache::Transaction
: public HttpTransaction
{
45 // The transaction has the following modes, which apply to how it may access
48 // o If the mode of the transaction is NONE, then it is in "pass through"
49 // mode and all methods just forward to the inner network transaction.
51 // o If the mode of the transaction is only READ, then it may only read from
54 // o If the mode of the transaction is only WRITE, then it may only write to
57 // o If the mode of the transaction is READ_WRITE, then the transaction may
58 // optionally modify the cache entry (e.g., possibly corresponding to
61 // o If the mode of the transaction is UPDATE, then the transaction may
62 // update existing cache entries, but will never create a new entry or
63 // respond using the entry read from the cache.
68 READ
= READ_META
| READ_DATA
,
70 READ_WRITE
= READ
| WRITE
,
71 UPDATE
= READ_META
| WRITE
, // READ_WRITE & ~READ_DATA
74 Transaction(RequestPriority priority
,
76 ~Transaction() override
;
78 Mode
mode() const { return mode_
; }
80 const std::string
& key() const { return cache_key_
; }
82 // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
83 // HTTP cache entry that backs this transaction (if any).
84 // Returns the number of bytes actually written, or a net error code. If the
85 // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
86 // reference to the buffer (until completion), and notifies the caller using
87 // the provided |callback| when the operation finishes.
89 // The first time this method is called for a given transaction, previous
90 // meta-data will be overwritten with the provided data, and subsequent
91 // invocations will keep appending to the cached entry.
93 // In order to guarantee that the metadata is set to the correct entry, the
94 // response (or response info) must be evaluated by the caller, for instance
95 // to make sure that the response_time is as expected, before calling this
97 int WriteMetadata(IOBuffer
* buf
,
99 const CompletionCallback
& callback
);
101 // This transaction is being deleted and we are not done writing to the cache.
102 // We need to indicate that the response data was truncated. Returns true on
103 // success. Keep in mind that this operation may have side effects, such as
104 // deleting the active entry.
105 bool AddTruncatedFlag();
107 HttpCache::ActiveEntry
* entry() { return entry_
; }
109 // Returns the LoadState of the writer transaction of a given ActiveEntry. In
110 // other words, returns the LoadState of this transaction without asking the
111 // http cache, because this transaction should be the one currently writing
112 // to the cache entry.
113 LoadState
GetWriterLoadState() const;
115 const CompletionCallback
& io_callback() { return io_callback_
; }
117 const BoundNetLog
& net_log() const;
119 // Bypasses the cache lock whenever there is lock contention.
120 void BypassLockForTest() {
121 bypass_lock_for_test_
= true;
124 // Generates a failure when attempting to conditionalize a network request.
125 void FailConditionalizationForTest() {
126 fail_conditionalization_for_test_
= true;
129 // HttpTransaction methods:
130 int Start(const HttpRequestInfo
* request_info
,
131 const CompletionCallback
& callback
,
132 const BoundNetLog
& net_log
) override
;
133 int RestartIgnoringLastError(const CompletionCallback
& callback
) override
;
134 int RestartWithCertificate(X509Certificate
* client_cert
,
135 const CompletionCallback
& callback
) override
;
136 int RestartWithAuth(const AuthCredentials
& credentials
,
137 const CompletionCallback
& callback
) override
;
138 bool IsReadyToRestartForAuth() override
;
139 int Read(IOBuffer
* buf
,
141 const CompletionCallback
& callback
) override
;
142 void StopCaching() override
;
143 bool GetFullRequestHeaders(HttpRequestHeaders
* headers
) const override
;
144 int64
GetTotalReceivedBytes() const override
;
145 void DoneReading() override
;
146 const HttpResponseInfo
* GetResponseInfo() const override
;
147 LoadState
GetLoadState() const override
;
148 UploadProgress
GetUploadProgress(void) const override
;
149 void SetQuicServerInfo(QuicServerInfo
* quic_server_info
) override
;
150 bool GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const override
;
151 void SetPriority(RequestPriority priority
) override
;
152 void SetWebSocketHandshakeStreamCreateHelper(
153 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) override
;
154 void SetBeforeNetworkStartCallback(
155 const BeforeNetworkStartCallback
& callback
) override
;
156 void SetBeforeProxyHeadersSentCallback(
157 const BeforeProxyHeadersSentCallback
& callback
) override
;
158 int ResumeNetworkStart() override
;
159 void GetConnectionAttempts(ConnectionAttempts
* out
) const override
;
162 static const size_t kNumValidationHeaders
= 2;
163 // Helper struct to pair a header name with its value, for
164 // headers used to validate cache entries.
165 struct ValidationHeaders
{
166 ValidationHeaders() : initialized(false) {}
168 std::string values
[kNumValidationHeaders
];
175 STATE_GET_BACKEND_COMPLETE
,
177 STATE_SEND_REQUEST_COMPLETE
,
178 STATE_SUCCESSFUL_SEND_REQUEST
,
180 STATE_NETWORK_READ_COMPLETE
,
183 STATE_OPEN_ENTRY_COMPLETE
,
185 STATE_CREATE_ENTRY_COMPLETE
,
187 STATE_DOOM_ENTRY_COMPLETE
,
189 STATE_ADD_TO_ENTRY_COMPLETE
,
190 STATE_START_PARTIAL_CACHE_VALIDATION
,
191 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
,
192 STATE_UPDATE_CACHED_RESPONSE
,
193 STATE_UPDATE_CACHED_RESPONSE_COMPLETE
,
194 STATE_OVERWRITE_CACHED_RESPONSE
,
195 STATE_TRUNCATE_CACHED_DATA
,
196 STATE_TRUNCATE_CACHED_DATA_COMPLETE
,
197 STATE_TRUNCATE_CACHED_METADATA
,
198 STATE_TRUNCATE_CACHED_METADATA_COMPLETE
,
199 STATE_PARTIAL_HEADERS_RECEIVED
,
200 STATE_CACHE_READ_RESPONSE
,
201 STATE_CACHE_READ_RESPONSE_COMPLETE
,
202 STATE_CACHE_DISPATCH_VALIDATION
,
203 STATE_TOGGLE_UNUSED_SINCE_PREFETCH
,
204 STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE
,
205 STATE_CACHE_WRITE_RESPONSE
,
206 STATE_CACHE_WRITE_TRUNCATED_RESPONSE
,
207 STATE_CACHE_WRITE_RESPONSE_COMPLETE
,
208 STATE_CACHE_READ_METADATA
,
209 STATE_CACHE_READ_METADATA_COMPLETE
,
210 STATE_CACHE_QUERY_DATA
,
211 STATE_CACHE_QUERY_DATA_COMPLETE
,
212 STATE_CACHE_READ_DATA
,
213 STATE_CACHE_READ_DATA_COMPLETE
,
214 STATE_CACHE_WRITE_DATA
,
215 STATE_CACHE_WRITE_DATA_COMPLETE
218 // Used for categorizing transactions for reporting in histograms. Patterns
219 // cover relatively common use cases being measured and considered for
220 // optimization. Many use cases that are more complex or uncommon are binned
221 // as PATTERN_NOT_COVERED, and details are not reported.
222 // NOTE: This enumeration is used in histograms, so please do not add entries
224 enum TransactionPattern
{
227 PATTERN_ENTRY_NOT_CACHED
,
229 PATTERN_ENTRY_VALIDATED
,
230 PATTERN_ENTRY_UPDATED
,
231 PATTERN_ENTRY_CANT_CONDITIONALIZE
,
235 // This is a helper function used to trigger a completion callback. It may
236 // only be called if callback_ is non-null.
237 void DoCallback(int rv
);
239 // This will trigger the completion callback if appropriate.
240 int HandleResult(int rv
);
242 // Runs the state transition loop.
243 int DoLoop(int result
);
245 // Each of these methods corresponds to a State value. If there is an
246 // argument, the value corresponds to the return of the previous state or
247 // corresponding callback.
249 int DoGetBackendComplete(int result
);
251 int DoSendRequestComplete(int result
);
252 int DoSuccessfulSendRequest();
254 int DoNetworkReadComplete(int result
);
257 int DoOpenEntryComplete(int result
);
259 int DoCreateEntryComplete(int result
);
261 int DoDoomEntryComplete(int result
);
263 int DoAddToEntryComplete(int result
);
264 int DoStartPartialCacheValidation();
265 int DoCompletePartialCacheValidation(int result
);
266 int DoUpdateCachedResponse();
267 int DoUpdateCachedResponseComplete(int result
);
268 int DoOverwriteCachedResponse();
269 int DoTruncateCachedData();
270 int DoTruncateCachedDataComplete(int result
);
271 int DoTruncateCachedMetadata();
272 int DoTruncateCachedMetadataComplete(int result
);
273 int DoPartialHeadersReceived();
274 int DoCacheReadResponse();
275 int DoCacheReadResponseComplete(int result
);
276 int DoCacheDispatchValidation();
277 int DoCacheToggleUnusedSincePrefetch();
278 int DoCacheToggleUnusedSincePrefetchComplete(int result
);
279 int DoCacheWriteResponse();
280 int DoCacheWriteTruncatedResponse();
281 int DoCacheWriteResponseComplete(int result
);
282 int DoCacheReadMetadata();
283 int DoCacheReadMetadataComplete(int result
);
284 int DoCacheQueryData();
285 int DoCacheQueryDataComplete(int result
);
286 int DoCacheReadData();
287 int DoCacheReadDataComplete(int result
);
288 int DoCacheWriteData(int num_bytes
);
289 int DoCacheWriteDataComplete(int result
);
291 // These functions are involved in a field trial testing storing certificates
292 // in seperate entries from the HttpResponseInfo.
293 void ReadCertChain();
294 void WriteCertChain();
296 // Sets request_ and fields derived from it.
297 void SetRequest(const BoundNetLog
& net_log
, const HttpRequestInfo
* request
);
299 // Returns true if the request should be handled exclusively by the network
300 // layer (skipping the cache entirely).
301 bool ShouldPassThrough();
303 // Called to begin reading from the cache. Returns network error code.
304 int BeginCacheRead();
306 // Called to begin validating the cache entry. Returns network error code.
307 int BeginCacheValidation();
309 // Called to begin validating an entry that stores partial content. Returns
310 // a network error code.
311 int BeginPartialCacheValidation();
313 // Validates the entry headers against the requested range and continues with
314 // the validation of the rest of the entry. Returns a network error code.
315 int ValidateEntryHeadersAndContinue();
317 // Called to start requests which were given an "if-modified-since" or
318 // "if-none-match" validation header by the caller (NOT when the request was
319 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
320 // Returns a network error code.
321 int BeginExternallyConditionalizedRequest();
323 // Called to restart a network transaction after an error. Returns network
325 int RestartNetworkRequest();
327 // Called to restart a network transaction with a client certificate.
328 // Returns network error code.
329 int RestartNetworkRequestWithCertificate(X509Certificate
* client_cert
);
331 // Called to restart a network transaction with authentication credentials.
332 // Returns network error code.
333 int RestartNetworkRequestWithAuth(const AuthCredentials
& credentials
);
335 // Called to determine if we need to validate the cache entry before using it,
336 // and whether the validation should be synchronous or asynchronous.
337 ValidationType
RequiresValidation();
339 // Called to make the request conditional (to ask the server if the cached
340 // copy is valid). Returns true if able to make the request conditional.
341 bool ConditionalizeRequest();
343 // Makes sure that a 206 response is expected. Returns true on success.
344 // On success, handling_206_ will be set to true if we are processing a
346 bool ValidatePartialResponse();
348 // Handles a response validation error by bypassing the cache.
349 void IgnoreRangeRequest();
351 // Fixes the response headers to match expectations for a HEAD request.
352 void FixHeadersForHead();
354 // Changes the response code of a range request to be 416 (Requested range not
356 void FailRangeRequest();
358 // Setups the transaction for reading from the cache entry.
359 int SetupEntryForRead();
361 // Reads data from the network.
362 int ReadFromNetwork(IOBuffer
* data
, int data_len
);
364 // Reads data from the cache entry.
365 int ReadFromEntry(IOBuffer
* data
, int data_len
);
367 // Called to write data to the cache entry. If the write fails, then the
368 // cache entry is destroyed. Future calls to this function will just do
369 // nothing without side-effect. Returns a network error code.
370 int WriteToEntry(int index
, int offset
, IOBuffer
* data
, int data_len
,
371 const CompletionCallback
& callback
);
373 // Called to write response_ to the cache entry. |truncated| indicates if the
374 // entry should be marked as incomplete.
375 int WriteResponseInfoToEntry(bool truncated
);
377 // Called to append response data to the cache entry. Returns a network error
379 int AppendResponseDataToEntry(IOBuffer
* data
, int data_len
,
380 const CompletionCallback
& callback
);
382 // Called when we are done writing to the cache entry.
383 void DoneWritingToEntry(bool success
);
385 // Returns an error to signal the caller that the current read failed. The
386 // current operation |result| is also logged. If |restart| is true, the
387 // transaction should be restarted.
388 int OnCacheReadError(int result
, bool restart
);
390 // Called when the cache lock timeout fires.
391 void OnAddToEntryTimeout(base::TimeTicks start_time
);
393 // Deletes the current partial cache entry (sparse), and optionally removes
394 // the control object (partial_).
395 void DoomPartialEntry(bool delete_object
);
397 // Performs the needed work after receiving data from the network, when
398 // working with range requests.
399 int DoPartialNetworkReadCompleted(int result
);
401 // Performs the needed work after receiving data from the cache, when
402 // working with range requests.
403 int DoPartialCacheReadCompleted(int result
);
405 // Restarts this transaction after deleting the cached data. It is meant to
406 // be used when the current request cannot be fulfilled due to conflicts
407 // between the byte range request and the cached entry.
408 int DoRestartPartialRequest();
410 // Resets the relavant internal state to remove traces of internal processing
411 // related to range requests. Deletes |partial_| if |delete_object| is true.
412 void ResetPartialState(bool delete_object
);
414 // Resets |network_trans_|, which must be non-NULL. Also updates
415 // |old_network_trans_load_timing_|, which must be NULL when this is called.
416 void ResetNetworkTransaction();
418 // Returns true if we should bother attempting to resume this request if it
419 // is aborted while in progress. If |has_data| is true, the size of the stored
420 // data is considered for the result.
421 bool CanResume(bool has_data
);
423 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern
);
424 void RecordHistograms();
426 // Called to signal completion of asynchronous IO.
427 void OnIOComplete(int result
);
430 const HttpRequestInfo
* request_
;
431 RequestPriority priority_
;
432 BoundNetLog net_log_
;
433 scoped_ptr
<HttpRequestInfo
> custom_request_
;
434 HttpRequestHeaders request_headers_copy_
;
435 // If extra_headers specified a "if-modified-since" or "if-none-match",
436 // |external_validation_| contains the value of those headers.
437 ValidationHeaders external_validation_
;
438 base::WeakPtr
<HttpCache
> cache_
;
439 HttpCache::ActiveEntry
* entry_
;
440 HttpCache::ActiveEntry
* new_entry_
;
441 scoped_ptr
<HttpTransaction
> network_trans_
;
442 CompletionCallback callback_
; // Consumer's callback.
443 HttpResponseInfo response_
;
444 HttpResponseInfo auth_response_
;
445 const HttpResponseInfo
* new_response_
;
446 std::string cache_key_
;
449 bool reading_
; // We are already reading. Never reverts to false once set.
450 bool invalid_range_
; // We may bypass the cache for this request.
451 bool truncated_
; // We don't have all the response data.
452 bool is_sparse_
; // The data is stored in sparse byte ranges.
453 bool range_requested_
; // The user requested a byte range.
454 bool handling_206_
; // We must deal with this 206 response.
455 bool cache_pending_
; // We are waiting for the HttpCache.
456 bool done_reading_
; // All available data was read.
457 bool vary_mismatch_
; // The request doesn't match the stored vary data.
458 bool couldnt_conditionalize_request_
;
459 bool bypass_lock_for_test_
; // A test is exercising the cache lock.
460 bool fail_conditionalization_for_test_
; // Fail ConditionalizeRequest.
461 scoped_refptr
<IOBuffer
> read_buf_
;
464 int effective_load_flags_
;
466 scoped_ptr
<PartialData
> partial_
; // We are dealing with range requests.
467 UploadProgress final_upload_progress_
;
468 CompletionCallback io_callback_
;
470 // Members used to track data for histograms.
471 TransactionPattern transaction_pattern_
;
472 base::TimeTicks entry_lock_waiting_since_
;
473 base::TimeTicks first_cache_access_since_
;
474 base::TimeTicks send_request_since_
;
476 int64 total_received_bytes_
;
478 // Load timing information for the last network request, if any. Set in the
479 // 304 and 206 response cases, as the network transaction may be destroyed
480 // before the caller requests load timing information.
481 scoped_ptr
<LoadTimingInfo
> old_network_trans_load_timing_
;
483 ConnectionAttempts old_connection_attempts_
;
485 // The helper object to use to create WebSocketHandshakeStreamBase
486 // objects. Only relevant when establishing a WebSocket connection.
487 // This is passed to the underlying network transaction. It is stored here in
488 // case the transaction does not exist yet.
489 WebSocketHandshakeStreamBase::CreateHelper
*
490 websocket_handshake_stream_base_create_helper_
;
492 BeforeNetworkStartCallback before_network_start_callback_
;
493 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_
;
495 base::WeakPtrFactory
<Transaction
> weak_factory_
;
497 DISALLOW_COPY_AND_ASSIGN(Transaction
);
502 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_