In QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher,  early return if connection is disconnected after FlushPackets.

This is to fix https://bugs.chromium.org/p/chromium/issues/detail?id=1334021.

Protected by FLAGS_quic_reloadable_flag_quic_packet_flusher_check_connected_after_flush_packets.

PiperOrigin-RevId: 455696161
diff --git a/quiche/quic/core/quic_connection.cc b/quiche/quic/core/quic_connection.cc
index 3c9034f..ad7a103 100644
--- a/quiche/quic/core/quic_connection.cc
+++ b/quiche/quic/core/quic_connection.cc
@@ -4844,6 +4844,14 @@
       connection_->FlushCoalescedPacket();
     }
     connection_->FlushPackets();
+    if (GetQuicReloadableFlag(
+            quic_packet_flusher_check_connected_after_flush_packets)) {
+      QUIC_RELOADABLE_FLAG_COUNT(
+          quic_packet_flusher_check_connected_after_flush_packets);
+      if (!connection_->connected()) {
+        return;
+      }
+    }
     if (!handshake_packet_sent_ && connection_->handshake_packet_sent_) {
       // This would cause INITIAL key to be dropped. Drop keys here to avoid
       // missing the write keys in the middle of writing.
diff --git a/quiche/quic/core/quic_connection_test.cc b/quiche/quic/core/quic_connection_test.cc
index 2a89850..35c30f4 100644
--- a/quiche/quic/core/quic_connection_test.cc
+++ b/quiche/quic/core/quic_connection_test.cc
@@ -9871,7 +9871,10 @@
   use_tagging_decrypter();
 
   auto test_body = [&] {
-    EXPECT_CALL(visitor_, OnHandshakePacketSent());
+    if (!GetQuicReloadableFlag(
+            quic_packet_flusher_check_connected_after_flush_packets)) {
+      EXPECT_CALL(visitor_, OnHandshakePacketSent());
+    }
 
     EXPECT_CALL(visitor_,
                 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
diff --git a/quiche/quic/core/quic_flags_list.h b/quiche/quic/core/quic_flags_list.h
index 938446d..745bebd 100644
--- a/quiche/quic/core/quic_flags_list.h
+++ b/quiche/quic/core/quic_flags_list.h
@@ -23,6 +23,8 @@
 QUIC_FLAG(quic_restart_flag_quic_disable_legacy_version_encapsulation, false)
 // If true, QUIC will default enable MTU discovery at server, with a target of 1450 bytes.
 QUIC_FLAG(quic_reloadable_flag_quic_enable_mtu_discovery_at_server, false)
+// If true, QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher will early return if connection is disconnected after FlushPackets.
+QUIC_FLAG(quic_reloadable_flag_quic_packet_flusher_check_connected_after_flush_packets, true)
 // If true, QuicGsoBatchWriter will support release time if it is available and the process has the permission to do so.
 QUIC_FLAG(quic_restart_flag_quic_support_release_time_for_gso, false)
 // If true, TlsHandshaker::AdvanceHandshake will check if connection is closed after SSL_do_handshake.