xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/quic_sent_packet_manager.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 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 #ifndef QUICHE_QUIC_CORE_QUIC_SENT_PACKET_MANAGER_H_
6 #define QUICHE_QUIC_CORE_QUIC_SENT_PACKET_MANAGER_H_
7 
8 #include <cstddef>
9 #include <cstdint>
10 #include <map>
11 #include <memory>
12 #include <set>
13 #include <string>
14 #include <utility>
15 #include <vector>
16 
17 #include "quiche/quic/core/congestion_control/pacing_sender.h"
18 #include "quiche/quic/core/congestion_control/rtt_stats.h"
19 #include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
20 #include "quiche/quic/core/congestion_control/uber_loss_algorithm.h"
21 #include "quiche/quic/core/proto/cached_network_parameters_proto.h"
22 #include "quiche/quic/core/quic_packets.h"
23 #include "quiche/quic/core/quic_sustained_bandwidth_recorder.h"
24 #include "quiche/quic/core/quic_time.h"
25 #include "quiche/quic/core/quic_transmission_info.h"
26 #include "quiche/quic/core/quic_types.h"
27 #include "quiche/quic/core/quic_unacked_packet_map.h"
28 #include "quiche/quic/platform/api/quic_export.h"
29 #include "quiche/quic/platform/api/quic_flags.h"
30 #include "quiche/common/quiche_circular_deque.h"
31 
32 namespace quic {
33 
34 namespace test {
35 class QuicConnectionPeer;
36 class QuicSentPacketManagerPeer;
37 }  // namespace test
38 
39 class QuicClock;
40 class QuicConfig;
41 struct QuicConnectionStats;
42 
43 // Class which tracks the set of packets sent on a QUIC connection and contains
44 // a send algorithm to decide when to send new packets.  It keeps track of any
45 // retransmittable data associated with each packet. If a packet is
46 // retransmitted, it will keep track of each version of a packet so that if a
47 // previous transmission is acked, the data will not be retransmitted.
48 class QUICHE_EXPORT QuicSentPacketManager {
49  public:
50   // Interface which gets callbacks from the QuicSentPacketManager at
51   // interesting points.  Implementations must not mutate the state of
52   // the packet manager or connection as a result of these callbacks.
53   class QUICHE_EXPORT DebugDelegate {
54    public:
55     struct QUICHE_EXPORT SendParameters {
56       CongestionControlType congestion_control_type;
57       bool use_pacing;
58       QuicPacketCount initial_congestion_window;
59     };
60 
~DebugDelegate()61     virtual ~DebugDelegate() {}
62 
63     // Called when a spurious retransmission is detected.
OnSpuriousPacketRetransmission(TransmissionType,QuicByteCount)64     virtual void OnSpuriousPacketRetransmission(
65         TransmissionType /*transmission_type*/, QuicByteCount /*byte_size*/) {}
66 
OnIncomingAck(QuicPacketNumber,EncryptionLevel,const QuicAckFrame &,QuicTime,QuicPacketNumber,bool,QuicPacketNumber)67     virtual void OnIncomingAck(QuicPacketNumber /*ack_packet_number*/,
68                                EncryptionLevel /*ack_decrypted_level*/,
69                                const QuicAckFrame& /*ack_frame*/,
70                                QuicTime /*ack_receive_time*/,
71                                QuicPacketNumber /*largest_observed*/,
72                                bool /*rtt_updated*/,
73                                QuicPacketNumber /*least_unacked_sent_packet*/) {
74     }
75 
OnPacketLoss(QuicPacketNumber,EncryptionLevel,TransmissionType,QuicTime)76     virtual void OnPacketLoss(QuicPacketNumber /*lost_packet_number*/,
77                               EncryptionLevel /*encryption_level*/,
78                               TransmissionType /*transmission_type*/,
79                               QuicTime /*detection_time*/) {}
80 
OnApplicationLimited()81     virtual void OnApplicationLimited() {}
82 
OnAdjustNetworkParameters(QuicBandwidth,QuicTime::Delta,QuicByteCount,QuicByteCount)83     virtual void OnAdjustNetworkParameters(QuicBandwidth /*bandwidth*/,
84                                            QuicTime::Delta /*rtt*/,
85                                            QuicByteCount /*old_cwnd*/,
86                                            QuicByteCount /*new_cwnd*/) {}
87 
OnAdjustBurstSize(int,int)88     virtual void OnAdjustBurstSize(int /*old_burst_size*/,
89                                    int /*new_burst_size*/) {}
90 
OnOvershootingDetected()91     virtual void OnOvershootingDetected() {}
92 
OnConfigProcessed(const SendParameters &)93     virtual void OnConfigProcessed(const SendParameters& /*parameters*/) {}
94 
OnSendAlgorithmChanged(CongestionControlType)95     virtual void OnSendAlgorithmChanged(CongestionControlType /*type*/) {}
96   };
97 
98   // Interface which gets callbacks from the QuicSentPacketManager when
99   // network-related state changes. Implementations must not mutate the
100   // state of the packet manager as a result of these callbacks.
101   class QUICHE_EXPORT NetworkChangeVisitor {
102    public:
~NetworkChangeVisitor()103     virtual ~NetworkChangeVisitor() {}
104 
105     // Called when congestion window or RTT may have changed.
106     virtual void OnCongestionChange() = 0;
107 
108     // Called when the Path MTU may have increased.
109     virtual void OnPathMtuIncreased(QuicPacketLength packet_size) = 0;
110 
111     // Called when a in-flight packet sent on the current default path with ECN
112     // markings is acked.
113     virtual void OnInFlightEcnPacketAcked() = 0;
114 
115     // Called when an ACK frame with ECN counts has invalid values, or an ACK
116     // acknowledges packets with ECN marks and there are no ECN counts.
117     virtual void OnInvalidEcnFeedback() = 0;
118   };
119 
120   // The retransmission timer is a single timer which switches modes depending
121   // upon connection state.
122   enum RetransmissionTimeoutMode {
123     // Retransmission of handshake packets prior to handshake completion.
124     HANDSHAKE_MODE,
125     // Re-invoke the loss detection when a packet is not acked before the
126     // loss detection algorithm expects.
127     LOSS_MODE,
128     // A probe timeout. At least one probe packet must be sent when timer
129     // expires.
130     PTO_MODE,
131   };
132 
133   QuicSentPacketManager(Perspective perspective, const QuicClock* clock,
134                         QuicRandom* random, QuicConnectionStats* stats,
135                         CongestionControlType congestion_control_type);
136   QuicSentPacketManager(const QuicSentPacketManager&) = delete;
137   QuicSentPacketManager& operator=(const QuicSentPacketManager&) = delete;
138   virtual ~QuicSentPacketManager();
139 
140   virtual void SetFromConfig(const QuicConfig& config);
141 
ReserveUnackedPacketsInitialCapacity(int initial_capacity)142   void ReserveUnackedPacketsInitialCapacity(int initial_capacity) {
143     unacked_packets_.ReserveInitialCapacity(initial_capacity);
144   }
145 
146   void ApplyConnectionOptions(const QuicTagVector& connection_options);
147 
148   // Pass the CachedNetworkParameters to the send algorithm.
149   void ResumeConnectionState(
150       const CachedNetworkParameters& cached_network_params,
151       bool max_bandwidth_resumption);
152 
SetMaxPacingRate(QuicBandwidth max_pacing_rate)153   void SetMaxPacingRate(QuicBandwidth max_pacing_rate) {
154     pacing_sender_.set_max_pacing_rate(max_pacing_rate);
155   }
156 
157   // The delay to use for the send alarm. If zero, it essentially means
158   // to queue the send call immediately.
159   // WARNING: This is currently an experimental API.
160   // TODO(genioshelo): This should implement a dynamic delay based on the
161   // underlying connection properties and lumpy pacing.
GetDeferredSendAlarmDelay()162   QuicTime::Delta GetDeferredSendAlarmDelay() const {
163     return deferred_send_alarm_delay_.value_or(QuicTime::Delta::Zero());
164   }
SetDeferredSendAlarmDelay(QuicTime::Delta delay)165   void SetDeferredSendAlarmDelay(QuicTime::Delta delay) {
166     deferred_send_alarm_delay_ = delay;
167   }
168 
MaxPacingRate()169   QuicBandwidth MaxPacingRate() const {
170     return pacing_sender_.max_pacing_rate();
171   }
172 
173   // Called to mark the handshake state complete, and all handshake packets are
174   // neutered.
175   // TODO(fayang): Rename this function to OnHandshakeComplete.
176   void SetHandshakeConfirmed();
177 
178   // Requests retransmission of all unacked 0-RTT packets.
179   // Only 0-RTT encrypted packets will be retransmitted. This can happen,
180   // for example, when a CHLO has been rejected and the previously encrypted
181   // data needs to be encrypted with a new key.
182   void MarkZeroRttPacketsForRetransmission();
183 
184   // Request retransmission of all unacked INITIAL packets.
185   void MarkInitialPacketsForRetransmission();
186 
187   // Notify the sent packet manager of an external network measurement or
188   // prediction for either |bandwidth| or |rtt|; either can be empty.
189   void AdjustNetworkParameters(
190       const SendAlgorithmInterface::NetworkParams& params);
191 
192   void SetLossDetectionTuner(
193       std::unique_ptr<LossDetectionTunerInterface> tuner);
194   void OnConfigNegotiated();
195   void OnConnectionClosed();
196 
197   // Retransmits the oldest pending packet.
198   bool MaybeRetransmitOldestPacket(TransmissionType type);
199 
200   // Removes the retransmittable frames from all unencrypted packets to ensure
201   // they don't get retransmitted.
202   void NeuterUnencryptedPackets();
203 
204   // Returns true if there's outstanding crypto data.
HasUnackedCryptoPackets()205   bool HasUnackedCryptoPackets() const {
206     return unacked_packets_.HasPendingCryptoPackets();
207   }
208 
209   // Returns true if there are packets in flight expecting to be acknowledged.
HasInFlightPackets()210   bool HasInFlightPackets() const {
211     return unacked_packets_.HasInFlightPackets();
212   }
213 
214   // Returns the smallest packet number of a serialized packet which has not
215   // been acked by the peer.
GetLeastUnacked()216   QuicPacketNumber GetLeastUnacked() const {
217     return unacked_packets_.GetLeastUnacked();
218   }
219 
220   // Called when we have sent bytes to the peer.  This informs the manager both
221   // the number of bytes sent and if they were retransmitted and if this packet
222   // is used for rtt measuring.  Returns true if the sender should reset the
223   // retransmission timer.
224   bool OnPacketSent(SerializedPacket* mutable_packet, QuicTime sent_time,
225                     TransmissionType transmission_type,
226                     HasRetransmittableData has_retransmittable_data,
227                     bool measure_rtt, QuicEcnCodepoint ecn_codepoint);
228 
229   bool CanSendAckFrequency() const;
230 
231   QuicAckFrequencyFrame GetUpdatedAckFrequencyFrame() const;
232 
233   // Called when the retransmission timer expires and returns the retransmission
234   // mode.
235   RetransmissionTimeoutMode OnRetransmissionTimeout();
236 
237   // Calculate the time until we can send the next packet to the wire.
238   // Note 1: When kUnknownWaitTime is returned, there is no need to poll
239   // TimeUntilSend again until we receive an OnIncomingAckFrame event.
240   // Note 2: Send algorithms may or may not use |retransmit| in their
241   // calculations.
242   QuicTime::Delta TimeUntilSend(QuicTime now) const;
243 
244   // Returns the current delay for the retransmission timer, which may send
245   // either a tail loss probe or do a full RTO.  Returns QuicTime::Zero() if
246   // there are no retransmittable packets.
247   const QuicTime GetRetransmissionTime() const;
248 
249   // Returns the current delay for the path degrading timer, which is used to
250   // notify the session that this connection is degrading.
251   const QuicTime::Delta GetPathDegradingDelay() const;
252 
253   // Returns the current delay for detecting network blackhole.
254   const QuicTime::Delta GetNetworkBlackholeDelay(
255       int8_t num_rtos_for_blackhole_detection) const;
256 
257   // Returns the delay before reducing max packet size. This delay is guranteed
258   // to be smaller than the network blackhole delay.
259   QuicTime::Delta GetMtuReductionDelay(
260       int8_t num_rtos_for_blackhole_detection) const;
261 
GetRttStats()262   const RttStats* GetRttStats() const { return &rtt_stats_; }
263 
SetRttStats(const RttStats & rtt_stats)264   void SetRttStats(const RttStats& rtt_stats) {
265     rtt_stats_.CloneFrom(rtt_stats);
266   }
267 
268   // Returns the estimated bandwidth calculated by the congestion algorithm.
BandwidthEstimate()269   QuicBandwidth BandwidthEstimate() const {
270     return send_algorithm_->BandwidthEstimate();
271   }
272 
SustainedBandwidthRecorder()273   const QuicSustainedBandwidthRecorder* SustainedBandwidthRecorder() const {
274     return &sustained_bandwidth_recorder_;
275   }
276 
277   // Returns the size of the current congestion window in number of
278   // kDefaultTCPMSS-sized segments. Note, this is not the *available* window.
279   // Some send algorithms may not use a congestion window and will return 0.
GetCongestionWindowInTcpMss()280   QuicPacketCount GetCongestionWindowInTcpMss() const {
281     return send_algorithm_->GetCongestionWindow() / kDefaultTCPMSS;
282   }
283 
284   // Returns the number of packets of length |max_packet_length| which fit in
285   // the current congestion window. More packets may end up in flight if the
286   // congestion window has been recently reduced, of if non-full packets are
287   // sent.
EstimateMaxPacketsInFlight(QuicByteCount max_packet_length)288   QuicPacketCount EstimateMaxPacketsInFlight(
289       QuicByteCount max_packet_length) const {
290     return send_algorithm_->GetCongestionWindow() / max_packet_length;
291   }
292 
293   // Returns the size of the current congestion window size in bytes.
GetCongestionWindowInBytes()294   QuicByteCount GetCongestionWindowInBytes() const {
295     return send_algorithm_->GetCongestionWindow();
296   }
297 
298   // Returns the difference between current congestion window and bytes in
299   // flight. Returns 0 if bytes in flight is bigger than the current congestion
300   // window.
301   QuicByteCount GetAvailableCongestionWindowInBytes() const;
302 
GetPacingRate()303   QuicBandwidth GetPacingRate() const {
304     return send_algorithm_->PacingRate(GetBytesInFlight());
305   }
306 
307   // Returns the size of the slow start congestion window in nume of 1460 byte
308   // TCP segments, aka ssthresh.  Some send algorithms do not define a slow
309   // start threshold and will return 0.
GetSlowStartThresholdInTcpMss()310   QuicPacketCount GetSlowStartThresholdInTcpMss() const {
311     return send_algorithm_->GetSlowStartThreshold() / kDefaultTCPMSS;
312   }
313 
314   // Return the total time spent in slow start so far. If the sender is
315   // currently in slow start, the return value will include the duration between
316   // the most recent entry to slow start and now.
317   //
318   // Only implemented for BBR. Return QuicTime::Delta::Infinite() for other
319   // congestion controllers.
320   QuicTime::Delta GetSlowStartDuration() const;
321 
322   // Returns debugging information about the state of the congestion controller.
323   std::string GetDebugState() const;
324 
325   // Returns the number of bytes that are considered in-flight, i.e. not lost or
326   // acknowledged.
GetBytesInFlight()327   QuicByteCount GetBytesInFlight() const {
328     return unacked_packets_.bytes_in_flight();
329   }
330 
331   // Called when peer address changes. Must be called IFF the address change is
332   // not NAT rebinding. If reset_send_algorithm is true, switch to a new send
333   // algorithm object and retransmit all the in-flight packets. Return the send
334   // algorithm object used on the previous path.
335   std::unique_ptr<SendAlgorithmInterface> OnConnectionMigration(
336       bool reset_send_algorithm);
337 
338   // Called when an ack frame is initially parsed.
339   void OnAckFrameStart(QuicPacketNumber largest_acked,
340                        QuicTime::Delta ack_delay_time,
341                        QuicTime ack_receive_time);
342 
343   // Called when ack range [start, end) is received. Populates packets_acked_
344   // with newly acked packets.
345   void OnAckRange(QuicPacketNumber start, QuicPacketNumber end);
346 
347   // Called when a timestamp is processed.  If it's present in packets_acked_,
348   // the timestamp field is set.  Otherwise, the timestamp is ignored.
349   void OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp);
350 
351   // Called when an ack frame is parsed completely.
352   AckResult OnAckFrameEnd(QuicTime ack_receive_time,
353                           QuicPacketNumber ack_packet_number,
354                           EncryptionLevel ack_decrypted_level,
355                           const std::optional<QuicEcnCounts>& ecn_counts);
356 
357   void EnableMultiplePacketNumberSpacesSupport();
358 
359   void SetDebugDelegate(DebugDelegate* debug_delegate);
360 
GetLargestObserved()361   QuicPacketNumber GetLargestObserved() const {
362     return unacked_packets_.largest_acked();
363   }
364 
365   QuicPacketNumber GetLargestAckedPacket(
366       EncryptionLevel decrypted_packet_level) const;
367 
GetLargestSentPacket()368   QuicPacketNumber GetLargestSentPacket() const {
369     return unacked_packets_.largest_sent_packet();
370   }
371 
372   // Returns the lowest of the largest acknowledged packet and the least
373   // unacked packet. This is designed to be used when computing the packet
374   // number length to send.
375   QuicPacketNumber GetLeastPacketAwaitedByPeer(
376       EncryptionLevel encryption_level) const;
377 
378   QuicPacketNumber GetLargestPacketPeerKnowsIsAcked(
379       EncryptionLevel decrypted_packet_level) const;
380 
SetNetworkChangeVisitor(NetworkChangeVisitor * visitor)381   void SetNetworkChangeVisitor(NetworkChangeVisitor* visitor) {
382     QUICHE_DCHECK(!network_change_visitor_);
383     QUICHE_DCHECK(visitor);
384     network_change_visitor_ = visitor;
385   }
386 
InSlowStart()387   bool InSlowStart() const { return send_algorithm_->InSlowStart(); }
388 
GetConsecutivePtoCount()389   size_t GetConsecutivePtoCount() const { return consecutive_pto_count_; }
390 
391   void OnApplicationLimited();
392 
GetSendAlgorithm()393   const SendAlgorithmInterface* GetSendAlgorithm() const {
394     return send_algorithm_.get();
395   }
396 
397   // Wrapper for SendAlgorithmInterface functions, since these functions are
398   // not const.
EnableECT0()399   bool EnableECT0() { return send_algorithm_->EnableECT0(); }
EnableECT1()400   bool EnableECT1() { return send_algorithm_->EnableECT1(); }
401 
SetSessionNotifier(SessionNotifierInterface * session_notifier)402   void SetSessionNotifier(SessionNotifierInterface* session_notifier) {
403     unacked_packets_.SetSessionNotifier(session_notifier);
404   }
405 
406   NextReleaseTimeResult GetNextReleaseTime() const;
407 
initial_congestion_window()408   QuicPacketCount initial_congestion_window() const {
409     return initial_congestion_window_;
410   }
411 
largest_packet_peer_knows_is_acked()412   QuicPacketNumber largest_packet_peer_knows_is_acked() const {
413     QUICHE_DCHECK(!supports_multiple_packet_number_spaces());
414     return largest_packet_peer_knows_is_acked_;
415   }
416 
pending_timer_transmission_count()417   size_t pending_timer_transmission_count() const {
418     return pending_timer_transmission_count_;
419   }
420 
peer_max_ack_delay()421   QuicTime::Delta peer_max_ack_delay() const { return peer_max_ack_delay_; }
422 
set_peer_max_ack_delay(QuicTime::Delta peer_max_ack_delay)423   void set_peer_max_ack_delay(QuicTime::Delta peer_max_ack_delay) {
424     // The delayed ack time should never be more than one half the min RTO time.
425     QUICHE_DCHECK_LE(
426         peer_max_ack_delay,
427         (QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs) * 0.5));
428     peer_max_ack_delay_ = peer_max_ack_delay;
429   }
430 
unacked_packets()431   const QuicUnackedPacketMap& unacked_packets() const {
432     return unacked_packets_;
433   }
434 
uber_loss_algorithm()435   const UberLossAlgorithm* uber_loss_algorithm() const {
436     return &uber_loss_algorithm_;
437   }
438 
439   // Sets the send algorithm to the given congestion control type and points the
440   // pacing sender at |send_algorithm_|. Can be called any number of times.
441   void SetSendAlgorithm(CongestionControlType congestion_control_type);
442 
443   // Sets the send algorithm to |send_algorithm| and points the pacing sender at
444   // |send_algorithm_|. Takes ownership of |send_algorithm|. Can be called any
445   // number of times.
446   // Setting the send algorithm once the connection is underway is dangerous.
447   void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm);
448 
449   // Sends one probe packet.
450   void MaybeSendProbePacket();
451 
452   // Called to disable HANDSHAKE_MODE, and only PTO and LOSS modes are used.
453   // Also enable IETF loss detection.
454   void EnableIetfPtoAndLossDetection();
455 
456   // Called to retransmit in flight packet of |space| if any.
457   void RetransmitDataOfSpaceIfAny(PacketNumberSpace space);
458 
459   // Returns true if |timeout| is less than 3 * RTO/PTO delay.
460   bool IsLessThanThreePTOs(QuicTime::Delta timeout) const;
461 
462   // Returns current PTO delay.
463   QuicTime::Delta GetPtoDelay() const;
464 
supports_multiple_packet_number_spaces()465   bool supports_multiple_packet_number_spaces() const {
466     return unacked_packets_.supports_multiple_packet_number_spaces();
467   }
468 
handshake_mode_disabled()469   bool handshake_mode_disabled() const { return handshake_mode_disabled_; }
470 
zero_rtt_packet_acked()471   bool zero_rtt_packet_acked() const { return zero_rtt_packet_acked_; }
472 
one_rtt_packet_acked()473   bool one_rtt_packet_acked() const { return one_rtt_packet_acked_; }
474 
OnUserAgentIdKnown()475   void OnUserAgentIdKnown() { loss_algorithm_->OnUserAgentIdKnown(); }
476 
477   // Gets the earliest in flight packet sent time to calculate PTO. Also
478   // updates |packet_number_space| if a PTO timer should be armed.
479   QuicTime GetEarliestPacketSentTimeForPto(
480       PacketNumberSpace* packet_number_space) const;
481 
set_num_ptos_for_path_degrading(int num_ptos_for_path_degrading)482   void set_num_ptos_for_path_degrading(int num_ptos_for_path_degrading) {
483     num_ptos_for_path_degrading_ = num_ptos_for_path_degrading;
484   }
485 
486   // Sets the initial RTT of the connection. The inital RTT is clamped to
487   // - A maximum of kMaxInitialRoundTripTimeUs.
488   // - A minimum of kMinTrustedInitialRoundTripTimeUs if |trusted|, or
489   // kMinUntrustedInitialRoundTripTimeUs if not |trusted|.
490   void SetInitialRtt(QuicTime::Delta rtt, bool trusted);
491 
492  private:
493   friend class test::QuicConnectionPeer;
494   friend class test::QuicSentPacketManagerPeer;
495 
496   // Returns the current retransmission mode.
497   RetransmissionTimeoutMode GetRetransmissionMode() const;
498 
499   // Retransmits all crypto stream packets.
500   void RetransmitCryptoPackets();
501 
502   // Returns the timeout for retransmitting crypto handshake packets.
503   const QuicTime::Delta GetCryptoRetransmissionDelay() const;
504 
505   // Returns the probe timeout.
506   const QuicTime::Delta GetProbeTimeoutDelay(PacketNumberSpace space) const;
507 
508   // Update the RTT if the ack is for the largest acked packet number.
509   // Returns true if the rtt was updated.
510   bool MaybeUpdateRTT(QuicPacketNumber largest_acked,
511                       QuicTime::Delta ack_delay_time,
512                       QuicTime ack_receive_time);
513 
514   // Invokes the loss detection algorithm and loses and retransmits packets if
515   // necessary.
516   void InvokeLossDetection(QuicTime time);
517 
518   // Invokes OnCongestionEvent if |rtt_updated| is true, there are pending acks,
519   // or pending losses.  Clears pending acks and pending losses afterwards.
520   // |prior_in_flight| is the number of bytes in flight before the losses or
521   // acks, |event_time| is normally the timestamp of the ack packet which caused
522   // the event, although it can be the time at which loss detection was
523   // triggered.
524   void MaybeInvokeCongestionEvent(bool rtt_updated,
525                                   QuicByteCount prior_in_flight,
526                                   QuicTime event_time,
527                                   std::optional<QuicEcnCounts> ecn_counts,
528                                   const QuicEcnCounts& previous_counts);
529 
530   // Removes the retransmittability and in flight properties from the packet at
531   // |info| due to receipt by the peer.
532   void MarkPacketHandled(QuicPacketNumber packet_number,
533                          QuicTransmissionInfo* info, QuicTime ack_receive_time,
534                          QuicTime::Delta ack_delay_time,
535                          QuicTime receive_timestamp);
536 
537   // Request that |packet_number| be retransmitted after the other pending
538   // retransmissions.  Does not add it to the retransmissions if it's already
539   // a pending retransmission. Do not reuse iterator of the underlying
540   // unacked_packets_ after calling this function as it can be invalidated.
541   void MarkForRetransmission(QuicPacketNumber packet_number,
542                              TransmissionType transmission_type);
543 
544   // Called after packets have been marked handled with last received ack frame.
545   void PostProcessNewlyAckedPackets(QuicPacketNumber ack_packet_number,
546                                     EncryptionLevel ack_decrypted_level,
547                                     const QuicAckFrame& ack_frame,
548                                     QuicTime ack_receive_time, bool rtt_updated,
549                                     QuicByteCount prior_bytes_in_flight,
550                                     std::optional<QuicEcnCounts> ecn_counts);
551 
552   // Notify observers that packet with QuicTransmissionInfo |info| is a spurious
553   // retransmission. It is caller's responsibility to guarantee the packet with
554   // QuicTransmissionInfo |info| is a spurious retransmission before calling
555   // this function.
556   void RecordOneSpuriousRetransmission(const QuicTransmissionInfo& info);
557 
558   // Called when handshake is confirmed to remove the retransmittable frames
559   // from all packets of HANDSHAKE_DATA packet number space to ensure they don't
560   // get retransmitted and will eventually be removed from unacked packets map.
561   void NeuterHandshakePackets();
562 
563   // Indicates whether including peer_max_ack_delay_ when calculating PTO
564   // timeout.
565   bool ShouldAddMaxAckDelay(PacketNumberSpace space) const;
566 
567   // A helper function to return total delay of |num_timeouts| retransmission
568   // timeout with TLP and RTO mode.
569   // TODO(fayang): remove this method and calculate blackhole delay by PTO.
570   QuicTime::Delta GetNConsecutiveRetransmissionTimeoutDelay(
571       int num_timeouts) const;
572 
573   // Returns true if peer has finished address validation, such that
574   // retransmission timer is not armed if there is no packets in flight.
575   bool PeerCompletedAddressValidation() const;
576 
577   // Called when an AckFrequencyFrame is sent.
578   void OnAckFrequencyFrameSent(
579       const QuicAckFrequencyFrame& ack_frequency_frame);
580 
581   // Called when an AckFrequencyFrame is acked.
582   void OnAckFrequencyFrameAcked(
583       const QuicAckFrequencyFrame& ack_frequency_frame);
584 
585   // Checks if newly reported ECN counts are valid given what has been reported
586   // in the past. |space| is the packet number space the counts apply to.
587   // |ecn_counts| is what the peer reported. |newly_acked_ect0| and
588   // |newly_acked_ect1| count the number of previously unacked packets with
589   // those markings that appeared in an ack block for the first time.
590   bool IsEcnFeedbackValid(PacketNumberSpace space,
591                           const std::optional<QuicEcnCounts>& ecn_counts,
592                           QuicPacketCount newly_acked_ect0,
593                           QuicPacketCount newly_acked_ect1);
594 
595   // Update counters for the number of ECN-marked packets sent.
596   void RecordEcnMarkingSent(QuicEcnCodepoint ecn_codepoint,
597                             EncryptionLevel level);
598 
599   // Newly serialized retransmittable packets are added to this map, which
600   // contains owning pointers to any contained frames.  If a packet is
601   // retransmitted, this map will contain entries for both the old and the new
602   // packet. The old packet's retransmittable frames entry will be nullptr,
603   // while the new packet's entry will contain the frames to retransmit.
604   // If the old packet is acked before the new packet, then the old entry will
605   // be removed from the map and the new entry's retransmittable frames will be
606   // set to nullptr.
607   QuicUnackedPacketMap unacked_packets_;
608 
609   const QuicClock* clock_;
610   QuicRandom* random_;
611   QuicConnectionStats* stats_;
612 
613   DebugDelegate* debug_delegate_;
614   NetworkChangeVisitor* network_change_visitor_;
615   QuicPacketCount initial_congestion_window_;
616   RttStats rtt_stats_;
617   std::unique_ptr<SendAlgorithmInterface> send_algorithm_;
618   // Not owned. Always points to |uber_loss_algorithm_| outside of tests.
619   LossDetectionInterface* loss_algorithm_;
620   UberLossAlgorithm uber_loss_algorithm_;
621 
622   // Number of times the crypto handshake has been retransmitted.
623   size_t consecutive_crypto_retransmission_count_;
624   // Number of pending transmissions of PTO or crypto packets.
625   size_t pending_timer_transmission_count_;
626 
627   bool using_pacing_;
628   // If true, use a more conservative handshake retransmission policy.
629   bool conservative_handshake_retransmits_;
630 
631   // Vectors packets acked and lost as a result of the last congestion event.
632   AckedPacketVector packets_acked_;
633   LostPacketVector packets_lost_;
634   // Largest newly acknowledged packet.
635   QuicPacketNumber largest_newly_acked_;
636   // Largest packet in bytes ever acknowledged.
637   QuicPacketLength largest_mtu_acked_;
638 
639   // Replaces certain calls to |send_algorithm_| when |using_pacing_| is true.
640   // Calls into |send_algorithm_| for the underlying congestion control.
641   PacingSender pacing_sender_;
642 
643   // Indicates whether handshake is finished. This is purely used to determine
644   // retransmission mode. DONOT use this to infer handshake state.
645   bool handshake_finished_;
646 
647   // Records bandwidth from server to client in normal operation, over periods
648   // of time with no loss events.
649   QuicSustainedBandwidthRecorder sustained_bandwidth_recorder_;
650 
651   // The largest acked value that was sent in an ack, which has then been acked.
652   QuicPacketNumber largest_packet_peer_knows_is_acked_;
653   // The largest acked value that was sent in an ack, which has then been acked
654   // for per packet number space. Only used when connection supports multiple
655   // packet number spaces.
656   QuicPacketNumber
657       largest_packets_peer_knows_is_acked_[NUM_PACKET_NUMBER_SPACES];
658 
659   // The maximum ACK delay time that the peer might uses. Initialized to be the
660   // same as local_max_ack_delay_, may be changed via transport parameter
661   // negotiation or subsequently by AckFrequencyFrame.
662   QuicTime::Delta peer_max_ack_delay_;
663 
664   // Peer sends min_ack_delay in TransportParameter to advertise its support for
665   // AckFrequencyFrame.
666   QuicTime::Delta peer_min_ack_delay_ = QuicTime::Delta::Infinite();
667 
668   // Use smoothed RTT for computing max_ack_delay in AckFrequency frame.
669   bool use_smoothed_rtt_in_ack_delay_ = false;
670 
671   // The history of outstanding max_ack_delays sent to peer. Outstanding means
672   // a max_ack_delay is sent as part of the last acked AckFrequencyFrame or
673   // an unacked AckFrequencyFrame after that.
674   quiche::QuicheCircularDeque<
675       std::pair<QuicTime::Delta, /*sequence_number=*/uint64_t>>
676       in_use_sent_ack_delays_;
677 
678   // Latest received ack frame.
679   QuicAckFrame last_ack_frame_;
680 
681   // Record whether RTT gets updated by last largest acked..
682   bool rtt_updated_;
683 
684   // A reverse iterator of last_ack_frame_.packets. This is reset in
685   // OnAckRangeStart, and gradually moves in OnAckRange..
686   PacketNumberQueue::const_reverse_iterator acked_packets_iter_;
687 
688   // Number of times the PTO timer has fired in a row without receiving an ack.
689   size_t consecutive_pto_count_;
690 
691   // True if HANDSHAKE mode has been disabled.
692   bool handshake_mode_disabled_;
693 
694   // True if any ENCRYPTION_HANDSHAKE packet gets acknowledged.
695   bool handshake_packet_acked_;
696 
697   // True if any 0-RTT packet gets acknowledged.
698   bool zero_rtt_packet_acked_;
699 
700   // True if any 1-RTT packet gets acknowledged.
701   bool one_rtt_packet_acked_;
702 
703   // The number of PTOs needed for path degrading alarm. If equals to 0, the
704   // traditional path degrading mechanism will be used.
705   int num_ptos_for_path_degrading_;
706 
707   // If true, do not use PING only packets for RTT measurement or congestion
708   // control.
709   bool ignore_pings_;
710 
711   // Whether to ignore the ack_delay in received ACKs.
712   bool ignore_ack_delay_;
713 
714   // The total number of packets sent with ECT(0) or ECT(1) in each packet
715   // number space over the life of the connection.
716   QuicPacketCount ect0_packets_sent_[NUM_PACKET_NUMBER_SPACES] = {0, 0, 0};
717   QuicPacketCount ect1_packets_sent_[NUM_PACKET_NUMBER_SPACES] = {0, 0, 0};
718 
719   // Most recent ECN codepoint counts received in an ACK frame sent by the peer.
720   QuicEcnCounts peer_ack_ecn_counts_[NUM_PACKET_NUMBER_SPACES];
721 
722   std::optional<QuicTime::Delta> deferred_send_alarm_delay_;
723 };
724 
725 }  // namespace quic
726 
727 #endif  // QUICHE_QUIC_CORE_QUIC_SENT_PACKET_MANAGER_H_
728