Adds presentation_context and presentation_media_sinks_observer
[chromium-blink-merge.git] / net / http / http_cache_transaction.h
blobcbf092907a99869813309f9590b7bfae8c6a2cbc
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_
11 #include <string>
13 #include "base/time/time.h"
14 #include "net/base/completion_callback.h"
15 #include "net/base/request_priority.h"
16 #include "net/http/http_cache.h"
17 #include "net/http/http_request_headers.h"
18 #include "net/http/http_response_headers.h"
19 #include "net/http/http_response_info.h"
20 #include "net/http/http_transaction.h"
21 #include "net/log/net_log.h"
22 #include "net/socket/connection_attempts.h"
24 namespace net {
26 class PartialData;
27 struct HttpRequestInfo;
28 struct LoadTimingInfo;
30 // This is the transaction that is returned by the HttpCache transaction
31 // factory.
32 class HttpCache::Transaction : public HttpTransaction {
33 public:
34 // The transaction has the following modes, which apply to how it may access
35 // its cache entry.
37 // o If the mode of the transaction is NONE, then it is in "pass through"
38 // mode and all methods just forward to the inner network transaction.
40 // o If the mode of the transaction is only READ, then it may only read from
41 // the cache entry.
43 // o If the mode of the transaction is only WRITE, then it may only write to
44 // the cache entry.
46 // o If the mode of the transaction is READ_WRITE, then the transaction may
47 // optionally modify the cache entry (e.g., possibly corresponding to
48 // cache validation).
50 // o If the mode of the transaction is UPDATE, then the transaction may
51 // update existing cache entries, but will never create a new entry or
52 // respond using the entry read from the cache.
53 enum Mode {
54 NONE = 0,
55 READ_META = 1 << 0,
56 READ_DATA = 1 << 1,
57 READ = READ_META | READ_DATA,
58 WRITE = 1 << 2,
59 READ_WRITE = READ | WRITE,
60 UPDATE = READ_META | WRITE, // READ_WRITE & ~READ_DATA
63 Transaction(RequestPriority priority,
64 HttpCache* cache);
65 ~Transaction() override;
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
85 // method.
86 int WriteMetadata(IOBuffer* buf,
87 int buf_len,
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 // Bypasses the cache lock whenever there is lock contention.
109 void BypassLockForTest() {
110 bypass_lock_for_test_ = true;
113 // Generates a failure when attempting to conditionalize a network request.
114 void FailConditionalizationForTest() {
115 fail_conditionalization_for_test_ = true;
118 // HttpTransaction methods:
119 int Start(const HttpRequestInfo* request_info,
120 const CompletionCallback& callback,
121 const BoundNetLog& net_log) override;
122 int RestartIgnoringLastError(const CompletionCallback& callback) override;
123 int RestartWithCertificate(X509Certificate* client_cert,
124 const CompletionCallback& callback) override;
125 int RestartWithAuth(const AuthCredentials& credentials,
126 const CompletionCallback& callback) override;
127 bool IsReadyToRestartForAuth() override;
128 int Read(IOBuffer* buf,
129 int buf_len,
130 const CompletionCallback& callback) override;
131 void StopCaching() override;
132 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const override;
133 int64 GetTotalReceivedBytes() const override;
134 void DoneReading() override;
135 const HttpResponseInfo* GetResponseInfo() const override;
136 LoadState GetLoadState() const override;
137 UploadProgress GetUploadProgress(void) const override;
138 void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
139 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
140 void SetPriority(RequestPriority priority) override;
141 void SetWebSocketHandshakeStreamCreateHelper(
142 WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
143 void SetBeforeNetworkStartCallback(
144 const BeforeNetworkStartCallback& callback) override;
145 void SetBeforeProxyHeadersSentCallback(
146 const BeforeProxyHeadersSentCallback& callback) override;
147 int ResumeNetworkStart() override;
148 void GetConnectionAttempts(ConnectionAttempts* out) const override;
150 private:
151 static const size_t kNumValidationHeaders = 2;
152 // Helper struct to pair a header name with its value, for
153 // headers used to validate cache entries.
154 struct ValidationHeaders {
155 ValidationHeaders() : initialized(false) {}
157 std::string values[kNumValidationHeaders];
158 bool initialized;
161 enum State {
162 STATE_NONE,
163 STATE_GET_BACKEND,
164 STATE_GET_BACKEND_COMPLETE,
165 STATE_SEND_REQUEST,
166 STATE_SEND_REQUEST_COMPLETE,
167 STATE_SUCCESSFUL_SEND_REQUEST,
168 STATE_NETWORK_READ,
169 STATE_NETWORK_READ_COMPLETE,
170 STATE_INIT_ENTRY,
171 STATE_OPEN_ENTRY,
172 STATE_OPEN_ENTRY_COMPLETE,
173 STATE_CREATE_ENTRY,
174 STATE_CREATE_ENTRY_COMPLETE,
175 STATE_DOOM_ENTRY,
176 STATE_DOOM_ENTRY_COMPLETE,
177 STATE_ADD_TO_ENTRY,
178 STATE_ADD_TO_ENTRY_COMPLETE,
179 STATE_START_PARTIAL_CACHE_VALIDATION,
180 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
181 STATE_UPDATE_CACHED_RESPONSE,
182 STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
183 STATE_OVERWRITE_CACHED_RESPONSE,
184 STATE_TRUNCATE_CACHED_DATA,
185 STATE_TRUNCATE_CACHED_DATA_COMPLETE,
186 STATE_TRUNCATE_CACHED_METADATA,
187 STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
188 STATE_PARTIAL_HEADERS_RECEIVED,
189 STATE_CACHE_READ_RESPONSE,
190 STATE_CACHE_READ_RESPONSE_COMPLETE,
191 STATE_CACHE_DISPATCH_VALIDATION,
192 STATE_TOGGLE_UNUSED_SINCE_PREFETCH,
193 STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE,
194 STATE_CACHE_WRITE_RESPONSE,
195 STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
196 STATE_CACHE_WRITE_RESPONSE_COMPLETE,
197 STATE_CACHE_READ_METADATA,
198 STATE_CACHE_READ_METADATA_COMPLETE,
199 STATE_CACHE_QUERY_DATA,
200 STATE_CACHE_QUERY_DATA_COMPLETE,
201 STATE_CACHE_READ_DATA,
202 STATE_CACHE_READ_DATA_COMPLETE,
203 STATE_CACHE_WRITE_DATA,
204 STATE_CACHE_WRITE_DATA_COMPLETE
207 // Used for categorizing transactions for reporting in histograms. Patterns
208 // cover relatively common use cases being measured and considered for
209 // optimization. Many use cases that are more complex or uncommon are binned
210 // as PATTERN_NOT_COVERED, and details are not reported.
211 // NOTE: This enumeration is used in histograms, so please do not add entries
212 // in the middle.
213 enum TransactionPattern {
214 PATTERN_UNDEFINED,
215 PATTERN_NOT_COVERED,
216 PATTERN_ENTRY_NOT_CACHED,
217 PATTERN_ENTRY_USED,
218 PATTERN_ENTRY_VALIDATED,
219 PATTERN_ENTRY_UPDATED,
220 PATTERN_ENTRY_CANT_CONDITIONALIZE,
221 PATTERN_MAX,
224 // This is a helper function used to trigger a completion callback. It may
225 // only be called if callback_ is non-null.
226 void DoCallback(int rv);
228 // This will trigger the completion callback if appropriate.
229 int HandleResult(int rv);
231 // Runs the state transition loop.
232 int DoLoop(int result);
234 // Each of these methods corresponds to a State value. If there is an
235 // argument, the value corresponds to the return of the previous state or
236 // corresponding callback.
237 int DoGetBackend();
238 int DoGetBackendComplete(int result);
239 int DoSendRequest();
240 int DoSendRequestComplete(int result);
241 int DoSuccessfulSendRequest();
242 int DoNetworkRead();
243 int DoNetworkReadComplete(int result);
244 int DoInitEntry();
245 int DoOpenEntry();
246 int DoOpenEntryComplete(int result);
247 int DoCreateEntry();
248 int DoCreateEntryComplete(int result);
249 int DoDoomEntry();
250 int DoDoomEntryComplete(int result);
251 int DoAddToEntry();
252 int DoAddToEntryComplete(int result);
253 int DoStartPartialCacheValidation();
254 int DoCompletePartialCacheValidation(int result);
255 int DoUpdateCachedResponse();
256 int DoUpdateCachedResponseComplete(int result);
257 int DoOverwriteCachedResponse();
258 int DoTruncateCachedData();
259 int DoTruncateCachedDataComplete(int result);
260 int DoTruncateCachedMetadata();
261 int DoTruncateCachedMetadataComplete(int result);
262 int DoPartialHeadersReceived();
263 int DoCacheReadResponse();
264 int DoCacheReadResponseComplete(int result);
265 int DoCacheDispatchValidation();
266 int DoCacheToggleUnusedSincePrefetch();
267 int DoCacheToggleUnusedSincePrefetchComplete(int result);
268 int DoCacheWriteResponse();
269 int DoCacheWriteTruncatedResponse();
270 int DoCacheWriteResponseComplete(int result);
271 int DoCacheReadMetadata();
272 int DoCacheReadMetadataComplete(int result);
273 int DoCacheQueryData();
274 int DoCacheQueryDataComplete(int result);
275 int DoCacheReadData();
276 int DoCacheReadDataComplete(int result);
277 int DoCacheWriteData(int num_bytes);
278 int DoCacheWriteDataComplete(int result);
280 // These functions are involved in a field trial testing storing certificates
281 // in seperate entries from the HttpResponseInfo.
282 void ReadCertChain();
283 void WriteCertChain();
285 // Sets request_ and fields derived from it.
286 void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
288 // Returns true if the request should be handled exclusively by the network
289 // layer (skipping the cache entirely).
290 bool ShouldPassThrough();
292 // Called to begin reading from the cache. Returns network error code.
293 int BeginCacheRead();
295 // Called to begin validating the cache entry. Returns network error code.
296 int BeginCacheValidation();
298 // Called to begin validating an entry that stores partial content. Returns
299 // a network error code.
300 int BeginPartialCacheValidation();
302 // Validates the entry headers against the requested range and continues with
303 // the validation of the rest of the entry. Returns a network error code.
304 int ValidateEntryHeadersAndContinue();
306 // Called to start requests which were given an "if-modified-since" or
307 // "if-none-match" validation header by the caller (NOT when the request was
308 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
309 // Returns a network error code.
310 int BeginExternallyConditionalizedRequest();
312 // Called to restart a network transaction after an error. Returns network
313 // error code.
314 int RestartNetworkRequest();
316 // Called to restart a network transaction with a client certificate.
317 // Returns network error code.
318 int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
320 // Called to restart a network transaction with authentication credentials.
321 // Returns network error code.
322 int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
324 // Called to determine if we need to validate the cache entry before using it,
325 // and whether the validation should be synchronous or asynchronous.
326 ValidationType RequiresValidation();
328 // Called to make the request conditional (to ask the server if the cached
329 // copy is valid). Returns true if able to make the request conditional.
330 bool ConditionalizeRequest();
332 // Makes sure that a 206 response is expected. Returns true on success.
333 // On success, handling_206_ will be set to true if we are processing a
334 // partial entry.
335 bool ValidatePartialResponse();
337 // Handles a response validation error by bypassing the cache.
338 void IgnoreRangeRequest();
340 // Fixes the response headers to match expectations for a HEAD request.
341 void FixHeadersForHead();
343 // Launches an asynchronous revalidation based on this transaction.
344 void TriggerAsyncValidation();
346 // Changes the response code of a range request to be 416 (Requested range not
347 // satisfiable).
348 void FailRangeRequest();
350 // Setups the transaction for reading from the cache entry.
351 int SetupEntryForRead();
353 // Reads data from the network.
354 int ReadFromNetwork(IOBuffer* data, int data_len);
356 // Reads data from the cache entry.
357 int ReadFromEntry(IOBuffer* data, int data_len);
359 // Called to write data to the cache entry. If the write fails, then the
360 // cache entry is destroyed. Future calls to this function will just do
361 // nothing without side-effect. Returns a network error code.
362 int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
363 const CompletionCallback& callback);
365 // Called to write response_ to the cache entry. |truncated| indicates if the
366 // entry should be marked as incomplete.
367 int WriteResponseInfoToEntry(bool truncated);
369 // Called to append response data to the cache entry. Returns a network error
370 // code.
371 int AppendResponseDataToEntry(IOBuffer* data, int data_len,
372 const CompletionCallback& callback);
374 // Called when we are done writing to the cache entry.
375 void DoneWritingToEntry(bool success);
377 // Returns an error to signal the caller that the current read failed. The
378 // current operation |result| is also logged. If |restart| is true, the
379 // transaction should be restarted.
380 int OnCacheReadError(int result, bool restart);
382 // Called when the cache lock timeout fires.
383 void OnAddToEntryTimeout(base::TimeTicks start_time);
385 // Deletes the current partial cache entry (sparse), and optionally removes
386 // the control object (partial_).
387 void DoomPartialEntry(bool delete_object);
389 // Performs the needed work after receiving data from the network, when
390 // working with range requests.
391 int DoPartialNetworkReadCompleted(int result);
393 // Performs the needed work after receiving data from the cache, when
394 // working with range requests.
395 int DoPartialCacheReadCompleted(int result);
397 // Restarts this transaction after deleting the cached data. It is meant to
398 // be used when the current request cannot be fulfilled due to conflicts
399 // between the byte range request and the cached entry.
400 int DoRestartPartialRequest();
402 // Resets the relavant internal state to remove traces of internal processing
403 // related to range requests. Deletes |partial_| if |delete_object| is true.
404 void ResetPartialState(bool delete_object);
406 // Resets |network_trans_|, which must be non-NULL. Also updates
407 // |old_network_trans_load_timing_|, which must be NULL when this is called.
408 void ResetNetworkTransaction();
410 // Returns true if we should bother attempting to resume this request if it
411 // is aborted while in progress. If |has_data| is true, the size of the stored
412 // data is considered for the result.
413 bool CanResume(bool has_data);
415 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
416 void RecordHistograms();
418 // Called to signal completion of asynchronous IO.
419 void OnIOComplete(int result);
421 State next_state_;
422 const HttpRequestInfo* request_;
423 RequestPriority priority_;
424 BoundNetLog net_log_;
425 scoped_ptr<HttpRequestInfo> custom_request_;
426 HttpRequestHeaders request_headers_copy_;
427 // If extra_headers specified a "if-modified-since" or "if-none-match",
428 // |external_validation_| contains the value of those headers.
429 ValidationHeaders external_validation_;
430 base::WeakPtr<HttpCache> cache_;
431 HttpCache::ActiveEntry* entry_;
432 HttpCache::ActiveEntry* new_entry_;
433 scoped_ptr<HttpTransaction> network_trans_;
434 CompletionCallback callback_; // Consumer's callback.
435 HttpResponseInfo response_;
436 HttpResponseInfo auth_response_;
437 const HttpResponseInfo* new_response_;
438 std::string cache_key_;
439 Mode mode_;
440 State target_state_;
441 bool reading_; // We are already reading. Never reverts to false once set.
442 bool invalid_range_; // We may bypass the cache for this request.
443 bool truncated_; // We don't have all the response data.
444 bool is_sparse_; // The data is stored in sparse byte ranges.
445 bool range_requested_; // The user requested a byte range.
446 bool handling_206_; // We must deal with this 206 response.
447 bool cache_pending_; // We are waiting for the HttpCache.
448 bool done_reading_; // All available data was read.
449 bool vary_mismatch_; // The request doesn't match the stored vary data.
450 bool couldnt_conditionalize_request_;
451 bool bypass_lock_for_test_; // A test is exercising the cache lock.
452 bool fail_conditionalization_for_test_; // Fail ConditionalizeRequest.
453 scoped_refptr<IOBuffer> read_buf_;
454 int io_buf_len_;
455 int read_offset_;
456 int effective_load_flags_;
457 int write_len_;
458 scoped_ptr<PartialData> partial_; // We are dealing with range requests.
459 UploadProgress final_upload_progress_;
460 CompletionCallback io_callback_;
462 // Members used to track data for histograms.
463 TransactionPattern transaction_pattern_;
464 base::TimeTicks entry_lock_waiting_since_;
465 base::TimeTicks first_cache_access_since_;
466 base::TimeTicks send_request_since_;
468 int64 total_received_bytes_;
470 // Load timing information for the last network request, if any. Set in the
471 // 304 and 206 response cases, as the network transaction may be destroyed
472 // before the caller requests load timing information.
473 scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
475 ConnectionAttempts old_connection_attempts_;
477 // The helper object to use to create WebSocketHandshakeStreamBase
478 // objects. Only relevant when establishing a WebSocket connection.
479 // This is passed to the underlying network transaction. It is stored here in
480 // case the transaction does not exist yet.
481 WebSocketHandshakeStreamBase::CreateHelper*
482 websocket_handshake_stream_base_create_helper_;
484 BeforeNetworkStartCallback before_network_start_callback_;
485 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
487 base::WeakPtrFactory<Transaction> weak_factory_;
489 DISALLOW_COPY_AND_ASSIGN(Transaction);
492 } // namespace net
494 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_