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_
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"
26 struct HttpRequestInfo
;
27 struct LoadTimingInfo
;
29 // This is the transaction that is returned by the HttpCache transaction
31 class HttpCache::Transaction
: public HttpTransaction
{
33 // The transaction has the following modes, which apply to how it may access
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
42 // o If the mode of the transaction is only WRITE, then it may only write to
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
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.
56 READ
= READ_META
| READ_DATA
,
58 READ_WRITE
= READ
| WRITE
,
59 UPDATE
= READ_META
| WRITE
, // READ_WRITE & ~READ_DATA
62 Transaction(RequestPriority priority
,
64 virtual ~Transaction();
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
85 int WriteMetadata(IOBuffer
* buf
,
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 virtual int Start(const HttpRequestInfo
* request_info
,
114 const CompletionCallback
& callback
,
115 const BoundNetLog
& net_log
) override
;
116 virtual int RestartIgnoringLastError(
117 const CompletionCallback
& callback
) override
;
118 virtual int RestartWithCertificate(
119 X509Certificate
* client_cert
,
120 const CompletionCallback
& callback
) override
;
121 virtual int RestartWithAuth(const AuthCredentials
& credentials
,
122 const CompletionCallback
& callback
) override
;
123 virtual bool IsReadyToRestartForAuth() override
;
124 virtual int Read(IOBuffer
* buf
,
126 const CompletionCallback
& callback
) override
;
127 virtual void StopCaching() override
;
128 virtual bool GetFullRequestHeaders(
129 HttpRequestHeaders
* headers
) const override
;
130 virtual int64
GetTotalReceivedBytes() const override
;
131 virtual void DoneReading() override
;
132 virtual const HttpResponseInfo
* GetResponseInfo() const override
;
133 virtual LoadState
GetLoadState() const override
;
134 virtual UploadProgress
GetUploadProgress(void) const override
;
135 virtual void SetQuicServerInfo(QuicServerInfo
* quic_server_info
) override
;
136 virtual bool GetLoadTimingInfo(
137 LoadTimingInfo
* load_timing_info
) const override
;
138 virtual void SetPriority(RequestPriority priority
) override
;
139 virtual void SetWebSocketHandshakeStreamCreateHelper(
140 net::WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) override
;
141 virtual void SetBeforeNetworkStartCallback(
142 const BeforeNetworkStartCallback
& callback
) override
;
143 virtual void SetBeforeProxyHeadersSentCallback(
144 const BeforeProxyHeadersSentCallback
& callback
) override
;
145 virtual int ResumeNetworkStart() override
;
148 static const size_t kNumValidationHeaders
= 2;
149 // Helper struct to pair a header name with its value, for
150 // headers used to validate cache entries.
151 struct ValidationHeaders
{
152 ValidationHeaders() : initialized(false) {}
154 std::string values
[kNumValidationHeaders
];
161 STATE_GET_BACKEND_COMPLETE
,
163 STATE_SEND_REQUEST_COMPLETE
,
164 STATE_SUCCESSFUL_SEND_REQUEST
,
166 STATE_NETWORK_READ_COMPLETE
,
169 STATE_OPEN_ENTRY_COMPLETE
,
171 STATE_CREATE_ENTRY_COMPLETE
,
173 STATE_DOOM_ENTRY_COMPLETE
,
175 STATE_ADD_TO_ENTRY_COMPLETE
,
176 STATE_START_PARTIAL_CACHE_VALIDATION
,
177 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
,
178 STATE_UPDATE_CACHED_RESPONSE
,
179 STATE_UPDATE_CACHED_RESPONSE_COMPLETE
,
180 STATE_OVERWRITE_CACHED_RESPONSE
,
181 STATE_TRUNCATE_CACHED_DATA
,
182 STATE_TRUNCATE_CACHED_DATA_COMPLETE
,
183 STATE_TRUNCATE_CACHED_METADATA
,
184 STATE_TRUNCATE_CACHED_METADATA_COMPLETE
,
185 STATE_PARTIAL_HEADERS_RECEIVED
,
186 STATE_CACHE_READ_RESPONSE
,
187 STATE_CACHE_READ_RESPONSE_COMPLETE
,
188 STATE_CACHE_WRITE_RESPONSE
,
189 STATE_CACHE_WRITE_TRUNCATED_RESPONSE
,
190 STATE_CACHE_WRITE_RESPONSE_COMPLETE
,
191 STATE_CACHE_READ_METADATA
,
192 STATE_CACHE_READ_METADATA_COMPLETE
,
193 STATE_CACHE_QUERY_DATA
,
194 STATE_CACHE_QUERY_DATA_COMPLETE
,
195 STATE_CACHE_READ_DATA
,
196 STATE_CACHE_READ_DATA_COMPLETE
,
197 STATE_CACHE_WRITE_DATA
,
198 STATE_CACHE_WRITE_DATA_COMPLETE
201 // Used for categorizing transactions for reporting in histograms. Patterns
202 // cover relatively common use cases being measured and considered for
203 // optimization. Many use cases that are more complex or uncommon are binned
204 // as PATTERN_NOT_COVERED, and details are not reported.
205 // NOTE: This enumeration is used in histograms, so please do not add entries
207 enum TransactionPattern
{
210 PATTERN_ENTRY_NOT_CACHED
,
212 PATTERN_ENTRY_VALIDATED
,
213 PATTERN_ENTRY_UPDATED
,
214 PATTERN_ENTRY_CANT_CONDITIONALIZE
,
218 // This is a helper function used to trigger a completion callback. It may
219 // only be called if callback_ is non-null.
220 void DoCallback(int rv
);
222 // This will trigger the completion callback if appropriate.
223 int HandleResult(int rv
);
225 // Runs the state transition loop.
226 int DoLoop(int result
);
228 // Each of these methods corresponds to a State value. If there is an
229 // argument, the value corresponds to the return of the previous state or
230 // corresponding callback.
232 int DoGetBackendComplete(int result
);
234 int DoSendRequestComplete(int result
);
235 int DoSuccessfulSendRequest();
237 int DoNetworkReadComplete(int result
);
240 int DoOpenEntryComplete(int result
);
242 int DoCreateEntryComplete(int result
);
244 int DoDoomEntryComplete(int result
);
246 int DoAddToEntryComplete(int result
);
247 int DoStartPartialCacheValidation();
248 int DoCompletePartialCacheValidation(int result
);
249 int DoUpdateCachedResponse();
250 int DoUpdateCachedResponseComplete(int result
);
251 int DoOverwriteCachedResponse();
252 int DoTruncateCachedData();
253 int DoTruncateCachedDataComplete(int result
);
254 int DoTruncateCachedMetadata();
255 int DoTruncateCachedMetadataComplete(int result
);
256 int DoPartialHeadersReceived();
257 int DoCacheReadResponse();
258 int DoCacheReadResponseComplete(int result
);
259 int DoCacheWriteResponse();
260 int DoCacheWriteTruncatedResponse();
261 int DoCacheWriteResponseComplete(int result
);
262 int DoCacheReadMetadata();
263 int DoCacheReadMetadataComplete(int result
);
264 int DoCacheQueryData();
265 int DoCacheQueryDataComplete(int result
);
266 int DoCacheReadData();
267 int DoCacheReadDataComplete(int result
);
268 int DoCacheWriteData(int num_bytes
);
269 int DoCacheWriteDataComplete(int result
);
271 // These functions are involved in a field trial testing storing certificates
272 // in seperate entries from the HttpResponseInfo.
273 void ReadCertChain();
274 void WriteCertChain();
276 // Sets request_ and fields derived from it.
277 void SetRequest(const BoundNetLog
& net_log
, const HttpRequestInfo
* request
);
279 // Returns true if the request should be handled exclusively by the network
280 // layer (skipping the cache entirely).
281 bool ShouldPassThrough();
283 // Called to begin reading from the cache. Returns network error code.
284 int BeginCacheRead();
286 // Called to begin validating the cache entry. Returns network error code.
287 int BeginCacheValidation();
289 // Called to begin validating an entry that stores partial content. Returns
290 // a network error code.
291 int BeginPartialCacheValidation();
293 // Validates the entry headers against the requested range and continues with
294 // the validation of the rest of the entry. Returns a network error code.
295 int ValidateEntryHeadersAndContinue();
297 // Called to start requests which were given an "if-modified-since" or
298 // "if-none-match" validation header by the caller (NOT when the request was
299 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
300 // Returns a network error code.
301 int BeginExternallyConditionalizedRequest();
303 // Called to restart a network transaction after an error. Returns network
305 int RestartNetworkRequest();
307 // Called to restart a network transaction with a client certificate.
308 // Returns network error code.
309 int RestartNetworkRequestWithCertificate(X509Certificate
* client_cert
);
311 // Called to restart a network transaction with authentication credentials.
312 // Returns network error code.
313 int RestartNetworkRequestWithAuth(const AuthCredentials
& credentials
);
315 // Called to determine if we need to validate the cache entry before using it,
316 // and whether the validation should be synchronous or asynchronous.
317 ValidationType
RequiresValidation();
319 // Called to make the request conditional (to ask the server if the cached
320 // copy is valid). Returns true if able to make the request conditional.
321 bool ConditionalizeRequest();
323 // Makes sure that a 206 response is expected. Returns true on success.
324 // On success, handling_206_ will be set to true if we are processing a
326 bool ValidatePartialResponse();
328 // Handles a response validation error by bypassing the cache.
329 void IgnoreRangeRequest();
331 // Removes content-length and byte range related info if needed.
332 void FixHeadersForHead();
334 // Launches an asynchronous revalidation based on this transaction.
335 void TriggerAsyncValidation();
337 // Changes the response code of a range request to be 416 (Requested range not
339 void FailRangeRequest();
341 // Setups the transaction for reading from the cache entry.
342 int SetupEntryForRead();
344 // Reads data from the network.
345 int ReadFromNetwork(IOBuffer
* data
, int data_len
);
347 // Reads data from the cache entry.
348 int ReadFromEntry(IOBuffer
* data
, int data_len
);
350 // Called to write data to the cache entry. If the write fails, then the
351 // cache entry is destroyed. Future calls to this function will just do
352 // nothing without side-effect. Returns a network error code.
353 int WriteToEntry(int index
, int offset
, IOBuffer
* data
, int data_len
,
354 const CompletionCallback
& callback
);
356 // Called to write response_ to the cache entry. |truncated| indicates if the
357 // entry should be marked as incomplete.
358 int WriteResponseInfoToEntry(bool truncated
);
360 // Called to append response data to the cache entry. Returns a network error
362 int AppendResponseDataToEntry(IOBuffer
* data
, int data_len
,
363 const CompletionCallback
& callback
);
365 // Called when we are done writing to the cache entry.
366 void DoneWritingToEntry(bool success
);
368 // Returns an error to signal the caller that the current read failed. The
369 // current operation |result| is also logged. If |restart| is true, the
370 // transaction should be restarted.
371 int OnCacheReadError(int result
, bool restart
);
373 // Called when the cache lock timeout fires.
374 void OnAddToEntryTimeout(base::TimeTicks start_time
);
376 // Deletes the current partial cache entry (sparse), and optionally removes
377 // the control object (partial_).
378 void DoomPartialEntry(bool delete_object
);
380 // Performs the needed work after receiving data from the network, when
381 // working with range requests.
382 int DoPartialNetworkReadCompleted(int result
);
384 // Performs the needed work after receiving data from the cache, when
385 // working with range requests.
386 int DoPartialCacheReadCompleted(int result
);
388 // Restarts this transaction after deleting the cached data. It is meant to
389 // be used when the current request cannot be fulfilled due to conflicts
390 // between the byte range request and the cached entry.
391 int DoRestartPartialRequest();
393 // Resets |network_trans_|, which must be non-NULL. Also updates
394 // |old_network_trans_load_timing_|, which must be NULL when this is called.
395 void ResetNetworkTransaction();
397 // Returns true if we should bother attempting to resume this request if it
398 // is aborted while in progress. If |has_data| is true, the size of the stored
399 // data is considered for the result.
400 bool CanResume(bool has_data
);
402 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern
);
403 void RecordHistograms();
405 // Called to signal completion of asynchronous IO.
406 void OnIOComplete(int result
);
409 const HttpRequestInfo
* request_
;
410 RequestPriority priority_
;
411 BoundNetLog net_log_
;
412 scoped_ptr
<HttpRequestInfo
> custom_request_
;
413 HttpRequestHeaders request_headers_copy_
;
414 // If extra_headers specified a "if-modified-since" or "if-none-match",
415 // |external_validation_| contains the value of those headers.
416 ValidationHeaders external_validation_
;
417 base::WeakPtr
<HttpCache
> cache_
;
418 HttpCache::ActiveEntry
* entry_
;
419 HttpCache::ActiveEntry
* new_entry_
;
420 scoped_ptr
<HttpTransaction
> network_trans_
;
421 CompletionCallback callback_
; // Consumer's callback.
422 HttpResponseInfo response_
;
423 HttpResponseInfo auth_response_
;
424 const HttpResponseInfo
* new_response_
;
425 std::string cache_key_
;
428 bool reading_
; // We are already reading. Never reverts to false once set.
429 bool invalid_range_
; // We may bypass the cache for this request.
430 bool truncated_
; // We don't have all the response data.
431 bool is_sparse_
; // The data is stored in sparse byte ranges.
432 bool range_requested_
; // The user requested a byte range.
433 bool handling_206_
; // We must deal with this 206 response.
434 bool cache_pending_
; // We are waiting for the HttpCache.
435 bool done_reading_
; // All available data was read.
436 bool vary_mismatch_
; // The request doesn't match the stored vary data.
437 bool couldnt_conditionalize_request_
;
438 bool bypass_lock_for_test_
; // A test is exercising the cache lock.
439 scoped_refptr
<IOBuffer
> read_buf_
;
442 int effective_load_flags_
;
444 scoped_ptr
<PartialData
> partial_
; // We are dealing with range requests.
445 UploadProgress final_upload_progress_
;
446 CompletionCallback io_callback_
;
448 // Members used to track data for histograms.
449 TransactionPattern transaction_pattern_
;
450 base::TimeTicks entry_lock_waiting_since_
;
451 base::TimeTicks first_cache_access_since_
;
452 base::TimeTicks send_request_since_
;
454 int64 total_received_bytes_
;
456 // Load timing information for the last network request, if any. Set in the
457 // 304 and 206 response cases, as the network transaction may be destroyed
458 // before the caller requests load timing information.
459 scoped_ptr
<LoadTimingInfo
> old_network_trans_load_timing_
;
461 // The helper object to use to create WebSocketHandshakeStreamBase
462 // objects. Only relevant when establishing a WebSocket connection.
463 // This is passed to the underlying network transaction. It is stored here in
464 // case the transaction does not exist yet.
465 WebSocketHandshakeStreamBase::CreateHelper
*
466 websocket_handshake_stream_base_create_helper_
;
468 BeforeNetworkStartCallback before_network_start_callback_
;
469 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_
;
471 base::WeakPtrFactory
<Transaction
> weak_factory_
;
473 DISALLOW_COPY_AND_ASSIGN(Transaction
);
478 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_