• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 // This file declares HttpCache::Transaction, a private class of HttpCache so
6 // it should only be included by http_cache.cc
7 
8 #ifndef NET_HTTP_HTTP_CACHE_TRANSACTION_H_
9 #define NET_HTTP_HTTP_CACHE_TRANSACTION_H_
10 
11 #include <string>
12 
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"
21 
22 namespace net {
23 
24 class PartialData;
25 struct HttpRequestInfo;
26 class HttpTransactionDelegate;
27 struct LoadTimingInfo;
28 
29 // This is the transaction that is returned by the HttpCache transaction
30 // factory.
31 class HttpCache::Transaction : public HttpTransaction {
32  public:
33   // The transaction has the following modes, which apply to how it may access
34   // its cache entry.
35   //
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.
38   //
39   //  o If the mode of the transaction is only READ, then it may only read from
40   //    the cache entry.
41   //
42   //  o If the mode of the transaction is only WRITE, then it may only write to
43   //    the cache entry.
44   //
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
47   //    cache validation).
48   //
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.
52   enum Mode {
53     NONE            = 0,
54     READ_META       = 1 << 0,
55     READ_DATA       = 1 << 1,
56     READ            = READ_META | READ_DATA,
57     WRITE           = 1 << 2,
58     READ_WRITE      = READ | WRITE,
59     UPDATE          = READ_META | WRITE,  // READ_WRITE & ~READ_DATA
60   };
61 
62   Transaction(RequestPriority priority,
63               HttpCache* cache,
64               HttpTransactionDelegate* transaction_delegate);
65   virtual ~Transaction();
66 
mode()67   Mode mode() const { return mode_; }
68 
key()69   const std::string& key() const { return cache_key_; }
70 
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.
77   //
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.
81   //
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);
89 
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();
95 
entry()96   HttpCache::ActiveEntry* entry() { return entry_; }
97 
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;
103 
io_callback()104   const CompletionCallback& io_callback() { return io_callback_; }
105 
106   const BoundNetLog& net_log() const;
107 
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,
121                    int buf_len,
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;
133   virtual void SetWebSocketHandshakeStreamCreateHelper(
134       net::WebSocketHandshakeStreamBase::CreateHelper* create_helper) OVERRIDE;
135 
136  private:
137   static const size_t kNumValidationHeaders = 2;
138   // Helper struct to pair a header name with its value, for
139   // headers used to validate cache entries.
140   struct ValidationHeaders {
ValidationHeadersValidationHeaders141     ValidationHeaders() : initialized(false) {}
142 
143     std::string values[kNumValidationHeaders];
144     bool initialized;
145   };
146 
147   enum State {
148     STATE_NONE,
149     STATE_GET_BACKEND,
150     STATE_GET_BACKEND_COMPLETE,
151     STATE_SEND_REQUEST,
152     STATE_SEND_REQUEST_COMPLETE,
153     STATE_SUCCESSFUL_SEND_REQUEST,
154     STATE_NETWORK_READ,
155     STATE_NETWORK_READ_COMPLETE,
156     STATE_INIT_ENTRY,
157     STATE_OPEN_ENTRY,
158     STATE_OPEN_ENTRY_COMPLETE,
159     STATE_CREATE_ENTRY,
160     STATE_CREATE_ENTRY_COMPLETE,
161     STATE_DOOM_ENTRY,
162     STATE_DOOM_ENTRY_COMPLETE,
163     STATE_ADD_TO_ENTRY,
164     STATE_ADD_TO_ENTRY_COMPLETE,
165     STATE_START_PARTIAL_CACHE_VALIDATION,
166     STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
167     STATE_UPDATE_CACHED_RESPONSE,
168     STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
169     STATE_OVERWRITE_CACHED_RESPONSE,
170     STATE_TRUNCATE_CACHED_DATA,
171     STATE_TRUNCATE_CACHED_DATA_COMPLETE,
172     STATE_TRUNCATE_CACHED_METADATA,
173     STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
174     STATE_PARTIAL_HEADERS_RECEIVED,
175     STATE_CACHE_READ_RESPONSE,
176     STATE_CACHE_READ_RESPONSE_COMPLETE,
177     STATE_CACHE_WRITE_RESPONSE,
178     STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
179     STATE_CACHE_WRITE_RESPONSE_COMPLETE,
180     STATE_CACHE_READ_METADATA,
181     STATE_CACHE_READ_METADATA_COMPLETE,
182     STATE_CACHE_QUERY_DATA,
183     STATE_CACHE_QUERY_DATA_COMPLETE,
184     STATE_CACHE_READ_DATA,
185     STATE_CACHE_READ_DATA_COMPLETE,
186     STATE_CACHE_WRITE_DATA,
187     STATE_CACHE_WRITE_DATA_COMPLETE
188   };
189 
190   // Used for categorizing transactions for reporting in histograms. Patterns
191   // cover relatively common use cases being measured and considered for
192   // optimization. Many use cases that are more complex or uncommon are binned
193   // as PATTERN_NOT_COVERED, and details are not reported.
194   // NOTE: This enumeration is used in histograms, so please do not add entries
195   // in the middle.
196   enum TransactionPattern {
197     PATTERN_UNDEFINED,
198     PATTERN_NOT_COVERED,
199     PATTERN_ENTRY_NOT_CACHED,
200     PATTERN_ENTRY_USED,
201     PATTERN_ENTRY_VALIDATED,
202     PATTERN_ENTRY_UPDATED,
203     PATTERN_ENTRY_CANT_CONDITIONALIZE,
204     PATTERN_MAX,
205   };
206 
207   // This is a helper function used to trigger a completion callback.  It may
208   // only be called if callback_ is non-null.
209   void DoCallback(int rv);
210 
211   // This will trigger the completion callback if appropriate.
212   int HandleResult(int rv);
213 
214   // Runs the state transition loop.
215   int DoLoop(int result);
216 
217   // Each of these methods corresponds to a State value.  If there is an
218   // argument, the value corresponds to the return of the previous state or
219   // corresponding callback.
220   int DoGetBackend();
221   int DoGetBackendComplete(int result);
222   int DoSendRequest();
223   int DoSendRequestComplete(int result);
224   int DoSuccessfulSendRequest();
225   int DoNetworkRead();
226   int DoNetworkReadComplete(int result);
227   int DoInitEntry();
228   int DoOpenEntry();
229   int DoOpenEntryComplete(int result);
230   int DoCreateEntry();
231   int DoCreateEntryComplete(int result);
232   int DoDoomEntry();
233   int DoDoomEntryComplete(int result);
234   int DoAddToEntry();
235   int DoAddToEntryComplete(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);
259 
260   // Sets request_ and fields derived from it.
261   void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
262 
263   // Returns true if the request should be handled exclusively by the network
264   // layer (skipping the cache entirely).
265   bool ShouldPassThrough();
266 
267   // Called to begin reading from the cache.  Returns network error code.
268   int BeginCacheRead();
269 
270   // Called to begin validating the cache entry.  Returns network error code.
271   int BeginCacheValidation();
272 
273   // Called to begin validating an entry that stores partial content.  Returns
274   // a network error code.
275   int BeginPartialCacheValidation();
276 
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();
280 
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();
286 
287   // Called to restart a network transaction after an error.  Returns network
288   // error code.
289   int RestartNetworkRequest();
290 
291   // Called to restart a network transaction with a client certificate.
292   // Returns network error code.
293   int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
294 
295   // Called to restart a network transaction with authentication credentials.
296   // Returns network error code.
297   int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
298 
299   // Called to determine if we need to validate the cache entry before using it.
300   bool RequiresValidation();
301 
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();
305 
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
308   // partial entry.
309   bool ValidatePartialResponse();
310 
311   // Handles a response validation error by bypassing the cache.
312   void IgnoreRangeRequest();
313 
314   // Changes the response code of a range request to be 416 (Requested range not
315   // satisfiable).
316   void FailRangeRequest();
317 
318   // Setups the transaction for reading from the cache entry.
319   int SetupEntryForRead();
320 
321   // Reads data from the network.
322   int ReadFromNetwork(IOBuffer* data, int data_len);
323 
324   // Reads data from the cache entry.
325   int ReadFromEntry(IOBuffer* data, int data_len);
326 
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);
332 
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);
336 
337   // Called to append response data to the cache entry.  Returns a network error
338   // code.
339   int AppendResponseDataToEntry(IOBuffer* data, int data_len,
340                                 const CompletionCallback& callback);
341 
342   // Called when we are done writing to the cache entry.
343   void DoneWritingToEntry(bool success);
344 
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);
349 
350   // Deletes the current partial cache entry (sparse), and optionally removes
351   // the control object (partial_).
352   void DoomPartialEntry(bool delete_object);
353 
354   // Performs the needed work after receiving data from the network, when
355   // working with range requests.
356   int DoPartialNetworkReadCompleted(int result);
357 
358   // Performs the needed work after receiving data from the cache, when
359   // working with range requests.
360   int DoPartialCacheReadCompleted(int result);
361 
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();
366 
367   // Resets |network_trans_|, which must be non-NULL.  Also updates
368   // |old_network_trans_load_timing_|, which must be NULL when this is called.
369   void ResetNetworkTransaction();
370 
371   // Returns true if we should bother attempting to resume this request if it
372   // is aborted while in progress. If |has_data| is true, the size of the stored
373   // data is considered for the result.
374   bool CanResume(bool has_data);
375 
376   // Called to signal completion of asynchronous IO.
377   void OnIOComplete(int result);
378 
379   void ReportCacheActionStart();
380   void ReportCacheActionFinish();
381   void ReportNetworkActionStart();
382   void ReportNetworkActionFinish();
383   void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
384   void RecordHistograms();
385 
386   State next_state_;
387   const HttpRequestInfo* request_;
388   RequestPriority priority_;
389   BoundNetLog net_log_;
390   scoped_ptr<HttpRequestInfo> custom_request_;
391   HttpRequestHeaders request_headers_copy_;
392   // If extra_headers specified a "if-modified-since" or "if-none-match",
393   // |external_validation_| contains the value of those headers.
394   ValidationHeaders external_validation_;
395   base::WeakPtr<HttpCache> cache_;
396   HttpCache::ActiveEntry* entry_;
397   HttpCache::ActiveEntry* new_entry_;
398   scoped_ptr<HttpTransaction> network_trans_;
399   CompletionCallback callback_;  // Consumer's callback.
400   HttpResponseInfo response_;
401   HttpResponseInfo auth_response_;
402   const HttpResponseInfo* new_response_;
403   std::string cache_key_;
404   Mode mode_;
405   State target_state_;
406   bool reading_;  // We are already reading.
407   bool invalid_range_;  // We may bypass the cache for this request.
408   bool truncated_;  // We don't have all the response data.
409   bool is_sparse_;  // The data is stored in sparse byte ranges.
410   bool range_requested_;  // The user requested a byte range.
411   bool handling_206_;  // We must deal with this 206 response.
412   bool cache_pending_;  // We are waiting for the HttpCache.
413   bool done_reading_;
414   bool vary_mismatch_;  // The request doesn't match the stored vary data.
415   bool couldnt_conditionalize_request_;
416   scoped_refptr<IOBuffer> read_buf_;
417   int io_buf_len_;
418   int read_offset_;
419   int effective_load_flags_;
420   int write_len_;
421   scoped_ptr<PartialData> partial_;  // We are dealing with range requests.
422   UploadProgress final_upload_progress_;
423   base::WeakPtrFactory<Transaction> weak_factory_;
424   CompletionCallback io_callback_;
425 
426   // Members used to track data for histograms.
427   TransactionPattern transaction_pattern_;
428   base::TimeTicks entry_lock_waiting_since_;
429   base::TimeTicks first_cache_access_since_;
430   base::TimeTicks send_request_since_;
431 
432   HttpTransactionDelegate* transaction_delegate_;
433 
434   // Load timing information for the last network request, if any.  Set in the
435   // 304 and 206 response cases, as the network transaction may be destroyed
436   // before the caller requests load timing information.
437   scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
438 
439   // The helper object to use to create WebSocketHandshakeStreamBase
440   // objects. Only relevant when establishing a WebSocket connection.
441   // This is passed to the underlying network transaction. It is stored here in
442   // case the transaction does not exist yet.
443   WebSocketHandshakeStreamBase::CreateHelper*
444       websocket_handshake_stream_base_create_helper_;
445 
446   DISALLOW_COPY_AND_ASSIGN(Transaction);
447 };
448 
449 }  // namespace net
450 
451 #endif  // NET_HTTP_HTTP_CACHE_TRANSACTION_H_
452