From 016384726e04e5e13efecffcccf8561a6845237d Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 15 May 2026 06:36:11 -0700 Subject: [PATCH] quic: apply multiple additional minor improvements Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/63267 Reviewed-By: Matteo Collina --- src/quic/bindingdata.cc | 22 ++++++++-------- src/quic/data.cc | 8 ++++-- src/quic/endpoint.cc | 24 ++++++++--------- src/quic/endpoint.h | 9 ++++--- src/quic/quic.cc | 10 +++++--- src/quic/session.cc | 20 +++++++-------- src/quic/session.h | 43 +++++++++++++++++-------------- src/quic/streams.cc | 57 +++++++++++++++++++++-------------------- src/quic/tlscontext.cc | 6 ++--- src/quic/tlscontext.h | 2 +- 10 files changed, 109 insertions(+), 92 deletions(-) diff --git a/src/quic/bindingdata.cc b/src/quic/bindingdata.cc index d6ceb2d2c6d..d37cab805de 100644 --- a/src/quic/bindingdata.cc +++ b/src/quic/bindingdata.cc @@ -335,7 +335,7 @@ void BindingData::OnFlushCheck() { // pending_flush_sessions_ and are picked up on the next check tick. auto sessions = std::move(pending_flush_sessions_); for (auto& session : sessions) { - session->pending_flush_ = false; + session->flags_.pending_flush = false; if (!session->is_destroyed()) { session->FlushPendingData(); } @@ -437,28 +437,28 @@ JS_METHOD_IMPL(BindingData::SetCallbacks) { } NgTcp2CallbackScope::NgTcp2CallbackScope(Session* session) : session(session) { - CHECK(!session->in_ngtcp2_callback_scope_); - session->in_ngtcp2_callback_scope_ = true; + CHECK(!session->flags_.in_ngtcp2_callback_scope); + session->flags_.in_ngtcp2_callback_scope = true; } NgTcp2CallbackScope::~NgTcp2CallbackScope() { - session->in_ngtcp2_callback_scope_ = false; - if (session->destroy_deferred_) { - session->destroy_deferred_ = false; + session->flags_.in_ngtcp2_callback_scope = false; + if (session->flags_.destroy_deferred) { + session->flags_.destroy_deferred = false; session->Destroy(); } } NgHttp3CallbackScope::NgHttp3CallbackScope(Session* session) : session(session) { - CHECK(!session->in_nghttp3_callback_scope_); - session->in_nghttp3_callback_scope_ = true; + CHECK(!session->flags_.in_nghttp3_callback_scope); + session->flags_.in_nghttp3_callback_scope = true; } NgHttp3CallbackScope::~NgHttp3CallbackScope() { - session->in_nghttp3_callback_scope_ = false; - if (session->destroy_deferred_) { - session->destroy_deferred_ = false; + session->flags_.in_nghttp3_callback_scope = false; + if (session->flags_.destroy_deferred) { + session->flags_.destroy_deferred = false; session->Destroy(); } } diff --git a/src/quic/data.cc b/src/quic/data.cc index d56420feae1..aebae9099a2 100644 --- a/src/quic/data.cc +++ b/src/quic/data.cc @@ -137,7 +137,9 @@ Store Store::CopyFrom(Local buffer) { auto backing = buffer->GetBackingStore(); auto length = buffer->ByteLength(); auto dest = ArrayBuffer::NewBackingStore( - isolate, length, BackingStoreInitializationMode::kUninitialized, + isolate, + length, + BackingStoreInitializationMode::kUninitialized, BackingStoreOnFailureMode::kReturnNull); if (!dest) { THROW_ERR_MEMORY_ALLOCATION_FAILED(Environment::GetCurrent(isolate)); @@ -154,7 +156,9 @@ Store Store::CopyFrom(Local view) { auto length = view->ByteLength(); auto offset = view->ByteOffset(); auto dest = ArrayBuffer::NewBackingStore( - isolate, length, BackingStoreInitializationMode::kUninitialized, + isolate, + length, + BackingStoreInitializationMode::kUninitialized, BackingStoreOnFailureMode::kReturnNull); // copy content if (!dest) { diff --git a/src/quic/endpoint.cc b/src/quic/endpoint.cc index 46dd0231c4f..dfeb53402a7 100644 --- a/src/quic/endpoint.cc +++ b/src/quic/endpoint.cc @@ -378,7 +378,7 @@ Endpoint::UDP::~UDP() { } int Endpoint::UDP::Bind(const Options& options) { - if (is_bound_) return UV_EALREADY; + if (flags_.is_bound) return UV_EALREADY; if (is_closed_or_closing()) return UV_EBADF; int flags = 0; @@ -388,7 +388,7 @@ int Endpoint::UDP::Bind(const Options& options) { int size; if (!err) { - is_bound_ = true; + flags_.is_bound = true; size = static_cast(options.udp_receive_buffer_size); if (size > 0) { err = uv_recv_buffer_size(reinterpret_cast(&impl_->handle_), @@ -427,34 +427,34 @@ void Endpoint::UDP::Unref() { int Endpoint::UDP::Start() { if (is_closed_or_closing()) return UV_EBADF; - if (is_started_) return 0; + if (flags_.is_started) return 0; int err = uv_udp_recv_start(&impl_->handle_, Impl::OnAlloc, Impl::OnReceive); - is_started_ = (err == 0); + flags_.is_started = (err == 0); return err; } void Endpoint::UDP::Stop() { - if (is_closed_or_closing() || !is_started_) return; + if (is_closed_or_closing() || !flags_.is_started) return; USE(uv_udp_recv_stop(&impl_->handle_)); - is_started_ = false; + flags_.is_started = false; } void Endpoint::UDP::Close() { if (is_closed_or_closing()) return; DCHECK(impl_); Stop(); - is_bound_ = false; - is_closed_ = true; + flags_.is_bound = false; + flags_.is_closed = true; impl_->Close(); impl_.reset(); } bool Endpoint::UDP::is_bound() const { - return is_bound_; + return flags_.is_bound; } bool Endpoint::UDP::is_closed() const { - return is_closed_; + return flags_.is_closed; } bool Endpoint::UDP::is_closed_or_closing() const { @@ -1294,8 +1294,8 @@ void Endpoint::Receive(const uint8_t* data, } // Schedule the session for deferred SendPendingData if it hasn't // been scheduled already in this burst. - if (!session->is_destroyed() && !session->pending_flush_) { - session->pending_flush_ = true; + if (!session->is_destroyed() && !session->flags_.pending_flush) { + session->flags_.pending_flush = true; BindingData::Get(env()).ScheduleSessionFlush( BaseObjectPtr(session)); } diff --git a/src/quic/endpoint.h b/src/quic/endpoint.h index a9f020e0328..1a31a89b2d1 100644 --- a/src/quic/endpoint.h +++ b/src/quic/endpoint.h @@ -343,9 +343,12 @@ class Endpoint final : public AsyncWrap, public Packet::Listener { class Impl; BaseObjectWeakPtr impl_; - bool is_bound_ = false; - bool is_started_ = false; - bool is_closed_ = false; + struct Flags { + uint8_t is_bound : 1 = 0; + uint8_t is_started : 1 = 0; + uint8_t is_closed : 1 = 0; + }; + Flags flags_; }; bool is_closed() const; diff --git a/src/quic/quic.cc b/src/quic/quic.cc index d39215a0682..36e781f1d70 100644 --- a/src/quic/quic.cc +++ b/src/quic/quic.cc @@ -13,7 +13,7 @@ #include "node_external_reference.h" #include -#include + namespace node { using v8::Context; @@ -25,7 +25,11 @@ using v8::Value; namespace quic { namespace { -std::once_flag crypto_init_flag; +uv_once_t crypto_init_flag = UV_ONCE_INIT; + +void InitNgtcp2CryptoOnce() { + ngtcp2_crypto_ossl_init(); +} } // namespace void CreatePerIsolateProperties(IsolateData* isolate_data, @@ -39,8 +43,8 @@ void CreatePerContextProperties(Local target, Local unused, Local context, void* priv) { + uv_once(&crypto_init_flag, InitNgtcp2CryptoOnce); Realm* realm = Realm::GetCurrent(context); - std::call_once(crypto_init_flag, ngtcp2_crypto_ossl_init); BindingData::InitPerContext(realm, target); Endpoint::InitPerContext(realm, target); Session::InitPerContext(realm, target); diff --git a/src/quic/session.cc b/src/quic/session.cc index 7737f97e98a..de17cff0c2f 100644 --- a/src/quic/session.cc +++ b/src/quic/session.cc @@ -1810,7 +1810,7 @@ bool Session::is_server() const { } bool Session::is_destroyed() const { - return !impl_ || destroy_deferred_; + return !impl_ || flags_.destroy_deferred; } bool Session::is_destroyed_or_closing() const { @@ -1988,9 +1988,9 @@ void Session::Destroy() { // destroy impl_ now because the callback is executing methods on // objects owned by impl_ (e.g., the Application). Defer the // destruction until the scope exits. - if (in_ngtcp2_callback_scope_ || in_nghttp3_callback_scope_) { + if (flags_.in_ngtcp2_callback_scope || flags_.in_nghttp3_callback_scope) { Debug(this, "Session destroy deferred (in callback scope)"); - destroy_deferred_ = true; + flags_.destroy_deferred = true; return; } @@ -2131,8 +2131,8 @@ void Session::EmitQlog(uint32_t flags, std::string_view data) { if (is_destroyed()) { auto isolate = env()->isolate(); Global recv(isolate, object()); - Global cb( - isolate, BindingData::Get(env()).session_qlog_callback()); + Global cb(isolate, + BindingData::Get(env()).session_qlog_callback()); std::string buf(data); env()->SetImmediate([recv = std::move(recv), cb = std::move(cb), @@ -2381,7 +2381,7 @@ void Session::SendBatch(Packet::Ptr* packets, if (primary_count == 0) return; // Use batched send for the primary endpoint. - if (prefer_try_send_) { + if (flags_.prefer_try_send) { endpoint().SendBatch(primary_packets, primary_count); } else { // Non-flush path: send individually via async uv_udp_send. @@ -2396,9 +2396,9 @@ void Session::FlushPendingData() { if (impl_->application_) { // Prefer synchronous sends during the deferred flush to avoid the // one-tick latency of async uv_udp_send from the uv_check callback. - prefer_try_send_ = true; + flags_.prefer_try_send = true; application().SendPendingData(); - prefer_try_send_ = false; + flags_.prefer_try_send = false; } } @@ -2422,7 +2422,7 @@ void Session::Send(Packet::Ptr packet) { // prefer synchronous send to avoid the one-tick latency of async // uv_udp_send. SendOrTrySend uses uv_udp_try_send first, falling // back to uv_udp_send on EAGAIN. - if (prefer_try_send_) { + if (flags_.prefer_try_send) { Debug(this, "Session is sending (try_send) %s", packet->ToString()); endpoint().SendOrTrySend(std::move(packet)); return; @@ -2857,7 +2857,7 @@ bool Session::can_send_packets() const { // or closing period. The callback scope check is per-session so that // one session's ngtcp2 callback does not block unrelated sessions // from sending. - return !is_destroyed() && !in_ngtcp2_callback_scope_ && + return !is_destroyed() && !flags_.in_ngtcp2_callback_scope && !is_in_draining_period() && !is_in_closing_period(); } diff --git a/src/quic/session.h b/src/quic/session.h index 472079984f3..a7b01ef5e0e 100644 --- a/src/quic/session.h +++ b/src/quic/session.h @@ -606,25 +606,30 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source { Side side_; const ngtcp2_mem* allocator_; std::unique_ptr impl_; - // These flags live on Session (not Impl) so that the NgTcp2CallbackScope - // and NgHttp3CallbackScope destructors can safely clear them even after - // Impl has been destroyed via MakeCallback re-entrancy during a callback. - // The scope is placed at the ngtcp2/nghttp3 entry point (e.g. Receive, - // OnTimeout) rather than on individual callbacks, so the deferred destroy - // only fires after all callbacks for that entry point have completed. - bool in_ngtcp2_callback_scope_ = false; - bool in_nghttp3_callback_scope_ = false; - bool destroy_deferred_ = false; - // Set when this session is in BindingData's pending_flush_sessions_ vector. - // Cleared by the flush callback before calling SendPendingData. - // Provides O(1) dedup so a session receiving multiple packets in one I/O - // burst is only scheduled for flush once. - bool pending_flush_ = false; - // When true, Session::Send prefers synchronous delivery via - // Endpoint::SendOrTrySend (uv_udp_try_send with async fallback). - // Set during FlushPendingData to avoid the one-tick latency of - // async-only sends from the uv_check callback. - bool prefer_try_send_ = false; + + struct Flags { + // These flags live on Session (not Impl) so that the NgTcp2CallbackScope + // and NgHttp3CallbackScope destructors can safely clear them even after + // Impl has been destroyed via MakeCallback re-entrancy during a callback. + // The scope is placed at the ngtcp2/nghttp3 entry point (e.g. Receive, + // OnTimeout) rather than on individual callbacks, so the deferred destroy + // only fires after all callbacks for that entry point have completed. + uint8_t in_ngtcp2_callback_scope : 1 = 0; + uint8_t in_nghttp3_callback_scope : 1 = 0; + uint8_t destroy_deferred : 1 = 0; + // Set when this session is in BindingData's pending_flush_sessions_ vector. + // Cleared by the flush callback before calling SendPendingData. + // Provides O(1) dedup so a session receiving multiple packets in one I/O + // burst is only scheduled for flush once. + uint8_t pending_flush : 1 = 0; + // When true, Session::Send prefers synchronous delivery via + // Endpoint::SendOrTrySend (uv_udp_try_send with async fallback). + // Set during FlushPendingData to avoid the one-tick latency of + // async-only sends from the uv_check callback. + uint8_t prefer_try_send : 1 = 0; + }; + Flags flags_; + QuicConnectionPointer connection_; std::unique_ptr tls_session_; friend struct NgTcp2CallbackScope; diff --git a/src/quic/streams.cc b/src/quic/streams.cc index 3bcfd544abf..255ce5bb13a 100644 --- a/src/quic/streams.cc +++ b/src/quic/streams.cc @@ -290,7 +290,7 @@ Maybe> Stream::GetDataQueueFromSource( &file_handle, value, Nothing>()); Local path; if (!ToV8Value(env->context(), file_handle->original_name()) - .ToLocal(&path)) { + .ToLocal(&path)) { return Nothing>(); } auto entry = DataQueue::CreateFdEntry(env, path); @@ -529,8 +529,9 @@ class Stream::Outbound final : public MemoryRetainer { explicit Outbound(Stream* stream) : stream_(stream), queue_(DataQueue::Create()), - reader_(queue_->get_reader()), - streaming_(true) {} + reader_(queue_->get_reader()) { + flags_.streaming = true; + } void Acknowledge(size_t amount) { size_t remaining = std::min(amount, total_ - uncommitted_); @@ -603,7 +604,7 @@ class Stream::Outbound final : public MemoryRetainer { if (queue_) queue_->cap(); } - bool is_streaming() const { return streaming_; } + bool is_streaming() const { return flags_.streaming; } size_t total() const { return total_; } size_t uncommitted() const { return uncommitted_; } @@ -615,7 +616,7 @@ class Stream::Outbound final : public MemoryRetainer { // Appends an entry to the underlying DataQueue. Only valid when // the Outbound was created in streaming mode. bool AppendEntry(std::unique_ptr entry) { - if (!streaming_ || !queue_) return false; + if (!flags_.streaming || !queue_) return false; auto size = entry->size(); auto result = queue_->append(std::move(entry)); if (result.has_value() && result.value()) { @@ -630,7 +631,7 @@ class Stream::Outbound final : public MemoryRetainer { ngtcp2_vec* data, size_t count, size_t max_count_hint) { - if (next_pending_) { + if (flags_.next_pending) { // An async read is in flight, but there may be uncommitted bytes // from a previous read that ngtcp2 didn't accept (nwrite=0 due // to pacing/congestion). Return those bytes so the send loop can @@ -643,14 +644,14 @@ class Stream::Outbound final : public MemoryRetainer { return bob::Status::STATUS_BLOCK; } - if (errored_) { + if (flags_.errored) { std::move(next)(UV_EBADF, nullptr, 0, [](int) {}); return UV_EBADF; } // If eos_ is true and there are no uncommitted bytes we'll return eos, // otherwise, return whatever is in the uncommitted queue. - if (eos_) { + if (flags_.eos) { if (uncommitted_ > 0) { PullUncommitted(std::move(next)); return bob::Status::STATUS_CONTINUE; @@ -683,8 +684,8 @@ class Stream::Outbound final : public MemoryRetainer { // If next_pending_ is true then a pull from the reader ended up // being asynchronous, our stream is blocking waiting for the data, // but we have an error! oh no! We need to error the stream. - if (next_pending_) { - next_pending_ = false; + if (flags_.next_pending) { + flags_.next_pending = false; stream_->Destroy( QuicError::ForNgtcp2Error(NGTCP2_INTERNAL_ERROR)); // We do not need to worry about calling MarkErrored in this case @@ -705,8 +706,8 @@ class Stream::Outbound final : public MemoryRetainer { // session will try to read from it again. // We must clear next_pending_ before calling ResumeStream because // ResumeStream can synchronously re-enter Outbound::Pull. - if (next_pending_) { - next_pending_ = false; + if (flags_.next_pending) { + flags_.next_pending = false; stream_->session().ResumeStream(stream_->id()); } return; @@ -732,8 +733,8 @@ class Stream::Outbound final : public MemoryRetainer { // pull from it again. // We must clear next_pending_ before calling ResumeStream because // ResumeStream can synchronously re-enter Outbound::Pull. - if (next_pending_) { - next_pending_ = false; + if (flags_.next_pending) { + flags_.next_pending = false; stream_->session().ResumeStream(stream_->id()); } }, @@ -795,7 +796,7 @@ class Stream::Outbound final : public MemoryRetainer { // rather than blocking — the async callback will resume the stream when // more data arrives. if (ret == bob::Status::STATUS_WAIT) { - next_pending_ = true; + flags_.next_pending = true; if (uncommitted_ > 0) { PullUncommitted(std::move(next)); return bob::Status::STATUS_CONTINUE; @@ -843,7 +844,7 @@ class Stream::Outbound final : public MemoryRetainer { } void MarkErrored() { - errored_ = true; + flags_.errored = true; head_.reset(); tail_ = nullptr; commit_head_ = nullptr; @@ -854,7 +855,7 @@ class Stream::Outbound final : public MemoryRetainer { } void MarkEnded() { - eos_ = true; + flags_.eos = true; queue_.reset(); reader_.reset(); } @@ -894,17 +895,17 @@ class Stream::Outbound final : public MemoryRetainer { std::shared_ptr queue_; std::shared_ptr reader_; - bool errored_ = false; - - // True when in streaming mode (non-idempotent queue, appendable). - bool streaming_ = false; - - // Will be set to true if the reader_ ends up providing a pull result - // asynchronously. - bool next_pending_ = false; - - // Will be set to true once reader_ has returned eos. - bool eos_ = false; + struct Flags { + uint8_t errored : 1 = 0; + // True when in streaming mode (non-idempotent queue, appendable). + uint8_t streaming : 1 = 0; + // Will be set to true if the reader_ ends up providing a pull result + // asynchronously. + uint8_t next_pending : 1 = 0; + // Will be set to true once reader_ has returned eos. + uint8_t eos : 1 = 0; + }; + Flags flags_; // The collection of buffers that we have pulled from reader_ and that we // are holding onto until they are acknowledged. diff --git a/src/quic/tlscontext.cc b/src/quic/tlscontext.cc index 6b708315c97..2eba97ab8ad 100644 --- a/src/quic/tlscontext.cc +++ b/src/quic/tlscontext.cc @@ -50,7 +50,7 @@ namespace quic { namespace { // Temporarily wraps an SSL pointer but does not take ownership. -// Use by a few of the TLSSession methods that need access to the SSL* +// Used by a few of the TLSSession methods that need access to the SSL* // pointer held by the OSSLContext but cannot take ownership of it. class SSLPointerRef final { public: @@ -188,7 +188,7 @@ void OSSLContext::reset() { if (ctx_) { // The SSL object inside the ngtcp2 ctx may not have been set if // SSL creation failed. Guard against null before clearing app data. - if (SSL* ssl = ngtcp2_crypto_ossl_ctx_get_ssl(ctx_); ssl != nullptr) { + if (SSL* ssl = *this; ssl != nullptr) { SSL_set_app_data(ssl, nullptr); } // connection_ is set during Initialize(). If Initialize() was @@ -225,7 +225,7 @@ void OSSLContext::Initialize(SSL* ssl, connection_ = connection; } -std::string OSSLContext::get_cipher_name() const { +std::string_view OSSLContext::get_cipher_name() const { return SSL_get_cipher_name(*this); } diff --git a/src/quic/tlscontext.h b/src/quic/tlscontext.h index 335f577e399..c1d9b95d561 100644 --- a/src/quic/tlscontext.h +++ b/src/quic/tlscontext.h @@ -45,7 +45,7 @@ class OSSLContext final { ngtcp2_conn* connection, SSL_CTX* ssl_ctx); - std::string get_cipher_name() const; + std::string_view get_cipher_name() const; std::string get_selected_alpn() const; std::string_view get_negotiated_group() const;