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