quic: apply multiple additional minor improvements

Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63267
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell committed 2026-05-21 14:16:51 -07:00
1 parent 137f7aecab
commit 016384726e
10 files changed
+109 -92

No files matched your search

+11 -11
View File
@@ -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();
}
}
+6 -2
View File
@@ -137,7 +137,9 @@ Store Store::CopyFrom(Local<ArrayBuffer> 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<ArrayBufferView> 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) {
+12 -12
View File
@@ -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<int>(options.udp_receive_buffer_size);
if (size > 0) {
err = uv_recv_buffer_size(reinterpret_cast<uv_handle_t*>(&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>(session));
}
+6 -3
View File
@@ -343,9 +343,12 @@ class Endpoint final : public AsyncWrap, public Packet::Listener {
class Impl;
BaseObjectWeakPtr<Impl> 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;
+7 -3
View File
@@ -13,7 +13,7 @@
#include "node_external_reference.h"
#include <ngtcp2/ngtcp2_crypto_ossl.h>
#include <mutex>
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<Object> target,
Local<Value> unused,
Local<Context> 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);
+10 -10
View File
@@ -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<Object> recv(isolate, object());
Global<Function> cb(
isolate, BindingData::Get(env()).session_qlog_callback());
Global<Function> 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();
}
+24 -19
View File
@@ -606,25 +606,30 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
Side side_;
const ngtcp2_mem* allocator_;
std::unique_ptr<Impl> 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<TLSSession> tls_session_;
friend struct NgTcp2CallbackScope;
+29 -28
View File
@@ -290,7 +290,7 @@ Maybe<std::shared_ptr<DataQueue>> Stream::GetDataQueueFromSource(
&file_handle, value, Nothing<std::shared_ptr<DataQueue>>());
Local<Value> path;
if (!ToV8Value(env->context(), file_handle->original_name())
.ToLocal(&path)) {
.ToLocal(&path)) {
return Nothing<std::shared_ptr<DataQueue>>();
}
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<DataQueue::Entry> 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<DataQueue> queue_;
std::shared_ptr<DataQueue::Reader> 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.
+3 -3
View File
@@ -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);
}
+1 -1
View File
@@ -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;