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_START_PARTIAL_CACHE_VALIDATION,
164 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
165 STATE_UPDATE_CACHED_RESPONSE,
166 STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
167 STATE_OVERWRITE_CACHED_RESPONSE,
168 STATE_TRUNCATE_CACHED_DATA,
169 STATE_TRUNCATE_CACHED_DATA_COMPLETE,
170 STATE_TRUNCATE_CACHED_METADATA,
171 STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
172 STATE_PARTIAL_HEADERS_RECEIVED,
173 STATE_CACHE_READ_RESPONSE,
174 STATE_CACHE_READ_RESPONSE_COMPLETE,
175 STATE_CACHE_WRITE_RESPONSE,
176 STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
177 STATE_CACHE_WRITE_RESPONSE_COMPLETE,
178 STATE_CACHE_READ_METADATA,
179 STATE_CACHE_READ_METADATA_COMPLETE,
180 STATE_CACHE_QUERY_DATA,
181 STATE_CACHE_QUERY_DATA_COMPLETE,
182 STATE_CACHE_READ_DATA,
183 STATE_CACHE_READ_DATA_COMPLETE,
184 STATE_CACHE_WRITE_DATA,
185 STATE_CACHE_WRITE_DATA_COMPLETE
188 // Used for categorizing transactions for reporting in histograms. Patterns
189 // cover relatively common use cases being measured and considered for
190 // optimization. Many use cases that are more complex or uncommon are binned
191 // as PATTERN_NOT_COVERED, and details are not reported.
192 // NOTE: This enumeration is used in histograms, so please do not add entries
194 enum TransactionPattern {
197 PATTERN_ENTRY_NOT_CACHED,
199 PATTERN_ENTRY_VALIDATED,
200 PATTERN_ENTRY_UPDATED,
201 PATTERN_ENTRY_CANT_CONDITIONALIZE,
205 // This is a helper function used to trigger a completion callback. It may
206 // only be called if callback_ is non-null.
207 void DoCallback(int rv);
209 // This will trigger the completion callback if appropriate.
210 int HandleResult(int rv);
212 // Runs the state transition loop.
213 int DoLoop(int result);
215 // Each of these methods corresponds to a State value. If there is an
216 // argument, the value corresponds to the return of the previous state or
217 // corresponding callback.
219 int DoGetBackendComplete(int result);
221 int DoSendRequestComplete(int result);
222 int DoSuccessfulSendRequest();
224 int DoNetworkReadComplete(int result);
227 int DoOpenEntryComplete(int result);
229 int DoCreateEntryComplete(int result);
231 int DoDoomEntryComplete(int result);
233 int DoAddToEntryComplete(int result);
234 int DoStartPartialCacheValidation();
235 int DoCompletePartialCacheValidation(int result);
236 int DoUpdateCachedResponse();
237 int DoUpdateCachedResponseComplete(int result);
238 int DoOverwriteCachedResponse();
239 int DoTruncateCachedData();
240 int DoTruncateCachedDataComplete(int result);
241 int DoTruncateCachedMetadata();
242 int DoTruncateCachedMetadataComplete(int result);
243 int DoPartialHeadersReceived();
244 int DoCacheReadResponse();
245 int DoCacheReadResponseComplete(int result);
246 int DoCacheWriteResponse();
247 int DoCacheWriteTruncatedResponse();
248 int DoCacheWriteResponseComplete(int result);
249 int DoCacheReadMetadata();
250 int DoCacheReadMetadataComplete(int result);
251 int DoCacheQueryData();
252 int DoCacheQueryDataComplete(int result);
253 int DoCacheReadData();
254 int DoCacheReadDataComplete(int result);
255 int DoCacheWriteData(int num_bytes);
256 int DoCacheWriteDataComplete(int result);
258 // Sets request_ and fields derived from it.
259 void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
261 // Returns true if the request should be handled exclusively by the network
262 // layer (skipping the cache entirely).
263 bool ShouldPassThrough();
265 // Called to begin reading from the cache. Returns network error code.
266 int BeginCacheRead();
268 // Called to begin validating the cache entry. Returns network error code.
269 int BeginCacheValidation();
271 // Called to begin validating an entry that stores partial content. Returns
272 // a network error code.
273 int BeginPartialCacheValidation();
275 // Validates the entry headers against the requested range and continues with
276 // the validation of the rest of the entry. Returns a network error code.
277 int ValidateEntryHeadersAndContinue();
279 // Called to start requests which were given an "if-modified-since" or
280 // "if-none-match" validation header by the caller (NOT when the request was
281 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
282 // Returns a network error code.
283 int BeginExternallyConditionalizedRequest();
285 // Called to restart a network transaction after an error. Returns network
287 int RestartNetworkRequest();
289 // Called to restart a network transaction with a client certificate.
290 // Returns network error code.
291 int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
293 // Called to restart a network transaction with authentication credentials.
294 // Returns network error code.
295 int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
297 // Called to determine if we need to validate the cache entry before using it.
298 bool RequiresValidation();
300 // Called to make the request conditional (to ask the server if the cached
301 // copy is valid). Returns true if able to make the request conditional.
302 bool ConditionalizeRequest();
304 // Makes sure that a 206 response is expected. Returns true on success.
305 // On success, handling_206_ will be set to true if we are processing a
307 bool ValidatePartialResponse();
309 // Handles a response validation error by bypassing the cache.
310 void IgnoreRangeRequest();
312 // Changes the response code of a range request to be 416 (Requested range not
314 void FailRangeRequest();
316 // Setups the transaction for reading from the cache entry.
317 int SetupEntryForRead();
319 // Reads data from the network.
320 int ReadFromNetwork(IOBuffer* data, int data_len);
322 // Reads data from the cache entry.
323 int ReadFromEntry(IOBuffer* data, int data_len);
325 // Called to write data to the cache entry. If the write fails, then the
326 // cache entry is destroyed. Future calls to this function will just do
327 // nothing without side-effect. Returns a network error code.
328 int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
329 const CompletionCallback& callback);
331 // Called to write response_ to the cache entry. |truncated| indicates if the
332 // entry should be marked as incomplete.
333 int WriteResponseInfoToEntry(bool truncated);
335 // Called to append response data to the cache entry. Returns a network error
337 int AppendResponseDataToEntry(IOBuffer* data, int data_len,
338 const CompletionCallback& callback);
340 // Called when we are done writing to the cache entry.
341 void DoneWritingToEntry(bool success);
343 // Returns an error to signal the caller that the current read failed. The
344 // current operation |result| is also logged. If |restart| is true, the
345 // transaction should be restarted.
346 int OnCacheReadError(int result, bool restart);
348 // Deletes the current partial cache entry (sparse), and optionally removes
349 // the control object (partial_).
350 void DoomPartialEntry(bool delete_object);
352 // Performs the needed work after receiving data from the network, when
353 // working with range requests.
354 int DoPartialNetworkReadCompleted(int result);
356 // Performs the needed work after receiving data from the cache, when
357 // working with range requests.
358 int DoPartialCacheReadCompleted(int result);
360 // Restarts this transaction after deleting the cached data. It is meant to
361 // be used when the current request cannot be fulfilled due to conflicts
362 // between the byte range request and the cached entry.
363 int DoRestartPartialRequest();
365 // Resets |network_trans_|, which must be non-NULL. Also updates
366 // |old_network_trans_load_timing_|, which must be NULL when this is called.
367 void ResetNetworkTransaction();
369 // Returns true if we should bother attempting to resume this request if it
370 // is aborted while in progress. If |has_data| is true, the size of the stored
371 // data is considered for the result.
372 bool CanResume(bool has_data);
374 // Called to signal completion of asynchronous IO.
375 void OnIOComplete(int result);
377 void ReportCacheActionStart();
378 void ReportCacheActionFinish();
379 void ReportNetworkActionStart();
380 void ReportNetworkActionFinish();
381 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
382 void RecordHistograms();
385 const HttpRequestInfo* request_;
386 RequestPriority priority_;
387 BoundNetLog net_log_;
388 scoped_ptr<HttpRequestInfo> custom_request_;
389 HttpRequestHeaders request_headers_copy_;
390 // If extra_headers specified a "if-modified-since" or "if-none-match",
391 // |external_validation_| contains the value of those headers.
392 ValidationHeaders external_validation_;
393 base::WeakPtr<HttpCache> cache_;
394 HttpCache::ActiveEntry* entry_;
395 HttpCache::ActiveEntry* new_entry_;
396 scoped_ptr<HttpTransaction> network_trans_;
397 CompletionCallback callback_; // Consumer's callback.
398 HttpResponseInfo response_;
399 HttpResponseInfo auth_response_;
400 const HttpResponseInfo* new_response_;
401 std::string cache_key_;
404 bool reading_; // We are already reading.
405 bool invalid_range_; // We may bypass the cache for this request.
406 bool truncated_; // We don't have all the response data.
407 bool is_sparse_; // The data is stored in sparse byte ranges.
408 bool range_requested_; // The user requested a byte range.
409 bool handling_206_; // We must deal with this 206 response.
410 bool cache_pending_; // We are waiting for the HttpCache.
412 bool vary_mismatch_; // The request doesn't match the stored vary data.
413 bool couldnt_conditionalize_request_;
414 scoped_refptr<IOBuffer> read_buf_;
417 int effective_load_flags_;
419 scoped_ptr<PartialData> partial_; // We are dealing with range requests.
420 UploadProgress final_upload_progress_;
421 base::WeakPtrFactory<Transaction> weak_factory_;
422 CompletionCallback io_callback_;
424 // Members used to track data for histograms.
425 TransactionPattern transaction_pattern_;
426 base::TimeTicks entry_lock_waiting_since_;
427 base::TimeTicks first_cache_access_since_;
428 base::TimeTicks send_request_since_;
430 HttpTransactionDelegate* transaction_delegate_;
432 // Load timing information for the last network request, if any. Set in the
433 // 304 and 206 response cases, as the network transaction may be destroyed
434 // before the caller requests load timing information.
435 scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
440 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_