- add sources.
[platform/framework/web/crosswalk.git] / src / net / http / http_cache_transaction.h
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
67   Mode mode() const { return mode_; }
68
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
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
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
134  private:
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) {}
140
141     std::string values[kNumValidationHeaders];
142     bool initialized;
143   };
144
145   enum State {
146     STATE_NONE,
147     STATE_GET_BACKEND,
148     STATE_GET_BACKEND_COMPLETE,
149     STATE_SEND_REQUEST,
150     STATE_SEND_REQUEST_COMPLETE,
151     STATE_SUCCESSFUL_SEND_REQUEST,
152     STATE_NETWORK_READ,
153     STATE_NETWORK_READ_COMPLETE,
154     STATE_INIT_ENTRY,
155     STATE_OPEN_ENTRY,
156     STATE_OPEN_ENTRY_COMPLETE,
157     STATE_CREATE_ENTRY,
158     STATE_CREATE_ENTRY_COMPLETE,
159     STATE_DOOM_ENTRY,
160     STATE_DOOM_ENTRY_COMPLETE,
161     STATE_ADD_TO_ENTRY,
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
186   };
187
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
193   // in the middle.
194   enum TransactionPattern {
195     PATTERN_UNDEFINED,
196     PATTERN_NOT_COVERED,
197     PATTERN_ENTRY_NOT_CACHED,
198     PATTERN_ENTRY_USED,
199     PATTERN_ENTRY_VALIDATED,
200     PATTERN_ENTRY_UPDATED,
201     PATTERN_ENTRY_CANT_CONDITIONALIZE,
202     PATTERN_MAX,
203   };
204
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);
208
209   // This will trigger the completion callback if appropriate.
210   int HandleResult(int rv);
211
212   // Runs the state transition loop.
213   int DoLoop(int result);
214
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.
218   int DoGetBackend();
219   int DoGetBackendComplete(int result);
220   int DoSendRequest();
221   int DoSendRequestComplete(int result);
222   int DoSuccessfulSendRequest();
223   int DoNetworkRead();
224   int DoNetworkReadComplete(int result);
225   int DoInitEntry();
226   int DoOpenEntry();
227   int DoOpenEntryComplete(int result);
228   int DoCreateEntry();
229   int DoCreateEntryComplete(int result);
230   int DoDoomEntry();
231   int DoDoomEntryComplete(int result);
232   int DoAddToEntry();
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);
257
258   // Sets request_ and fields derived from it.
259   void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
260
261   // Returns true if the request should be handled exclusively by the network
262   // layer (skipping the cache entirely).
263   bool ShouldPassThrough();
264
265   // Called to begin reading from the cache.  Returns network error code.
266   int BeginCacheRead();
267
268   // Called to begin validating the cache entry.  Returns network error code.
269   int BeginCacheValidation();
270
271   // Called to begin validating an entry that stores partial content.  Returns
272   // a network error code.
273   int BeginPartialCacheValidation();
274
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();
278
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();
284
285   // Called to restart a network transaction after an error.  Returns network
286   // error code.
287   int RestartNetworkRequest();
288
289   // Called to restart a network transaction with a client certificate.
290   // Returns network error code.
291   int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
292
293   // Called to restart a network transaction with authentication credentials.
294   // Returns network error code.
295   int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
296
297   // Called to determine if we need to validate the cache entry before using it.
298   bool RequiresValidation();
299
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();
303
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
306   // partial entry.
307   bool ValidatePartialResponse();
308
309   // Handles a response validation error by bypassing the cache.
310   void IgnoreRangeRequest();
311
312   // Changes the response code of a range request to be 416 (Requested range not
313   // satisfiable).
314   void FailRangeRequest();
315
316   // Setups the transaction for reading from the cache entry.
317   int SetupEntryForRead();
318
319   // Reads data from the network.
320   int ReadFromNetwork(IOBuffer* data, int data_len);
321
322   // Reads data from the cache entry.
323   int ReadFromEntry(IOBuffer* data, int data_len);
324
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);
330
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);
334
335   // Called to append response data to the cache entry.  Returns a network error
336   // code.
337   int AppendResponseDataToEntry(IOBuffer* data, int data_len,
338                                 const CompletionCallback& callback);
339
340   // Called when we are done writing to the cache entry.
341   void DoneWritingToEntry(bool success);
342
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);
347
348   // Deletes the current partial cache entry (sparse), and optionally removes
349   // the control object (partial_).
350   void DoomPartialEntry(bool delete_object);
351
352   // Performs the needed work after receiving data from the network, when
353   // working with range requests.
354   int DoPartialNetworkReadCompleted(int result);
355
356   // Performs the needed work after receiving data from the cache, when
357   // working with range requests.
358   int DoPartialCacheReadCompleted(int result);
359
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();
364
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();
368
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);
373
374   // Called to signal completion of asynchronous IO.
375   void OnIOComplete(int result);
376
377   void ReportCacheActionStart();
378   void ReportCacheActionFinish();
379   void ReportNetworkActionStart();
380   void ReportNetworkActionFinish();
381   void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
382   void RecordHistograms();
383
384   State next_state_;
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_;
402   Mode mode_;
403   State target_state_;
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.
411   bool done_reading_;
412   bool vary_mismatch_;  // The request doesn't match the stored vary data.
413   bool couldnt_conditionalize_request_;
414   scoped_refptr<IOBuffer> read_buf_;
415   int io_buf_len_;
416   int read_offset_;
417   int effective_load_flags_;
418   int write_len_;
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_;
423
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_;
429
430   HttpTransactionDelegate* transaction_delegate_;
431
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_;
436 };
437
438 }  // namespace net
439
440 #endif  // NET_HTTP_HTTP_CACHE_TRANSACTION_H_