• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 <stddef.h>
12 #include <stdint.h>
13 
14 #include <memory>
15 #include <string>
16 
17 #include "base/functional/callback.h"
18 #include "base/memory/raw_ptr.h"
19 #include "base/memory/raw_ptr_exclusion.h"
20 #include "base/memory/scoped_refptr.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/time/time.h"
23 #include "net/base/completion_once_callback.h"
24 #include "net/base/completion_repeating_callback.h"
25 #include "net/base/io_buffer.h"
26 #include "net/base/ip_endpoint.h"
27 #include "net/base/load_states.h"
28 #include "net/base/net_error_details.h"
29 #include "net/base/net_errors.h"
30 #include "net/base/request_priority.h"
31 #include "net/http/http_cache.h"
32 #include "net/http/http_request_headers.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/http/http_response_info.h"
35 #include "net/http/http_transaction.h"
36 #include "net/http/partial_data.h"
37 #include "net/log/net_log_with_source.h"
38 #include "net/socket/connection_attempts.h"
39 #include "net/websockets/websocket_handshake_stream_base.h"
40 
41 namespace net {
42 
43 class PartialData;
44 struct HttpRequestInfo;
45 struct LoadTimingInfo;
46 class SSLPrivateKey;
47 
48 // This is the transaction that is returned by the HttpCache transaction
49 // factory.
50 class NET_EXPORT_PRIVATE HttpCache::Transaction : public HttpTransaction {
51  public:
52   // The transaction has the following modes, which apply to how it may access
53   // its cache entry.
54   //
55   //  o If the mode of the transaction is NONE, then it is in "pass through"
56   //    mode and all methods just forward to the inner network transaction.
57   //
58   //  o If the mode of the transaction is only READ, then it may only read from
59   //    the cache entry.
60   //
61   //  o If the mode of the transaction is only WRITE, then it may only write to
62   //    the cache entry.
63   //
64   //  o If the mode of the transaction is READ_WRITE, then the transaction may
65   //    optionally modify the cache entry (e.g., possibly corresponding to
66   //    cache validation).
67   //
68   //  o If the mode of the transaction is UPDATE, then the transaction may
69   //    update existing cache entries, but will never create a new entry or
70   //    respond using the entry read from the cache.
71   enum Mode {
72     NONE            = 0,
73     READ_META       = 1 << 0,
74     READ_DATA       = 1 << 1,
75     READ            = READ_META | READ_DATA,
76     WRITE           = 1 << 2,
77     READ_WRITE      = READ | WRITE,
78     UPDATE          = READ_META | WRITE,  // READ_WRITE & ~READ_DATA
79   };
80 
81   Transaction(RequestPriority priority,
82               HttpCache* cache);
83 
84   Transaction(const Transaction&) = delete;
85   Transaction& operator=(const Transaction&) = delete;
86 
87   ~Transaction() override;
88 
89   // Virtual so it can be extended for testing.
90   virtual Mode mode() const;
91 
method()92   const std::string& method() const { return method_; }
93 
key()94   const std::string& key() const { return cache_key_; }
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 
SetIOCallBackForTest(CompletionRepeatingCallback cb)104   void SetIOCallBackForTest(CompletionRepeatingCallback cb) {
105     io_callback_ = cb;
106   }
107 
108   // Returns the IO callback specific to HTTPCache callbacks. This is done
109   // indirectly so the callbacks can be replaced when testing.
110   // TODO(https://crbug.com/1454228/): Find a cleaner way to do this so the
111   // callback can be called directly.
cache_io_callback()112   const CompletionRepeatingCallback& cache_io_callback() {
113     return cache_io_callback_;
114   }
SetCacheIOCallBackForTest(CompletionRepeatingCallback cb)115   void SetCacheIOCallBackForTest(CompletionRepeatingCallback cb) {
116     cache_io_callback_ = cb;
117   }
118 
119   const NetLogWithSource& net_log() const;
120 
121   // Bypasses the cache lock whenever there is lock contention.
BypassLockForTest()122   void BypassLockForTest() {
123     bypass_lock_for_test_ = true;
124   }
125 
BypassLockAfterHeadersForTest()126   void BypassLockAfterHeadersForTest() {
127     bypass_lock_after_headers_for_test_ = true;
128   }
129 
130   // Generates a failure when attempting to conditionalize a network request.
FailConditionalizationForTest()131   void FailConditionalizationForTest() {
132     fail_conditionalization_for_test_ = true;
133   }
134 
135   // HttpTransaction methods:
136   int Start(const HttpRequestInfo* request_info,
137             CompletionOnceCallback callback,
138             const NetLogWithSource& net_log) override;
139   int RestartIgnoringLastError(CompletionOnceCallback callback) override;
140   int RestartWithCertificate(scoped_refptr<X509Certificate> client_cert,
141                              scoped_refptr<SSLPrivateKey> client_private_key,
142                              CompletionOnceCallback callback) override;
143   int RestartWithAuth(const AuthCredentials& credentials,
144                       CompletionOnceCallback callback) override;
145   bool IsReadyToRestartForAuth() override;
146   int Read(IOBuffer* buf,
147            int buf_len,
148            CompletionOnceCallback callback) override;
149   void StopCaching() override;
150   int64_t GetTotalReceivedBytes() const override;
151   int64_t GetTotalSentBytes() const override;
152   void DoneReading() override;
153   const HttpResponseInfo* GetResponseInfo() const override;
154   LoadState GetLoadState() const override;
155   void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
156   bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
157   bool GetRemoteEndpoint(IPEndPoint* endpoint) const override;
158   void PopulateNetErrorDetails(NetErrorDetails* details) const override;
159   void SetPriority(RequestPriority priority) override;
160   void SetWebSocketHandshakeStreamCreateHelper(
161       WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
162   void SetBeforeNetworkStartCallback(
163       BeforeNetworkStartCallback callback) override;
164   void SetConnectedCallback(const ConnectedCallback& callback) override;
165   void SetRequestHeadersCallback(RequestHeadersCallback callback) override;
166   void SetResponseHeadersCallback(ResponseHeadersCallback callback) override;
167   void SetEarlyResponseHeadersCallback(
168       ResponseHeadersCallback callback) override;
169   void SetModifyRequestHeadersCallback(
170       base::RepeatingCallback<void(net::HttpRequestHeaders*)> callback)
171       override;
172   void SetIsSharedDictionaryReadAllowedCallback(
173       base::RepeatingCallback<bool()> callback) override;
174   int ResumeNetworkStart() override;
175   ConnectionAttempts GetConnectionAttempts() const override;
176   void CloseConnectionOnDestruction() override;
177 
178   // Invoked when parallel validation cannot proceed due to response failure
179   // and this transaction needs to be restarted.
180   void SetValidatingCannotProceed();
181 
182   // Invoked to remove the association between a transaction waiting to be
183   // added to an entry and the entry.
ResetCachePendingState()184   void ResetCachePendingState() { cache_pending_ = false; }
185 
priority()186   RequestPriority priority() const { return priority_; }
partial()187   PartialData* partial() { return partial_.get(); }
is_truncated()188   bool is_truncated() { return truncated_; }
189 
190   // Invoked when this writer transaction is about to be removed from entry.
191   // If result is an error code, a future Read should fail with |result|.
192   void WriterAboutToBeRemovedFromEntry(int result);
193 
194   // Invoked when this transaction is about to become a reader because the cache
195   // entry has finished writing.
196   void WriteModeTransactionAboutToBecomeReader();
197 
198   // Add time spent writing data in the disk cache. Used for histograms.
199   void AddDiskCacheWriteTime(base::TimeDelta elapsed);
200 
201  private:
202   static const size_t kNumValidationHeaders = 2;
203   // Helper struct to pair a header name with its value, for
204   // headers used to validate cache entries.
205   struct ValidationHeaders {
206     ValidationHeaders() = default;
207 
208     std::string values[kNumValidationHeaders];
ResetValidationHeaders209     void Reset() {
210       initialized = false;
211       for (auto& value : values)
212         value.clear();
213     }
214     bool initialized = false;
215   };
216 
217   struct NetworkTransactionInfo {
218     NetworkTransactionInfo();
219 
220     NetworkTransactionInfo(const NetworkTransactionInfo&) = delete;
221     NetworkTransactionInfo& operator=(const NetworkTransactionInfo&) = delete;
222 
223     ~NetworkTransactionInfo();
224 
225     // Load timing information for the last network request, if any. Set in the
226     // 304 and 206 response cases, as the network transaction may be destroyed
227     // before the caller requests load timing information.
228     std::unique_ptr<LoadTimingInfo> old_network_trans_load_timing;
229     int64_t total_received_bytes = 0;
230     int64_t total_sent_bytes = 0;
231     ConnectionAttempts old_connection_attempts;
232     IPEndPoint old_remote_endpoint;
233   };
234 
235   enum State {
236     STATE_UNSET,
237 
238     // Normally, states are traversed in approximately this order.
239     STATE_NONE,
240     STATE_GET_BACKEND,
241     STATE_GET_BACKEND_COMPLETE,
242     STATE_INIT_ENTRY,
243     STATE_OPEN_OR_CREATE_ENTRY,
244     STATE_OPEN_OR_CREATE_ENTRY_COMPLETE,
245     STATE_DOOM_ENTRY,
246     STATE_DOOM_ENTRY_COMPLETE,
247     STATE_CREATE_ENTRY,
248     STATE_CREATE_ENTRY_COMPLETE,
249     STATE_ADD_TO_ENTRY,
250     STATE_ADD_TO_ENTRY_COMPLETE,
251     STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE,
252     STATE_CACHE_READ_RESPONSE,
253     STATE_CACHE_READ_RESPONSE_COMPLETE,
254     STATE_WRITE_UPDATED_PREFETCH_RESPONSE,
255     STATE_WRITE_UPDATED_PREFETCH_RESPONSE_COMPLETE,
256     STATE_CACHE_DISPATCH_VALIDATION,
257     STATE_CACHE_QUERY_DATA,
258     STATE_CACHE_QUERY_DATA_COMPLETE,
259     STATE_START_PARTIAL_CACHE_VALIDATION,
260     STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
261     STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT,
262     STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT_COMPLETE,
263     STATE_CONNECTED_CALLBACK,
264     STATE_CONNECTED_CALLBACK_COMPLETE,
265     STATE_SETUP_ENTRY_FOR_READ,
266     STATE_SEND_REQUEST,
267     STATE_SEND_REQUEST_COMPLETE,
268     STATE_SUCCESSFUL_SEND_REQUEST,
269     STATE_UPDATE_CACHED_RESPONSE,
270     STATE_CACHE_WRITE_UPDATED_RESPONSE,
271     STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE,
272     STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
273     STATE_OVERWRITE_CACHED_RESPONSE,
274     STATE_CACHE_WRITE_RESPONSE,
275     STATE_CACHE_WRITE_RESPONSE_COMPLETE,
276     STATE_TRUNCATE_CACHED_DATA,
277     STATE_TRUNCATE_CACHED_DATA_COMPLETE,
278     STATE_TRUNCATE_CACHED_METADATA,
279     STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
280     STATE_PARTIAL_HEADERS_RECEIVED,
281     STATE_HEADERS_PHASE_CANNOT_PROCEED,
282     STATE_FINISH_HEADERS,
283     STATE_FINISH_HEADERS_COMPLETE,
284 
285     // These states are entered from Read.
286     STATE_NETWORK_READ_CACHE_WRITE,
287     STATE_NETWORK_READ_CACHE_WRITE_COMPLETE,
288     STATE_CACHE_READ_DATA,
289     STATE_CACHE_READ_DATA_COMPLETE,
290     // These states are entered if the request should be handled exclusively
291     // by the network layer (skipping the cache entirely).
292     STATE_NETWORK_READ,
293     STATE_NETWORK_READ_COMPLETE,
294   };
295 
296   // Used for categorizing validation triggers in histograms.
297   // NOTE: This enumeration is used in histograms, so please do not add entries
298   // in the middle.
299   enum ValidationCause {
300     VALIDATION_CAUSE_UNDEFINED,
301     VALIDATION_CAUSE_VARY_MISMATCH,
302     VALIDATION_CAUSE_VALIDATE_FLAG,
303     VALIDATION_CAUSE_STALE,
304     VALIDATION_CAUSE_ZERO_FRESHNESS,
305     VALIDATION_CAUSE_MAX
306   };
307 
308   enum MemoryEntryDataHints {
309     // If this hint is set, the caching headers indicate we can't do anything
310     // with this entry (unless we are ignoring them thanks to a loadflag),
311     // i.e. it's expired and has nothing that permits validations.
312     HINT_UNUSABLE_PER_CACHING_HEADERS = (1 << 0),
313   };
314 
315   // Runs the state transition loop. Resets and calls |callback_| on exit,
316   // unless the return value is ERR_IO_PENDING.
317   int DoLoop(int result);
318 
319   // Each of these methods corresponds to a State value.  If there is an
320   // argument, the value corresponds to the return of the previous state or
321   // corresponding callback.
322   int DoGetBackend();
323   int DoGetBackendComplete(int result);
324   int DoInitEntry();
325   int DoOpenOrCreateEntry();
326   int DoOpenOrCreateEntryComplete(int result);
327   int DoDoomEntry();
328   int DoDoomEntryComplete(int result);
329   int DoCreateEntry();
330   int DoCreateEntryComplete(int result);
331   int DoAddToEntry();
332   int DoAddToEntryComplete(int result);
333   int DoDoneHeadersAddToEntryComplete(int result);
334   int DoCacheReadResponse();
335   int DoCacheReadResponseComplete(int result);
336   int DoCacheWriteUpdatedPrefetchResponse(int result);
337   int DoCacheWriteUpdatedPrefetchResponseComplete(int result);
338   int DoCacheDispatchValidation();
339   int DoCacheQueryData();
340   int DoCacheQueryDataComplete(int result);
341   int DoCacheUpdateStaleWhileRevalidateTimeout();
342   int DoCacheUpdateStaleWhileRevalidateTimeoutComplete(int result);
343   int DoConnectedCallback();
344   int DoConnectedCallbackComplete(int result);
345   int DoSetupEntryForRead();
346   int DoStartPartialCacheValidation();
347   int DoCompletePartialCacheValidation(int result);
348   int DoSendRequest();
349   int DoSendRequestComplete(int result);
350   int DoSuccessfulSendRequest();
351   int DoUpdateCachedResponse();
352   int DoCacheWriteUpdatedResponse();
353   int DoCacheWriteUpdatedResponseComplete(int result);
354   int DoUpdateCachedResponseComplete(int result);
355   int DoOverwriteCachedResponse();
356   int DoCacheWriteResponse();
357   int DoCacheWriteResponseComplete(int result);
358   int DoTruncateCachedData();
359   int DoTruncateCachedDataComplete(int result);
360   int DoTruncateCachedMetadata();
361   int DoTruncateCachedMetadataComplete(int result);
362   int DoPartialHeadersReceived();
363   int DoHeadersPhaseCannotProceed(int result);
364   int DoFinishHeaders(int result);
365   int DoFinishHeadersComplete(int result);
366   int DoNetworkReadCacheWrite();
367   int DoNetworkReadCacheWriteComplete(int result);
368   int DoCacheReadData();
369   int DoCacheReadDataComplete(int result);
370   int DoNetworkRead();
371   int DoNetworkReadComplete(int result);
372 
373   // Adds time out handling while waiting to be added to entry or after headers
374   // phase is complete.
375   void AddCacheLockTimeoutHandler(ActiveEntry* entry);
376 
377   // Sets request_ and fields derived from it.
378   void SetRequest(const NetLogWithSource& net_log);
379 
380   // Returns true if the request should be handled exclusively by the network
381   // layer (skipping the cache entirely).
382   bool ShouldPassThrough();
383 
384   // Called to begin reading from the cache.  Returns network error code.
385   int BeginCacheRead();
386 
387   // Called to begin validating the cache entry.  Returns network error code.
388   int BeginCacheValidation();
389 
390   // Called to begin validating an entry that stores partial content.  Returns
391   // a network error code.
392   int BeginPartialCacheValidation();
393 
394   // Validates the entry headers against the requested range and continues with
395   // the validation of the rest of the entry.  Returns a network error code.
396   int ValidateEntryHeadersAndContinue();
397 
398   // Returns whether the current externally conditionalized request's validation
399   // headers match the current cache entry's headers.
400   bool ExternallyConditionalizedValidationHeadersMatchEntry() const;
401 
402   // Called to start requests which were given an "if-modified-since" or
403   // "if-none-match" validation header by the caller (NOT when the request was
404   // conditionalized internally in response to LOAD_VALIDATE_CACHE).
405   // Returns a network error code.
406   int BeginExternallyConditionalizedRequest();
407 
408   // Called to restart a network transaction after an error.  Returns network
409   // error code.
410   int RestartNetworkRequest();
411 
412   // Called to restart a network transaction with a client certificate.
413   // Returns network error code.
414   int RestartNetworkRequestWithCertificate(
415       scoped_refptr<X509Certificate> client_cert,
416       scoped_refptr<SSLPrivateKey> client_private_key);
417 
418   // Called to restart a network transaction with authentication credentials.
419   // Returns network error code.
420   int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
421 
422   // Called to determine if we need to validate the cache entry before using it,
423   // and whether the validation should be synchronous or asynchronous.
424   ValidationType RequiresValidation();
425 
426   // Called to make the request conditional (to ask the server if the cached
427   // copy is valid).  Returns true if able to make the request conditional.
428   bool ConditionalizeRequest();
429 
430   // Determines if saved response permits conditionalization, and extracts
431   // etag/last-modified values. Only depends on |response_.headers|.
432   // |*etag_value| and |*last_modified_value| will be set if true is returned,
433   // but may also be modified in other cases.
434   bool IsResponseConditionalizable(std::string* etag_value,
435                                    std::string* last_modified_value) const;
436 
437   // Returns true if |method_| indicates that we should only try to open an
438   // entry and not attempt to create.
439   bool ShouldOpenOnlyMethods() const;
440 
441   // Returns true if the resource info MemoryEntryDataHints bit flags in
442   // |in_memory_info| and the current request & load flags suggest that
443   // the cache entry in question is not actually usable for HTTP
444   // (i.e. already expired, and nothing is forcing us to disregard that).
445   bool MaybeRejectBasedOnEntryInMemoryData(uint8_t in_memory_info);
446 
447   // Returns true if response_ is such that, if saved to cache, it would only
448   // be usable if load flags asked us to ignore caching headers.
449   // (return value of false makes no statement as to suitability of the entry).
450   bool ComputeUnusablePerCachingHeaders();
451 
452   // Makes sure that a 206 response is expected.  Returns true on success.
453   // On success, handling_206_ will be set to true if we are processing a
454   // partial entry.
455   bool ValidatePartialResponse();
456 
457   // Handles a response validation error by bypassing the cache.
458   void IgnoreRangeRequest();
459 
460   // Fixes the response headers to match expectations for a HEAD request.
461   void FixHeadersForHead();
462 
463   // Called to write a response to the cache entry. |truncated| indicates if the
464   // entry should be marked as incomplete.
465   int WriteResponseInfoToEntry(const HttpResponseInfo& response,
466                                bool truncated);
467 
468   // Helper function, should be called with result of WriteResponseInfoToEntry
469   // (or the result of the callback, when WriteResponseInfoToEntry returns
470   // ERR_IO_PENDING). Calls DoneWithEntry if |result| is not the right
471   // number of bytes. It is expected that the state that calls this will
472   // return whatever net error code this function returns, which currently
473   // is always "OK".
474   int OnWriteResponseInfoToEntryComplete(int result);
475 
476   // Configures the transaction to read from the network and stop writing to the
477   // entry. It will release the entry if possible. Returns true if caching could
478   // be stopped successfully. It will not be stopped if there are multiple
479   // transactions writing to the cache simultaneously.
480   bool StopCachingImpl(bool success);
481 
482   // Informs the HttpCache that this transaction is done with the entry and
483   // changes the mode to NONE. Set |entry_is_complete| to false if the
484   // transaction has not yet finished fully writing or reading the request
485   // to/from the entry. If |entry_is_complete| is false the result may be either
486   // a truncated or a doomed entry based on whether the stored response can be
487   // resumed or not.
488   void DoneWithEntry(bool entry_is_complete);
489 
490   // Dooms the given entry so that it will not be re-used for other requests,
491   // then calls `DoneWithEntry()`.
492   //
493   // This happens when network conditions have changed since the entry was
494   // cached, which results in deterministic failures when trying to use the
495   // cache entry. In order to let future requests succeed, the cache entry
496   // should be doomed.
497   void DoomInconsistentEntry();
498 
499   // Returns an error to signal the caller that the current read failed. The
500   // current operation |result| is also logged. If |restart| is true, the
501   // transaction should be restarted.
502   int OnCacheReadError(int result, bool restart);
503 
504   // Called when the cache lock timeout fires.
505   void OnCacheLockTimeout(base::TimeTicks start_time);
506 
507   // Deletes the current partial cache entry (sparse), and optionally removes
508   // the control object (partial_).
509   void DoomPartialEntry(bool delete_object);
510 
511   // Performs the needed work after receiving data from the network, when
512   // working with range requests.
513   int DoPartialNetworkReadCompleted(int result);
514 
515   // Performs the needed work after receiving data from the cache, when
516   // working with range requests.
517   int DoPartialCacheReadCompleted(int result);
518 
519   // Restarts this transaction after deleting the cached data. It is meant to
520   // be used when the current request cannot be fulfilled due to conflicts
521   // between the byte range request and the cached entry.
522   int DoRestartPartialRequest();
523 
524   // Resets the relavant internal state to remove traces of internal processing
525   // related to range requests. Deletes |partial_| if |delete_object| is true.
526   void ResetPartialState(bool delete_object);
527 
528   // Resets |network_trans_|, which must be non-NULL.  Also updates
529   // |old_network_trans_load_timing_|, which must be NULL when this is called.
530   void ResetNetworkTransaction();
531 
532   // Returns the currently active network transaction.
533   const HttpTransaction* network_transaction() const;
534   HttpTransaction* network_transaction();
535 
536   // Returns the network transaction from |this| or from writers only if it was
537   // moved from |this| to writers. This is so that statistics of the network
538   // transaction are not attributed to any other writer member.
539   const HttpTransaction* GetOwnedOrMovedNetworkTransaction() const;
540 
541   // Returns true if we should bother attempting to resume this request if it is
542   // aborted while in progress. If |has_data| is true, the size of the stored
543   // data is considered for the result.
544   bool CanResume(bool has_data);
545 
546   // Setter for response_ and auth_response_. It updates its cache entry status,
547   // if needed.
548   void SetResponse(const HttpResponseInfo& new_response);
549   void SetAuthResponse(const HttpResponseInfo& new_response);
550 
551   void UpdateCacheEntryStatus(
552       HttpResponseInfo::CacheEntryStatus new_cache_entry_status);
553 
554   // Sets the response.cache_entry_status to the current cache_entry_status_.
555   void SyncCacheEntryStatusToResponse();
556 
557   // Logs histograms for this transaction. It is invoked when the transaction is
558   // either complete or is done writing to entry and will continue in
559   // network-only mode.
560   void RecordHistograms();
561 
562   // Returns true if this transaction is a member of entry_->writers.
563   bool InWriters() const;
564 
565   // Called to signal completion of asynchronous IO. Note that this callback is
566   // used in the conventional sense where one layer calls the callback of the
567   // layer above it e.g. this callback gets called from the network transaction
568   // layer. In addition, it is also used for HttpCache layer to let this
569   // transaction know when it is out of a queued state in ActiveEntry and can
570   // continue its processing.
571   void OnIOComplete(int result);
572 
573   // Called to signal completion of an asynchronous HTTPCache operation. It
574   // uses a separate callback from OnIoComplete so that cache transaction
575   // operations and network IO can be run in parallel.
576   void OnCacheIOComplete(int result);
577 
578   // When in a DoLoop, use this to set the next state as it verifies that the
579   // state isn't set twice.
580   void TransitionToState(State state);
581 
582   // Helper function to decide the next reading state.
583   int TransitionToReadingState();
584 
585   // Saves network transaction info using |transaction|.
586   void SaveNetworkTransactionInfo(const HttpTransaction& transaction);
587 
588   // Determines whether caching should be disabled for a response, given its
589   // headers.
590   bool ShouldDisableCaching(const HttpResponseHeaders& headers) const;
591 
592   // 304 revalidations of resources that set security headers and that get
593   // forwarded might need to set these headers again to avoid being blocked.
594   void UpdateSecurityHeadersBeforeForwarding();
595 
596   enum class DiskCacheAccessType {
597     kRead,
598     kWrite,
599   };
600   void BeginDiskCacheAccessTimeCount();
601   void EndDiskCacheAccessTimeCount(DiskCacheAccessType type);
602 
603   State next_state_{STATE_NONE};
604 
605   // Set when a HTTPCache transaction is pending in parallel with other IO.
606   bool waiting_for_cache_io_ = false;
607 
608   // If a pending async HTTPCache transaction takes longer than the parallel
609   // Network IO, this will store the result of the Network IO operation until
610   // the cache transaction completes (or times out).
611   absl::optional<int> pending_io_result_ = absl::nullopt;
612 
613   // Used for tracing.
614   const uint64_t trace_id_;
615 
616   // Initial request with which Start() was invoked.
617   raw_ptr<const HttpRequestInfo> initial_request_ = nullptr;
618 
619   // `custom_request_` is assigned to `request_` after allocation. It must be
620   // declared before `request_` so that it will be destroyed afterwards to
621   // prevent that pointer from dangling.
622   std::unique_ptr<HttpRequestInfo> custom_request_;
623 
624   raw_ptr<const HttpRequestInfo> request_ = nullptr;
625 
626   std::string method_;
627   RequestPriority priority_;
628   NetLogWithSource net_log_;
629   HttpRequestHeaders request_headers_copy_;
630   // If extra_headers specified a "if-modified-since" or "if-none-match",
631   // |external_validation_| contains the value of those headers.
632   ValidationHeaders external_validation_;
633   base::WeakPtr<HttpCache> cache_;
634   raw_ptr<HttpCache::ActiveEntry, AcrossTasksDanglingUntriaged> entry_ =
635       nullptr;
636   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
637   // #addr-of
638   RAW_PTR_EXCLUSION HttpCache::ActiveEntry* new_entry_ = nullptr;
639   std::unique_ptr<HttpTransaction> network_trans_;
640   CompletionOnceCallback callback_;  // Consumer's callback.
641   HttpResponseInfo response_;
642   HttpResponseInfo auth_response_;
643 
644   // This is only populated when we want to modify a prefetch request in some
645   // way for future transactions, while leaving it untouched for the current
646   // one. DoCacheReadResponseComplete() sets this to a copy of |response_|,
647   // and modifies the members for future transactions. Then,
648   // WriteResponseInfoToEntry() writes |updated_prefetch_response_| to the cache
649   // entry if it is populated, or |response_| otherwise. Finally,
650   // WriteResponseInfoToEntry() resets this to absl::nullopt.
651   std::unique_ptr<HttpResponseInfo> updated_prefetch_response_;
652 
653   raw_ptr<const HttpResponseInfo, AcrossTasksDanglingUntriaged> new_response_ =
654       nullptr;
655   std::string cache_key_;
656   Mode mode_ = NONE;
657   bool reading_ = false;          // We are already reading. Never reverts to
658                                   // false once set.
659   bool invalid_range_ = false;    // We may bypass the cache for this request.
660   bool truncated_ = false;        // We don't have all the response data.
661   bool is_sparse_ = false;        // The data is stored in sparse byte ranges.
662   bool range_requested_ = false;  // The user requested a byte range.
663   bool handling_206_ = false;     // We must deal with this 206 response.
664   bool cache_pending_ = false;    // We are waiting for the HttpCache.
665 
666   // Headers have been received from the network and it's not a match with the
667   // existing entry.
668   bool done_headers_create_new_entry_ = false;
669 
670   bool vary_mismatch_ = false;  // The request doesn't match the stored vary
671                                 // data.
672   bool couldnt_conditionalize_request_ = false;
673   bool bypass_lock_for_test_ = false;  // A test is exercising the cache lock.
674   bool bypass_lock_after_headers_for_test_ = false;  // A test is exercising the
675                                                      // cache lock.
676   bool fail_conditionalization_for_test_ =
677       false;  // Fail ConditionalizeRequest.
678 
679   scoped_refptr<IOBuffer> read_buf_;
680 
681   // Length of the buffer passed in Read().
682   int read_buf_len_ = 0;
683 
684   int io_buf_len_ = 0;
685   int read_offset_ = 0;
686   int effective_load_flags_ = 0;
687   std::unique_ptr<PartialData> partial_;  // We are dealing with range requests.
688   CompletionRepeatingCallback io_callback_;
689   CompletionRepeatingCallback cache_io_callback_;  // cache-specific IO callback
690   base::RepeatingCallback<bool()> is_shared_dictionary_read_allowed_callback_;
691 
692   // Error code to be returned from a subsequent Read call if shared writing
693   // failed in a separate transaction.
694   int shared_writing_error_ = OK;
695 
696   // Members used to track data for histograms.
697   // This cache_entry_status_ takes precedence over
698   // response_.cache_entry_status. In fact, response_.cache_entry_status must be
699   // kept in sync with cache_entry_status_ (via SetResponse and
700   // UpdateCacheEntryStatus).
701   HttpResponseInfo::CacheEntryStatus cache_entry_status_ =
702       HttpResponseInfo::CacheEntryStatus::ENTRY_UNDEFINED;
703   ValidationCause validation_cause_ = VALIDATION_CAUSE_UNDEFINED;
704   base::TimeTicks entry_lock_waiting_since_;
705   base::TimeTicks first_cache_access_since_;
706   base::TimeTicks send_request_since_;
707   base::TimeTicks read_headers_since_;
708   base::Time open_entry_last_used_;
709   base::TimeTicks last_disk_cache_access_start_time_;
710   base::TimeDelta total_disk_cache_read_time_;
711   base::TimeDelta total_disk_cache_write_time_;
712   bool recorded_histograms_ = false;
713   bool has_opened_or_created_entry_ = false;
714   bool record_entry_open_or_creation_time_ = false;
715 
716   NetworkTransactionInfo network_transaction_info_;
717 
718   // True if this transaction created the network transaction that is now being
719   // used by writers. This is used to check that only this transaction should
720   // account for the network bytes and other statistics of the network
721   // transaction.
722   // TODO(shivanisha) Note that if this transaction dies mid-way and there are
723   // other writer transactions, no transaction then accounts for those
724   // statistics.
725   bool moved_network_transaction_to_writers_ = false;
726 
727   // The helper object to use to create WebSocketHandshakeStreamBase
728   // objects. Only relevant when establishing a WebSocket connection.
729   // This is passed to the underlying network transaction. It is stored here in
730   // case the transaction does not exist yet.
731   raw_ptr<WebSocketHandshakeStreamBase::CreateHelper>
732       websocket_handshake_stream_base_create_helper_ = nullptr;
733 
734   BeforeNetworkStartCallback before_network_start_callback_;
735   ConnectedCallback connected_callback_;
736   RequestHeadersCallback request_headers_callback_;
737   ResponseHeadersCallback early_response_headers_callback_;
738   ResponseHeadersCallback response_headers_callback_;
739 
740   // True if the Transaction is currently processing the DoLoop.
741   bool in_do_loop_ = false;
742 
743   base::WeakPtrFactory<Transaction> weak_factory_{this};
744 };
745 
746 }  // namespace net
747 
748 #endif  // NET_HTTP_HTTP_CACHE_TRANSACTION_H_
749