xref: /aosp_15_r20/external/cronet/net/http/http_cache_transaction.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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, HttpCache* cache);
82 
83   Transaction(const Transaction&) = delete;
84   Transaction& operator=(const Transaction&) = delete;
85 
86   ~Transaction() override;
87 
88   // Virtual so it can be extended for testing.
89   virtual Mode mode() const;
90 
method()91   const std::string& method() const { return method_; }
92 
key()93   const std::string& key() const { return cache_key_; }
94 
95   // Returns the LoadState of the writer transaction of a given ActiveEntry. In
96   // other words, returns the LoadState of this transaction without asking the
97   // http cache, because this transaction should be the one currently writing
98   // to the cache entry.
99   LoadState GetWriterLoadState() const;
100 
SetIOCallBackForTest(CompletionRepeatingCallback cb)101   void SetIOCallBackForTest(CompletionRepeatingCallback cb) {
102     io_callback_ = cb;
103   }
104 
105   // Returns the IO callback specific to HTTPCache callbacks. This is done
106   // indirectly so the callbacks can be replaced when testing.
107   // TODO(https://crbug.com/1454228/): Find a cleaner way to do this so the
108   // callback can be called directly.
cache_io_callback()109   const CompletionRepeatingCallback& cache_io_callback() {
110     return cache_io_callback_;
111   }
SetCacheIOCallBackForTest(CompletionRepeatingCallback cb)112   void SetCacheIOCallBackForTest(CompletionRepeatingCallback cb) {
113     cache_io_callback_ = cb;
114   }
115 
116   const NetLogWithSource& net_log() const;
117 
118   // Bypasses the cache lock whenever there is lock contention.
BypassLockForTest()119   void BypassLockForTest() { bypass_lock_for_test_ = true; }
120 
BypassLockAfterHeadersForTest()121   void BypassLockAfterHeadersForTest() {
122     bypass_lock_after_headers_for_test_ = true;
123   }
124 
125   // Generates a failure when attempting to conditionalize a network request.
FailConditionalizationForTest()126   void FailConditionalizationForTest() {
127     fail_conditionalization_for_test_ = true;
128   }
129 
130   // HttpTransaction methods:
131   int Start(const HttpRequestInfo* request_info,
132             CompletionOnceCallback callback,
133             const NetLogWithSource& net_log) override;
134   int RestartIgnoringLastError(CompletionOnceCallback callback) override;
135   int RestartWithCertificate(scoped_refptr<X509Certificate> client_cert,
136                              scoped_refptr<SSLPrivateKey> client_private_key,
137                              CompletionOnceCallback callback) override;
138   int RestartWithAuth(const AuthCredentials& credentials,
139                       CompletionOnceCallback callback) override;
140   bool IsReadyToRestartForAuth() override;
141   int Read(IOBuffer* buf,
142            int buf_len,
143            CompletionOnceCallback callback) override;
144   void StopCaching() override;
145   int64_t GetTotalReceivedBytes() const override;
146   int64_t GetTotalSentBytes() const override;
147   void DoneReading() override;
148   const HttpResponseInfo* GetResponseInfo() const override;
149   LoadState GetLoadState() const override;
150   void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
151   bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
152   bool GetRemoteEndpoint(IPEndPoint* endpoint) const override;
153   void PopulateNetErrorDetails(NetErrorDetails* details) const override;
154   void SetPriority(RequestPriority priority) override;
155   void SetWebSocketHandshakeStreamCreateHelper(
156       WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
157   void SetBeforeNetworkStartCallback(
158       BeforeNetworkStartCallback callback) override;
159   void SetConnectedCallback(const ConnectedCallback& callback) override;
160   void SetRequestHeadersCallback(RequestHeadersCallback callback) override;
161   void SetResponseHeadersCallback(ResponseHeadersCallback callback) override;
162   void SetEarlyResponseHeadersCallback(
163       ResponseHeadersCallback callback) override;
164   void SetModifyRequestHeadersCallback(
165       base::RepeatingCallback<void(net::HttpRequestHeaders*)> callback)
166       override;
167   void SetIsSharedDictionaryReadAllowedCallback(
168       base::RepeatingCallback<bool()> callback) override;
169   int ResumeNetworkStart() override;
170   ConnectionAttempts GetConnectionAttempts() const override;
171   void CloseConnectionOnDestruction() override;
172   bool IsMdlMatchForMetrics() const override;
173 
174   // Invoked when parallel validation cannot proceed due to response failure
175   // and this transaction needs to be restarted.
176   void SetValidatingCannotProceed();
177 
178   // Invoked to remove the association between a transaction waiting to be
179   // added to an entry and the entry.
ResetCachePendingState()180   void ResetCachePendingState() { cache_pending_ = false; }
181 
priority()182   RequestPriority priority() const { return priority_; }
partial()183   PartialData* partial() { return partial_.get(); }
is_truncated()184   bool is_truncated() { return truncated_; }
185 
186   // Invoked when this writer transaction is about to be removed from entry.
187   // If result is an error code, a future Read should fail with |result|.
188   void WriterAboutToBeRemovedFromEntry(int result);
189 
190   // Invoked when this transaction is about to become a reader because the cache
191   // entry has finished writing.
192   void WriteModeTransactionAboutToBecomeReader();
193 
194   // Add time spent writing data in the disk cache. Used for histograms.
195   void AddDiskCacheWriteTime(base::TimeDelta elapsed);
196 
197  private:
198   static const size_t kNumValidationHeaders = 2;
199   // Helper struct to pair a header name with its value, for
200   // headers used to validate cache entries.
201   struct ValidationHeaders {
202     ValidationHeaders() = default;
203 
204     std::string values[kNumValidationHeaders];
ResetValidationHeaders205     void Reset() {
206       initialized = false;
207       for (auto& value : values) {
208         value.clear();
209       }
210     }
211     bool initialized = false;
212   };
213 
214   struct NetworkTransactionInfo {
215     NetworkTransactionInfo();
216 
217     NetworkTransactionInfo(const NetworkTransactionInfo&) = delete;
218     NetworkTransactionInfo& operator=(const NetworkTransactionInfo&) = delete;
219 
220     ~NetworkTransactionInfo();
221 
222     // Load timing information for the last network request, if any. Set in the
223     // 304 and 206 response cases, as the network transaction may be destroyed
224     // before the caller requests load timing information.
225     std::unique_ptr<LoadTimingInfo> old_network_trans_load_timing;
226     int64_t total_received_bytes = 0;
227     int64_t total_sent_bytes = 0;
228     ConnectionAttempts old_connection_attempts;
229     IPEndPoint old_remote_endpoint;
230     // For metrics. Can be removed when associated histograms are removed.
231     // Records whether any destroyed network transactions' ProxyInfo determined
232     // the request was to a Masked Domain List-covered domain.
233     bool previous_mdl_match_for_metrics = false;
234   };
235 
236   enum State {
237     STATE_UNSET,
238 
239     // Normally, states are traversed in approximately this order.
240     STATE_NONE,
241     STATE_GET_BACKEND,
242     STATE_GET_BACKEND_COMPLETE,
243     STATE_INIT_ENTRY,
244     STATE_OPEN_OR_CREATE_ENTRY,
245     STATE_OPEN_OR_CREATE_ENTRY_COMPLETE,
246     STATE_DOOM_ENTRY,
247     STATE_DOOM_ENTRY_COMPLETE,
248     STATE_CREATE_ENTRY,
249     STATE_CREATE_ENTRY_COMPLETE,
250     STATE_ADD_TO_ENTRY,
251     STATE_ADD_TO_ENTRY_COMPLETE,
252     STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE,
253     STATE_CACHE_READ_RESPONSE,
254     STATE_CACHE_READ_RESPONSE_COMPLETE,
255     STATE_WRITE_UPDATED_PREFETCH_RESPONSE,
256     STATE_WRITE_UPDATED_PREFETCH_RESPONSE_COMPLETE,
257     STATE_CACHE_DISPATCH_VALIDATION,
258     STATE_CACHE_QUERY_DATA,
259     STATE_CACHE_QUERY_DATA_COMPLETE,
260     STATE_START_PARTIAL_CACHE_VALIDATION,
261     STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
262     STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT,
263     STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT_COMPLETE,
264     STATE_CONNECTED_CALLBACK,
265     STATE_CONNECTED_CALLBACK_COMPLETE,
266     STATE_SETUP_ENTRY_FOR_READ,
267     STATE_SEND_REQUEST,
268     STATE_SEND_REQUEST_COMPLETE,
269     STATE_SUCCESSFUL_SEND_REQUEST,
270     STATE_UPDATE_CACHED_RESPONSE,
271     STATE_CACHE_WRITE_UPDATED_RESPONSE,
272     STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE,
273     STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
274     STATE_OVERWRITE_CACHED_RESPONSE,
275     STATE_CACHE_WRITE_RESPONSE,
276     STATE_CACHE_WRITE_RESPONSE_COMPLETE,
277     STATE_TRUNCATE_CACHED_DATA,
278     STATE_TRUNCATE_CACHED_DATA_COMPLETE,
279     STATE_TRUNCATE_CACHED_METADATA,
280     STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
281     STATE_PARTIAL_HEADERS_RECEIVED,
282     STATE_HEADERS_PHASE_CANNOT_PROCEED,
283     STATE_FINISH_HEADERS,
284     STATE_FINISH_HEADERS_COMPLETE,
285 
286     // These states are entered from Read.
287     STATE_NETWORK_READ_CACHE_WRITE,
288     STATE_NETWORK_READ_CACHE_WRITE_COMPLETE,
289     STATE_CACHE_READ_DATA,
290     STATE_CACHE_READ_DATA_COMPLETE,
291     // These states are entered if the request should be handled exclusively
292     // by the network layer (skipping the cache entirely).
293     STATE_NETWORK_READ,
294     STATE_NETWORK_READ_COMPLETE,
295   };
296 
297   // Used for categorizing validation triggers in histograms.
298   // NOTE: This enumeration is used in histograms, so please do not add entries
299   // in the middle.
300   enum ValidationCause {
301     VALIDATION_CAUSE_UNDEFINED,
302     VALIDATION_CAUSE_VARY_MISMATCH,
303     VALIDATION_CAUSE_VALIDATE_FLAG,
304     VALIDATION_CAUSE_STALE,
305     VALIDATION_CAUSE_ZERO_FRESHNESS,
306     VALIDATION_CAUSE_MAX
307   };
308 
309   enum MemoryEntryDataHints {
310     // If this hint is set, the caching headers indicate we can't do anything
311     // with this entry (unless we are ignoring them thanks to a loadflag),
312     // i.e. it's expired and has nothing that permits validations.
313     HINT_UNUSABLE_PER_CACHING_HEADERS = (1 << 0),
314   };
315 
316   // Runs the state transition loop. Resets and calls |callback_| on exit,
317   // unless the return value is ERR_IO_PENDING.
318   int DoLoop(int result);
319 
320   // Each of these methods corresponds to a State value.  If there is an
321   // argument, the value corresponds to the return of the previous state or
322   // corresponding callback.
323   int DoGetBackend();
324   int DoGetBackendComplete(int result);
325   int DoInitEntry();
326   int DoOpenOrCreateEntry();
327   int DoOpenOrCreateEntryComplete(int result);
328   int DoDoomEntry();
329   int DoDoomEntryComplete(int result);
330   int DoCreateEntry();
331   int DoCreateEntryComplete(int result);
332   int DoAddToEntry();
333   int DoAddToEntryComplete(int result);
334   int DoDoneHeadersAddToEntryComplete(int result);
335   int DoCacheReadResponse();
336   int DoCacheReadResponseComplete(int result);
337   int DoCacheWriteUpdatedPrefetchResponse(int result);
338   int DoCacheWriteUpdatedPrefetchResponseComplete(int result);
339   int DoCacheDispatchValidation();
340   int DoCacheQueryData();
341   int DoCacheQueryDataComplete(int result);
342   int DoCacheUpdateStaleWhileRevalidateTimeout();
343   int DoCacheUpdateStaleWhileRevalidateTimeoutComplete(int result);
344   int DoConnectedCallback();
345   int DoConnectedCallbackComplete(int result);
346   int DoSetupEntryForRead();
347   int DoStartPartialCacheValidation();
348   int DoCompletePartialCacheValidation(int result);
349   int DoSendRequest();
350   int DoSendRequestComplete(int result);
351   int DoSuccessfulSendRequest();
352   int DoUpdateCachedResponse();
353   int DoCacheWriteUpdatedResponse();
354   int DoCacheWriteUpdatedResponseComplete(int result);
355   int DoUpdateCachedResponseComplete(int result);
356   int DoOverwriteCachedResponse();
357   int DoCacheWriteResponse();
358   int DoCacheWriteResponseComplete(int result);
359   int DoTruncateCachedData();
360   int DoTruncateCachedDataComplete(int result);
361   int DoTruncateCachedMetadata();
362   int DoTruncateCachedMetadataComplete(int result);
363   int DoPartialHeadersReceived();
364   int DoHeadersPhaseCannotProceed(int result);
365   int DoFinishHeaders(int result);
366   int DoFinishHeadersComplete(int result);
367   int DoNetworkReadCacheWrite();
368   int DoNetworkReadCacheWriteComplete(int result);
369   int DoCacheReadData();
370   int DoCacheReadDataComplete(int result);
371   int DoNetworkRead();
372   int DoNetworkReadComplete(int result);
373 
374   // Adds time out handling while waiting to be added to entry or after headers
375   // phase is complete.
376   void AddCacheLockTimeoutHandler(ActiveEntry* entry);
377 
378   // Sets request_ and fields derived from it.
379   void SetRequest(const NetLogWithSource& net_log);
380 
381   // Returns true if the request should be handled exclusively by the network
382   // layer (skipping the cache entirely).
383   bool ShouldPassThrough();
384 
385   // Called to begin reading from the cache.  Returns network error code.
386   int BeginCacheRead();
387 
388   // Called to begin validating the cache entry.  Returns network error code.
389   int BeginCacheValidation();
390 
391   // Called to begin validating an entry that stores partial content.  Returns
392   // a network error code.
393   int BeginPartialCacheValidation();
394 
395   // Validates the entry headers against the requested range and continues with
396   // the validation of the rest of the entry.  Returns a network error code.
397   int ValidateEntryHeadersAndContinue();
398 
399   // Returns whether the current externally conditionalized request's validation
400   // headers match the current cache entry's headers.
401   bool ExternallyConditionalizedValidationHeadersMatchEntry() const;
402 
403   // Called to start requests which were given an "if-modified-since" or
404   // "if-none-match" validation header by the caller (NOT when the request was
405   // conditionalized internally in response to LOAD_VALIDATE_CACHE).
406   // Returns a network error code.
407   int BeginExternallyConditionalizedRequest();
408 
409   // Called to restart a network transaction after an error.  Returns network
410   // error code.
411   int RestartNetworkRequest();
412 
413   // Called to restart a network transaction with a client certificate.
414   // Returns network error code.
415   int RestartNetworkRequestWithCertificate(
416       scoped_refptr<X509Certificate> client_cert,
417       scoped_refptr<SSLPrivateKey> client_private_key);
418 
419   // Called to restart a network transaction with authentication credentials.
420   // Returns network error code.
421   int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
422 
423   // Called to determine if we need to validate the cache entry before using it,
424   // and whether the validation should be synchronous or asynchronous.
425   ValidationType RequiresValidation();
426 
427   // Called to make the request conditional (to ask the server if the cached
428   // copy is valid).  Returns true if able to make the request conditional.
429   bool ConditionalizeRequest();
430 
431   // Determines if saved response permits conditionalization, and extracts
432   // etag/last-modified values. Only depends on |response_.headers|.
433   // |*etag_value| and |*last_modified_value| will be set if true is returned,
434   // but may also be modified in other cases.
435   bool IsResponseConditionalizable(std::string* etag_value,
436                                    std::string* last_modified_value) const;
437 
438   // Returns true if |method_| indicates that we should only try to open an
439   // entry and not attempt to create.
440   bool ShouldOpenOnlyMethods() const;
441 
442   // Returns true if the resource info MemoryEntryDataHints bit flags in
443   // |in_memory_info| and the current request & load flags suggest that
444   // the cache entry in question is not actually usable for HTTP
445   // (i.e. already expired, and nothing is forcing us to disregard that).
446   bool MaybeRejectBasedOnEntryInMemoryData(uint8_t in_memory_info);
447 
448   // Returns true if response_ is such that, if saved to cache, it would only
449   // be usable if load flags asked us to ignore caching headers.
450   // (return value of false makes no statement as to suitability of the entry).
451   bool ComputeUnusablePerCachingHeaders();
452 
453   // Makes sure that a 206 response is expected.  Returns true on success.
454   // On success, handling_206_ will be set to true if we are processing a
455   // partial entry.
456   bool ValidatePartialResponse();
457 
458   // Handles a response validation error by bypassing the cache.
459   void IgnoreRangeRequest();
460 
461   // Fixes the response headers to match expectations for a HEAD request.
462   void FixHeadersForHead();
463 
464   // Called to write a response to the cache entry. |truncated| indicates if the
465   // entry should be marked as incomplete.
466   int WriteResponseInfoToEntry(const HttpResponseInfo& response,
467                                bool truncated);
468 
469   // Helper function, should be called with result of WriteResponseInfoToEntry
470   // (or the result of the callback, when WriteResponseInfoToEntry returns
471   // ERR_IO_PENDING). Calls DoneWithEntry if |result| is not the right
472   // number of bytes. It is expected that the state that calls this will
473   // return whatever net error code this function returns, which currently
474   // is always "OK".
475   int OnWriteResponseInfoToEntryComplete(int result);
476 
477   // Configures the transaction to read from the network and stop writing to the
478   // entry. It will release the entry if possible. Returns true if caching could
479   // be stopped successfully. It will not be stopped if there are multiple
480   // transactions writing to the cache simultaneously.
481   bool StopCachingImpl(bool success);
482 
483   // Informs the HttpCache that this transaction is done with the entry and
484   // changes the mode to NONE. Set |entry_is_complete| to false if the
485   // transaction has not yet finished fully writing or reading the request
486   // to/from the entry. If |entry_is_complete| is false the result may be either
487   // a truncated or a doomed entry based on whether the stored response can be
488   // resumed or not.
489   void DoneWithEntry(bool entry_is_complete);
490 
491   // Dooms the given entry so that it will not be re-used for other requests,
492   // then calls `DoneWithEntry()`.
493   //
494   // This happens when network conditions have changed since the entry was
495   // cached, which results in deterministic failures when trying to use the
496   // cache entry. In order to let future requests succeed, the cache entry
497   // should be doomed.
498   void DoomInconsistentEntry();
499 
500   // Returns an error to signal the caller that the current read failed. The
501   // current operation |result| is also logged. If |restart| is true, the
502   // transaction should be restarted.
503   int OnCacheReadError(int result, bool restart);
504 
505   // Called when the cache lock timeout fires.
506   void OnCacheLockTimeout(base::TimeTicks start_time);
507 
508   // Deletes the current partial cache entry (sparse), and optionally removes
509   // the control object (partial_).
510   void DoomPartialEntry(bool delete_object);
511 
512   // Performs the needed work after receiving data from the network, when
513   // working with range requests.
514   int DoPartialNetworkReadCompleted(int result);
515 
516   // Performs the needed work after receiving data from the cache, when
517   // working with range requests.
518   int DoPartialCacheReadCompleted(int result);
519 
520   // Restarts this transaction after deleting the cached data. It is meant to
521   // be used when the current request cannot be fulfilled due to conflicts
522   // between the byte range request and the cached entry.
523   int DoRestartPartialRequest();
524 
525   // Resets the relavant internal state to remove traces of internal processing
526   // related to range requests. Deletes |partial_| if |delete_object| is true.
527   void ResetPartialState(bool delete_object);
528 
529   // Resets |network_trans_|, which must be non-NULL.  Also updates
530   // |old_network_trans_load_timing_|, which must be NULL when this is called.
531   void ResetNetworkTransaction();
532 
533   // Returns the currently active network transaction.
534   const HttpTransaction* network_transaction() const;
535   HttpTransaction* network_transaction();
536 
537   // Returns the network transaction from |this| or from writers only if it was
538   // moved from |this| to writers. This is so that statistics of the network
539   // transaction are not attributed to any other writer member.
540   const HttpTransaction* GetOwnedOrMovedNetworkTransaction() const;
541 
542   // Returns true if we should bother attempting to resume this request if it is
543   // aborted while in progress. If |has_data| is true, the size of the stored
544   // data is considered for the result.
545   bool CanResume(bool has_data);
546 
547   // Setter for response_ and auth_response_. It updates its cache entry status,
548   // if needed.
549   void SetResponse(const HttpResponseInfo& new_response);
550   void SetAuthResponse(const HttpResponseInfo& new_response);
551 
552   void UpdateCacheEntryStatus(
553       HttpResponseInfo::CacheEntryStatus new_cache_entry_status);
554 
555   // Sets the response.cache_entry_status to the current cache_entry_status_.
556   void SyncCacheEntryStatusToResponse();
557 
558   // Logs histograms for this transaction. It is invoked when the transaction is
559   // either complete or is done writing to entry and will continue in
560   // network-only mode.
561   void RecordHistograms();
562 
563   // Returns true if this transaction is a member of entry_->writers.
564   bool InWriters() const;
565 
566   // Called to signal completion of asynchronous IO. Note that this callback is
567   // used in the conventional sense where one layer calls the callback of the
568   // layer above it e.g. this callback gets called from the network transaction
569   // layer. In addition, it is also used for HttpCache layer to let this
570   // transaction know when it is out of a queued state in ActiveEntry and can
571   // continue its processing.
572   void OnIOComplete(int result);
573 
574   // Called to signal completion of an asynchronous HTTPCache operation. It
575   // uses a separate callback from OnIoComplete so that cache transaction
576   // operations and network IO can be run in parallel.
577   void OnCacheIOComplete(int result);
578 
579   // When in a DoLoop, use this to set the next state as it verifies that the
580   // state isn't set twice.
581   void TransitionToState(State state);
582 
583   // Helper function to decide the next reading state.
584   int TransitionToReadingState();
585 
586   // Saves network transaction info using |transaction|.
587   void SaveNetworkTransactionInfo(const HttpTransaction& transaction);
588 
589   // Determines whether caching should be disabled for a response, given its
590   // headers.
591   bool ShouldDisableCaching(const HttpResponseHeaders& headers) const;
592 
593   // 304 revalidations of resources that set security headers and that get
594   // forwarded might need to set these headers again to avoid being blocked.
595   void UpdateSecurityHeadersBeforeForwarding();
596 
597   enum class DiskCacheAccessType {
598     kRead,
599     kWrite,
600   };
601   void BeginDiskCacheAccessTimeCount();
602   void EndDiskCacheAccessTimeCount(DiskCacheAccessType type);
603 
604   State next_state_{STATE_NONE};
605 
606   // Set when a HTTPCache transaction is pending in parallel with other IO.
607   bool waiting_for_cache_io_ = false;
608 
609   // If a pending async HTTPCache transaction takes longer than the parallel
610   // Network IO, this will store the result of the Network IO operation until
611   // the cache transaction completes (or times out).
612   std::optional<int> pending_io_result_ = std::nullopt;
613 
614   // Used for tracing.
615   const uint64_t trace_id_;
616 
617   // Initial request with which Start() was invoked.
618   raw_ptr<const HttpRequestInfo> initial_request_ = nullptr;
619 
620   // `custom_request_` is assigned to `request_` after allocation. It must be
621   // declared before `request_` so that it will be destroyed afterwards to
622   // prevent that pointer from dangling.
623   std::unique_ptr<HttpRequestInfo> custom_request_;
624 
625   raw_ptr<const HttpRequestInfo> request_ = nullptr;
626 
627   std::string method_;
628   RequestPriority priority_;
629   NetLogWithSource net_log_;
630   HttpRequestHeaders request_headers_copy_;
631   // If extra_headers specified a "if-modified-since" or "if-none-match",
632   // |external_validation_| contains the value of those headers.
633   ValidationHeaders external_validation_;
634   base::WeakPtr<HttpCache> cache_;
635   scoped_refptr<HttpCache::ActiveEntry> entry_;
636   // This field is not a raw_ptr<> because it was filtered by the rewriter for:
637   // #addr-of
638   scoped_refptr<HttpCache::ActiveEntry> new_entry_;
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 std::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