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_info.h"
20 #include "net/http/http_transaction.h"
25 struct HttpRequestInfo
;
26 class HttpTransactionDelegate
;
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 HttpTransactionDelegate
* transaction_delegate
);
65 virtual ~Transaction();
67 Mode
mode() const { return mode_
; }
69 const std::string
& key() const { return cache_key_
; }
71 // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
72 // HTTP cache entry that backs this transaction (if any).
73 // Returns the number of bytes actually written, or a net error code. If the
74 // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
75 // reference to the buffer (until completion), and notifies the caller using
76 // the provided |callback| when the operation finishes.
78 // The first time this method is called for a given transaction, previous
79 // meta-data will be overwritten with the provided data, and subsequent
80 // invocations will keep appending to the cached entry.
82 // In order to guarantee that the metadata is set to the correct entry, the
83 // response (or response info) must be evaluated by the caller, for instance
84 // to make sure that the response_time is as expected, before calling this
86 int WriteMetadata(IOBuffer
* buf
,
88 const CompletionCallback
& callback
);
90 // This transaction is being deleted and we are not done writing to the cache.
91 // We need to indicate that the response data was truncated. Returns true on
92 // success. Keep in mind that this operation may have side effects, such as
93 // deleting the active entry.
94 bool AddTruncatedFlag();
96 HttpCache::ActiveEntry
* entry() { return entry_
; }
98 // Returns the LoadState of the writer transaction of a given ActiveEntry. In
99 // other words, returns the LoadState of this transaction without asking the
100 // http cache, because this transaction should be the one currently writing
101 // to the cache entry.
102 LoadState
GetWriterLoadState() const;
104 const CompletionCallback
& io_callback() { return io_callback_
; }
106 const BoundNetLog
& net_log() const;
108 // HttpTransaction methods:
109 virtual int Start(const HttpRequestInfo
* request_info
,
110 const CompletionCallback
& callback
,
111 const BoundNetLog
& net_log
) OVERRIDE
;
112 virtual int RestartIgnoringLastError(
113 const CompletionCallback
& callback
) OVERRIDE
;
114 virtual int RestartWithCertificate(
115 X509Certificate
* client_cert
,
116 const CompletionCallback
& callback
) OVERRIDE
;
117 virtual int RestartWithAuth(const AuthCredentials
& credentials
,
118 const CompletionCallback
& callback
) OVERRIDE
;
119 virtual bool IsReadyToRestartForAuth() OVERRIDE
;
120 virtual int Read(IOBuffer
* buf
,
122 const CompletionCallback
& callback
) OVERRIDE
;
123 virtual void StopCaching() OVERRIDE
;
124 virtual bool GetFullRequestHeaders(
125 HttpRequestHeaders
* headers
) const OVERRIDE
;
126 virtual void DoneReading() OVERRIDE
;
127 virtual const HttpResponseInfo
* GetResponseInfo() const OVERRIDE
;
128 virtual LoadState
GetLoadState() const OVERRIDE
;
129 virtual UploadProgress
GetUploadProgress(void) const OVERRIDE
;
130 virtual bool GetLoadTimingInfo(
131 LoadTimingInfo
* load_timing_info
) const OVERRIDE
;
132 virtual void SetPriority(RequestPriority priority
) OVERRIDE
;
135 static const size_t kNumValidationHeaders
= 2;
136 // Helper struct to pair a header name with its value, for
137 // headers used to validate cache entries.
138 struct ValidationHeaders
{
139 ValidationHeaders() : initialized(false) {}
141 std::string values
[kNumValidationHeaders
];
148 STATE_GET_BACKEND_COMPLETE
,
150 STATE_SEND_REQUEST_COMPLETE
,
151 STATE_SUCCESSFUL_SEND_REQUEST
,
153 STATE_NETWORK_READ_COMPLETE
,
156 STATE_OPEN_ENTRY_COMPLETE
,
158 STATE_CREATE_ENTRY_COMPLETE
,
160 STATE_DOOM_ENTRY_COMPLETE
,
162 STATE_ADD_TO_ENTRY_COMPLETE
,
163 STATE_ADD_TO_ENTRY_COMPLETE_AFTER_DELAY
,
164 STATE_START_PARTIAL_CACHE_VALIDATION
,
165 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
,
166 STATE_UPDATE_CACHED_RESPONSE
,
167 STATE_UPDATE_CACHED_RESPONSE_COMPLETE
,
168 STATE_OVERWRITE_CACHED_RESPONSE
,
169 STATE_TRUNCATE_CACHED_DATA
,
170 STATE_TRUNCATE_CACHED_DATA_COMPLETE
,
171 STATE_TRUNCATE_CACHED_METADATA
,
172 STATE_TRUNCATE_CACHED_METADATA_COMPLETE
,
173 STATE_PARTIAL_HEADERS_RECEIVED
,
174 STATE_CACHE_READ_RESPONSE
,
175 STATE_CACHE_READ_RESPONSE_COMPLETE
,
176 STATE_CACHE_WRITE_RESPONSE
,
177 STATE_CACHE_WRITE_TRUNCATED_RESPONSE
,
178 STATE_CACHE_WRITE_RESPONSE_COMPLETE
,
179 STATE_CACHE_READ_METADATA
,
180 STATE_CACHE_READ_METADATA_COMPLETE
,
181 STATE_CACHE_QUERY_DATA
,
182 STATE_CACHE_QUERY_DATA_COMPLETE
,
183 STATE_CACHE_READ_DATA
,
184 STATE_CACHE_READ_DATA_COMPLETE
,
185 STATE_CACHE_WRITE_DATA
,
186 STATE_CACHE_WRITE_DATA_COMPLETE
189 // Used for categorizing transactions for reporting in histograms. Patterns
190 // cover relatively common use cases being measured and considered for
191 // optimization. Many use cases that are more complex or uncommon are binned
192 // as PATTERN_NOT_COVERED, and details are not reported.
193 // NOTE: This enumeration is used in histograms, so please do not add entries
195 enum TransactionPattern
{
198 PATTERN_ENTRY_NOT_CACHED
,
200 PATTERN_ENTRY_VALIDATED
,
201 PATTERN_ENTRY_UPDATED
,
202 PATTERN_ENTRY_CANT_CONDITIONALIZE
,
206 // This is a helper function used to trigger a completion callback. It may
207 // only be called if callback_ is non-null.
208 void DoCallback(int rv
);
210 // This will trigger the completion callback if appropriate.
211 int HandleResult(int rv
);
213 // Runs the state transition loop.
214 int DoLoop(int result
);
216 // Each of these methods corresponds to a State value. If there is an
217 // argument, the value corresponds to the return of the previous state or
218 // corresponding callback.
220 int DoGetBackendComplete(int result
);
222 int DoSendRequestComplete(int result
);
223 int DoSuccessfulSendRequest();
225 int DoNetworkReadComplete(int result
);
228 int DoOpenEntryComplete(int result
);
230 int DoCreateEntryComplete(int result
);
232 int DoDoomEntryComplete(int result
);
234 int DoAddToEntryComplete(int result
);
235 int DoAddToEntryCompleteAfterDelay(int result
);
236 int DoStartPartialCacheValidation();
237 int DoCompletePartialCacheValidation(int result
);
238 int DoUpdateCachedResponse();
239 int DoUpdateCachedResponseComplete(int result
);
240 int DoOverwriteCachedResponse();
241 int DoTruncateCachedData();
242 int DoTruncateCachedDataComplete(int result
);
243 int DoTruncateCachedMetadata();
244 int DoTruncateCachedMetadataComplete(int result
);
245 int DoPartialHeadersReceived();
246 int DoCacheReadResponse();
247 int DoCacheReadResponseComplete(int result
);
248 int DoCacheWriteResponse();
249 int DoCacheWriteTruncatedResponse();
250 int DoCacheWriteResponseComplete(int result
);
251 int DoCacheReadMetadata();
252 int DoCacheReadMetadataComplete(int result
);
253 int DoCacheQueryData();
254 int DoCacheQueryDataComplete(int result
);
255 int DoCacheReadData();
256 int DoCacheReadDataComplete(int result
);
257 int DoCacheWriteData(int num_bytes
);
258 int DoCacheWriteDataComplete(int result
);
260 // Sets request_ and fields derived from it.
261 void SetRequest(const BoundNetLog
& net_log
, const HttpRequestInfo
* request
);
263 // Returns true if the request should be handled exclusively by the network
264 // layer (skipping the cache entirely).
265 bool ShouldPassThrough();
267 // Called to begin reading from the cache. Returns network error code.
268 int BeginCacheRead();
270 // Called to begin validating the cache entry. Returns network error code.
271 int BeginCacheValidation();
273 // Called to begin validating an entry that stores partial content. Returns
274 // a network error code.
275 int BeginPartialCacheValidation();
277 // Validates the entry headers against the requested range and continues with
278 // the validation of the rest of the entry. Returns a network error code.
279 int ValidateEntryHeadersAndContinue();
281 // Called to start requests which were given an "if-modified-since" or
282 // "if-none-match" validation header by the caller (NOT when the request was
283 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
284 // Returns a network error code.
285 int BeginExternallyConditionalizedRequest();
287 // Called to restart a network transaction after an error. Returns network
289 int RestartNetworkRequest();
291 // Called to restart a network transaction with a client certificate.
292 // Returns network error code.
293 int RestartNetworkRequestWithCertificate(X509Certificate
* client_cert
);
295 // Called to restart a network transaction with authentication credentials.
296 // Returns network error code.
297 int RestartNetworkRequestWithAuth(const AuthCredentials
& credentials
);
299 // Called to determine if we need to validate the cache entry before using it.
300 bool RequiresValidation();
302 // Called to make the request conditional (to ask the server if the cached
303 // copy is valid). Returns true if able to make the request conditional.
304 bool ConditionalizeRequest();
306 // Makes sure that a 206 response is expected. Returns true on success.
307 // On success, handling_206_ will be set to true if we are processing a
309 bool ValidatePartialResponse();
311 // Handles a response validation error by bypassing the cache.
312 void IgnoreRangeRequest();
314 // Changes the response code of a range request to be 416 (Requested range not
316 void FailRangeRequest();
318 // Setups the transaction for reading from the cache entry.
319 int SetupEntryForRead();
321 // Reads data from the network.
322 int ReadFromNetwork(IOBuffer
* data
, int data_len
);
324 // Reads data from the cache entry.
325 int ReadFromEntry(IOBuffer
* data
, int data_len
);
327 // Called to write data to the cache entry. If the write fails, then the
328 // cache entry is destroyed. Future calls to this function will just do
329 // nothing without side-effect. Returns a network error code.
330 int WriteToEntry(int index
, int offset
, IOBuffer
* data
, int data_len
,
331 const CompletionCallback
& callback
);
333 // Called to write response_ to the cache entry. |truncated| indicates if the
334 // entry should be marked as incomplete.
335 int WriteResponseInfoToEntry(bool truncated
);
337 // Called to append response data to the cache entry. Returns a network error
339 int AppendResponseDataToEntry(IOBuffer
* data
, int data_len
,
340 const CompletionCallback
& callback
);
342 // Called when we are done writing to the cache entry.
343 void DoneWritingToEntry(bool success
);
345 // Returns an error to signal the caller that the current read failed. The
346 // current operation |result| is also logged. If |restart| is true, the
347 // transaction should be restarted.
348 int OnCacheReadError(int result
, bool restart
);
350 // Deletes the current partial cache entry (sparse), and optionally removes
351 // the control object (partial_).
352 void DoomPartialEntry(bool delete_object
);
354 // Performs the needed work after receiving data from the network, when
355 // working with range requests.
356 int DoPartialNetworkReadCompleted(int result
);
358 // Performs the needed work after receiving data from the cache, when
359 // working with range requests.
360 int DoPartialCacheReadCompleted(int result
);
362 // Restarts this transaction after deleting the cached data. It is meant to
363 // be used when the current request cannot be fulfilled due to conflicts
364 // between the byte range request and the cached entry.
365 int DoRestartPartialRequest();
367 // Returns true if we should bother attempting to resume this request if it
368 // is aborted while in progress. If |has_data| is true, the size of the stored
369 // data is considered for the result.
370 bool CanResume(bool has_data
);
372 // Called to signal completion of asynchronous IO.
373 void OnIOComplete(int result
);
375 void ReportCacheActionStart();
376 void ReportCacheActionFinish();
377 void ReportNetworkActionStart();
378 void ReportNetworkActionFinish();
379 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern
);
380 void RecordHistograms();
382 // Resets cache_io_start_ to the current time, if |return_value| is
384 // Returns |return_value|.
385 int ResetCacheIOStart(int return_value
);
387 void ScheduleDelayedLoop(base::TimeDelta delay
, int result
);
388 void RunDelayedLoop(base::TimeTicks delay_start_time
,
389 base::TimeDelta intended_delay
, int result
);
391 // Resets |network_trans_|, which must be non-NULL. Also updates
392 // |old_network_trans_load_timing_|, which must be NULL when this is called.
393 void ResetNetworkTransaction();
396 const HttpRequestInfo
* request_
;
397 RequestPriority priority_
;
398 BoundNetLog net_log_
;
399 scoped_ptr
<HttpRequestInfo
> custom_request_
;
400 HttpRequestHeaders request_headers_copy_
;
401 // If extra_headers specified a "if-modified-since" or "if-none-match",
402 // |external_validation_| contains the value of those headers.
403 ValidationHeaders external_validation_
;
404 base::WeakPtr
<HttpCache
> cache_
;
405 HttpCache::ActiveEntry
* entry_
;
406 HttpCache::ActiveEntry
* new_entry_
;
407 scoped_ptr
<HttpTransaction
> network_trans_
;
408 CompletionCallback callback_
; // Consumer's callback.
409 HttpResponseInfo response_
;
410 HttpResponseInfo auth_response_
;
411 const HttpResponseInfo
* new_response_
;
412 std::string cache_key_
;
415 bool reading_
; // We are already reading.
416 bool invalid_range_
; // We may bypass the cache for this request.
417 bool truncated_
; // We don't have all the response data.
418 bool is_sparse_
; // The data is stored in sparse byte ranges.
419 bool range_requested_
; // The user requested a byte range.
420 bool handling_206_
; // We must deal with this 206 response.
421 bool cache_pending_
; // We are waiting for the HttpCache.
423 bool vary_mismatch_
; // The request doesn't match the stored vary data.
424 bool couldnt_conditionalize_request_
;
425 scoped_refptr
<IOBuffer
> read_buf_
;
428 int effective_load_flags_
;
430 scoped_ptr
<PartialData
> partial_
; // We are dealing with range requests.
431 UploadProgress final_upload_progress_
;
432 base::WeakPtrFactory
<Transaction
> weak_factory_
;
433 CompletionCallback io_callback_
;
435 // Members used to track data for histograms.
436 TransactionPattern transaction_pattern_
;
437 base::TimeTicks entry_lock_waiting_since_
;
438 base::TimeTicks first_cache_access_since_
;
439 base::TimeTicks send_request_since_
;
441 // For sensitivity analysis (field trials emulating longer cache IO times),
442 // the time at which a cache IO action has started, or base::TimeTicks()
443 // if no cache IO action is currently in progress.
444 base::TimeTicks cache_io_start_
;
446 // For OpenEntry and CreateEntry, if sensitivity analysis would mandate
447 // a delay on return, we must defer that delay until AddToEntry has been
448 // called, to avoid a race condition on the address returned.
449 base::TimeDelta deferred_cache_sensitivity_delay_
;
450 bool defer_cache_sensitivity_delay_
;
452 // For sensitivity analysis, the simulated increase in cache service times,
454 int sensitivity_analysis_percent_increase_
;
456 HttpTransactionDelegate
* transaction_delegate_
;
458 // Load timing information for the last network request, if any. Set in the
459 // 304 and 206 response cases, as the network transaction may be destroyed
460 // before the caller requests load timing information.
461 scoped_ptr
<LoadTimingInfo
> old_network_trans_load_timing_
;
466 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_