Commit f442b5a2328 for nodejs
commit f442b5a2328ac02af3cdff4d0b53ba02d1fccf81
Author: Yuya Inoue <65857152+inoway46@users.noreply.github.com>
Date: Fri Nov 20 01:39:21 2026 +0900
http2: add callback to informational header methods
In the HTTP/1 server, writeContinue(), writeEarlyHints() and
writeInformation() accept a callback that is called once the response
has been written to the socket. The HTTP/2 compat versions did not, so
code moving to the compat API had its callback ignored.
Accept an optional callback in http2stream.additionalHeaders() and in
the three compat methods. The request for the HEADERS frame is tracked
until nghttp2 serializes the frame, and completed together with the
write to the underlying stream that carries it.
Signed-off-by: inoway46 <inoueyuya416@gmail.com>
Assisted-by: claude:opus-5.5
PR-URL: https://github.com/nodejs/node/pull/67470
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Tim Perry <pimterry@gmail.com>
diff --git a/doc/api/http2.md b/doc/api/http2.md
index ecaefb0e990..2729820e5d8 100644
--- a/doc/api/http2.md
+++ b/doc/api/http2.md
@@ -1818,13 +1818,20 @@ used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server
provide additional methods such as `http2stream.pushStream()` and
`http2stream.respond()` that are only relevant on the server.
-#### `http2stream.additionalHeaders(headers)`
+#### `http2stream.additionalHeaders(headers[, callback])`
<!-- YAML
added: v8.4.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67470
+ description: Added the `callback` argument.
-->
* `headers` {HTTP/2 Headers Object}
+* `callback` {Function} Optional, called once the `HEADERS` frame has been
+ written to the socket, or with an error if it could not be written.
+ * `err` {Error|null}
Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer.
@@ -5057,23 +5064,40 @@ Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is free again.
-#### `response.writeContinue()`
+#### `response.writeContinue([callback])`
<!-- YAML
added: v8.4.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67470
+ description: Added the `callback` argument.
-->
+* `callback` {Function} Optional, called once the informational headers
+ have been written to the socket, or with an error if they could not be
+ written. It is not called if nothing is sent.
+ * `err` {Error|null}
+
Sends a status `100 Continue` to the client, indicating that the request body
should be sent. See the [`'checkContinue'`][] event on `Http2Server` and
`Http2SecureServer`.
-#### `response.writeEarlyHints(hints)`
+#### `response.writeEarlyHints(hints[, callback])`
<!-- YAML
added: v18.11.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67470
+ description: Added the `callback` argument.
-->
* `hints` {Object}
+* `callback` {Function} Optional, called once the informational headers
+ have been written to the socket, or with an error if they could not be
+ written. It is not called if nothing is sent.
+ * `err` {Error|null}
Sends a status `103 Early Hints` to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
@@ -5097,12 +5121,16 @@ response.writeEarlyHints({
});
```
-#### `response.writeInformation(statusCode[, headers])`
+#### `response.writeInformation(statusCode[, headers[, callback]])`
<!-- YAML
added:
- v26.2.0
- v24.18.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67470
+ description: Added the `callback` argument.
-->
* `statusCode` {number} An HTTP 1xx informational status code, between `100`
@@ -5110,6 +5138,10 @@ added:
allowed in HTTP/2.
* `headers` {Object} An optional object of headers to send with the
informational response.
+* `callback` {Function} Optional, called once the informational headers
+ have been written to the socket, or with an error if they could not be
+ written. It is not called if nothing is sent.
+ * `err` {Error|null}
Sends an arbitrary HTTP 1xx informational response, equivalent in HTTP/2 to a
`HEADERS` frame whose `:status` pseudo-header is a 1xx code. May be called
@@ -5334,8 +5366,8 @@ you need to implement any fall-back behavior yourself.
[`response.writableEnded`]: #responsewritableended
[`response.write()`]: #responsewritechunk-encoding-callback
[`response.write(data, encoding)`]: http.md#responsewritechunk-encoding-callback
-[`response.writeContinue()`]: #responsewritecontinue
-[`response.writeEarlyHints()`]: #responsewriteearlyhintshints
+[`response.writeContinue()`]: #responsewritecontinuecallback
+[`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
[`server.close()`]: #serverclosecallback
[`server.maxHeadersCount`]: http.md#servermaxheaderscount
diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js
index 34f16576da6..1ba00e80399 100644
--- a/lib/internal/http2/compat.js
+++ b/lib/internal/http2/compat.js
@@ -970,7 +970,7 @@ class Http2ServerResponse extends Stream {
this[kStream].respond(headers, options);
}
- writeInformation(statusCode, headers) {
+ writeInformation(statusCode, headers, cb) {
if (typeof statusCode !== 'number' ||
statusCode < 100 || statusCode > 199) {
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
@@ -978,6 +978,8 @@ class Http2ServerResponse extends Stream {
if (statusCode === 101) {
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
}
+ if (cb !== undefined)
+ validateFunction(cb, 'callback');
const stream = this[kStream];
@@ -994,16 +996,15 @@ class Http2ServerResponse extends Stream {
}
outHeaders[HTTP2_HEADER_STATUS] = statusCode;
- stream.additionalHeaders(outHeaders);
+ stream.additionalHeaders(outHeaders, cb);
return true;
}
- // TODO doesn't support callbacks
- writeContinue() {
- return this.writeInformation(HTTP_STATUS_CONTINUE);
+ writeContinue(cb) {
+ return this.writeInformation(HTTP_STATUS_CONTINUE, undefined, cb);
}
- writeEarlyHints(hints) {
+ writeEarlyHints(hints, cb) {
validateObject(hints, 'hints');
const headers = { __proto__: null };
@@ -1026,7 +1027,7 @@ class Http2ServerResponse extends Stream {
headers.Link = linkHeaderValue;
- return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers);
+ return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers, cb);
}
}
diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index fe1c3031e3c..926a72c8f1f 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -67,6 +67,7 @@ const { AsyncResource } = require('async_hooks');
const {
AbortError,
+ ErrnoException,
aggregateTwoErrors,
codes: {
ERR_HTTP2_ALTSVC_INVALID_ORIGIN,
@@ -190,6 +191,7 @@ const { FileHandle } = internalBinding('fs');
const binding = internalBinding('http2');
const {
ShutdownWrap,
+ WriteWrap,
kReadBytesOrError,
streamBaseState,
} = internalBinding('stream_wrap');
@@ -3501,14 +3503,17 @@ class ServerHttp2Stream extends Http2Stream {
// such that HEADERS may only be sent *before* or *after* DATA frames.
// If the block of headers being sent includes a status code, it MUST be
// a 1xx informational code and it MUST be sent before the request/response
- // headers are sent, or an error will be thrown.
- additionalHeaders(headers) {
+ // headers are sent, or an error will be thrown. The optional callback is
+ // called once the HEADERS frame has been written to the socket.
+ additionalHeaders(headers, callback) {
if (this.destroyed || this.closed)
throw new ERR_HTTP2_INVALID_STREAM();
if (this.headersSent)
throw new ERR_HTTP2_HEADERS_AFTER_RESPOND();
assertIsObject(headers, 'headers');
+ if (callback !== undefined)
+ validateFunction(callback, 'callback');
headers = ObjectAssign({ __proto__: null }, headers);
debugStreamObj(this, 'sending additional headers');
@@ -3534,12 +3539,32 @@ class ServerHttp2Stream extends Http2Stream {
else
this[kInfoHeaders].push(headers);
- const ret = this[kHandle].info(headersList);
- if (ret < 0)
- this.destroy(new NghttpError(ret));
+ let req;
+ if (callback !== undefined) {
+ req = new WriteWrap();
+ req.oncomplete = onInfoHeadersComplete;
+ req.callback = callback;
+ }
+
+ const ret = this[kHandle].info(headersList, req);
+ if (ret < 0) {
+ const err = new NghttpError(ret);
+ this.destroy(err);
+ if (callback !== undefined)
+ process.nextTick(callback, err);
+ }
}
}
+// Called once an informational HEADERS frame has been written to the socket,
+// or once it is known that it will not be.
+function onInfoHeadersComplete(status) {
+ if (status < 0)
+ this.callback(new ErrnoException(status, 'write', this.error));
+ else
+ this.callback(null);
+}
+
ServerHttp2Stream.prototype[kProceed] = ServerHttp2Stream.prototype.respond;
class ClientHttp2Stream extends Http2Stream {
diff --git a/src/node_http2.cc b/src/node_http2.cc
index 3a357eaf449..92ca4e7d452 100644
--- a/src/node_http2.cc
+++ b/src/node_http2.cc
@@ -1320,6 +1320,9 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle,
Debug(session, "frame type %d was not sent, code: %d",
frame->hd.type, error_code);
+ if (frame->hd.type == NGHTTP2_HEADERS)
+ session->HandleInfoHeadersFrame(frame, UV_ECANCELED);
+
if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
error_code == NGHTTP2_ERR_STREAM_CLOSED ||
error_code == NGHTTP2_ERR_STREAM_CLOSING) {
@@ -1361,6 +1364,9 @@ int Http2Session::OnFrameSent(nghttp2_session* handle,
Http2Session* session = static_cast<Http2Session*>(user_data);
session->statistics_.frame_sent += 1;
+ if (frame->hd.type == NGHTTP2_HEADERS)
+ session->HandleInfoHeadersFrame(frame, 0);
+
// If nghttp2 has internally terminated the session (e.g. due to a protocol
// error like oversized frames, padding errors, or HPACK compression
// failures), it calls nghttp2_session_terminate_session() directly which
@@ -2005,6 +2011,12 @@ void Http2Session::ClearOutgoing(int status) {
set_sending(false);
+ // Completing a request can start the next write. Take the requests that
+ // belong to the write that has just finished before completing any of them,
+ // so that the ones of the next write are left alone.
+ std::vector<OutgoingInfoReq> info_reqs;
+ info_reqs.swap(outgoing_info_reqs_);
+
if (!outgoing_buffers_.empty()) {
outgoing_storage_.clear();
outgoing_length_ = 0;
@@ -2022,6 +2034,11 @@ void Http2Session::ClearOutgoing(int status) {
}
}
+ for (const OutgoingInfoReq& req : info_reqs) {
+ WriteWrap::FromObject(req.req_wrap)
+ ->Done(req.status != 0 ? req.status : status);
+ }
+
// Now that we've finished sending queued data, if there are any pending
// RstStreams we should try sending again and then flush them one by one.
if (status == 0 && !pending_rst_streams_.empty()) {
@@ -2039,6 +2056,24 @@ void Http2Session::ClearOutgoing(int status) {
}
}
+// Called when nghttp2 has serialized a HEADERS frame, or has given up on
+// sending it. Informational HEADERS frames are always sent before any other
+// HEADERS frame of the same stream, and in the order they were submitted in,
+// so if the stream still has informational headers pending, this frame is the
+// oldest of them. Its request is completed in ClearOutgoing(), once the
+// current write to the underlying stream has finished.
+void Http2Session::HandleInfoHeadersFrame(const nghttp2_frame* frame,
+ int status) {
+ BaseObjectPtr<Http2Stream> stream = FindStream(frame->hd.stream_id);
+ if (!stream || stream->info_reqs_.empty()) return;
+ BaseObjectPtr<AsyncWrap> req_wrap = std::move(stream->info_reqs_.front());
+ stream->info_reqs_.pop();
+ if (req_wrap) {
+ outgoing_info_reqs_.push_back(
+ {std::move(req_wrap), std::move(stream), status});
+ }
+}
+
void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) {
outgoing_length_ += write.buf.len;
outgoing_buffers_.emplace_back(std::move(write));
@@ -2314,6 +2349,9 @@ bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
for (const NgHttp2StreamWrite& wr : outgoing_buffers_) {
if (wr.stream.get() == stream) return true;
}
+ for (const OutgoingInfoReq& req : outgoing_info_reqs_) {
+ if (req.stream.get() == stream) return true;
+ }
return false;
}
@@ -2418,6 +2456,7 @@ Http2Stream::~Http2Stream() {
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("current_headers", current_headers_);
tracker->TrackField("queue", queue_);
+ tracker->TrackField("info_reqs", info_reqs_);
}
std::string Http2Stream::diagnostic_name() const {
@@ -2542,6 +2581,7 @@ void Http2Stream::CompleteDestroyCleanup() {
WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED);
queue_.pop();
}
+ CancelPendingInfoRequests();
// We can destroy the stream now if there are no writes for it
// already on the socket. Otherwise, we'll wait for the garbage collector
@@ -2588,7 +2628,15 @@ int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) {
// Submit informational headers for a stream.
-int Http2Stream::SubmitInfo(const Http2Headers& headers) {
+void Http2Stream::CancelPendingInfoRequests() {
+ while (!info_reqs_.empty()) {
+ BaseObjectPtr<AsyncWrap> req_wrap = std::move(info_reqs_.front());
+ info_reqs_.pop();
+ if (req_wrap) WriteWrap::FromObject(req_wrap)->Done(UV_ECANCELED);
+ }
+}
+
+int Http2Stream::SubmitInfo(const Http2Headers& headers, WriteWrap* req_wrap) {
CHECK(!this->is_destroyed());
Http2Scope h2scope(this);
Debug(this, "sending %d informational headers", headers.length());
@@ -2601,6 +2649,12 @@ int Http2Stream::SubmitInfo(const Http2Headers& headers) {
headers.length(),
nullptr);
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
+ if (ret == 0) {
+ info_reqs_.emplace(req_wrap != nullptr ? req_wrap->GetAsyncWrap()
+ : nullptr);
+ } else if (req_wrap != nullptr) {
+ req_wrap->Dispose();
+ }
return ret;
}
@@ -3309,7 +3363,16 @@ void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
Local<Array> headers = args[0].As<Array>();
- args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers)));
+ // The optional request object is completed once the HEADERS frame has been
+ // written to the socket.
+ WriteWrap* req_wrap = nullptr;
+ if (args[1]->IsObject()) {
+ AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(stream);
+ req_wrap = stream->CreateWriteWrap(args[1].As<Object>());
+ }
+
+ args.GetReturnValue().Set(
+ stream->SubmitInfo(Http2Headers(env, headers), req_wrap));
}
// Submits trailing headers on the Http2Stream
diff --git a/src/node_http2.h b/src/node_http2.h
index 5016cb98ad5..972b829425e 100644
--- a/src/node_http2.h
+++ b/src/node_http2.h
@@ -347,8 +347,12 @@ class Http2Stream : public AsyncWrap,
// Initiate a response on this stream.
int SubmitResponse(const Http2Headers& headers, int options);
- // Submit informational headers for this stream
- int SubmitInfo(const Http2Headers& headers);
+ // Submit informational headers for this stream. If a request is given, it
+ // is completed once the HEADERS frame has been written to the socket.
+ int SubmitInfo(const Http2Headers& headers, WriteWrap* req_wrap = nullptr);
+
+ // Cancels the requests of informational headers that have not been sent.
+ void CancelPendingInfoRequests();
// Submit trailing headers for this stream
int SubmitTrailers(const Http2Headers& headers);
@@ -585,6 +589,11 @@ class Http2Stream : public AsyncWrap,
std::queue<NgHttp2StreamWrite> queue_;
size_t available_outbound_length_ = 0;
+ // One entry per informational HEADERS frame that has been submitted to
+ // nghttp2 but not serialized yet, in submission order. An entry is empty
+ // if no completion callback was requested for that frame.
+ std::queue<BaseObjectPtr<AsyncWrap>> info_reqs_;
+
Http2StreamListener stream_listener_;
friend class Http2Session;
@@ -1068,6 +1077,16 @@ class Http2Session : public AsyncWrap,
struct custom_settings_state remote_custom_settings_;
std::vector<NgHttp2StreamWrite> outgoing_buffers_;
+ // Requests of informational HEADERS frames that are part of the current
+ // write. The stream is retained until the request has been completed,
+ // because the request refers to it. A status of 0 means that the status of
+ // the write to the underlying stream is used.
+ struct OutgoingInfoReq {
+ BaseObjectPtr<AsyncWrap> req_wrap;
+ BaseObjectPtr<Http2Stream> stream;
+ int status;
+ };
+ std::vector<OutgoingInfoReq> outgoing_info_reqs_;
std::vector<uint8_t> outgoing_storage_;
size_t outgoing_length_ = 0;
std::vector<int32_t> pending_rst_streams_;
@@ -1089,6 +1108,7 @@ class Http2Session : public AsyncWrap,
void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length);
void ClearOutgoing(int status);
+ void HandleInfoHeadersFrame(const nghttp2_frame* frame, int status);
void FinishClose(uint32_t code, bool socket_closed, int write_status = 0);
void MaybeFinishPendingClose(int status = 0);
diff --git a/test/parallel/test-http2-compat-write-information-callback.js b/test/parallel/test-http2-compat-write-information-callback.js
new file mode 100644
index 00000000000..ecca7897ed2
--- /dev/null
+++ b/test/parallel/test-http2-compat-write-information-callback.js
@@ -0,0 +1,144 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto) common.skip('missing crypto');
+
+const assert = require('node:assert');
+const http2 = require('node:http2');
+
+// The callback passed to writeContinue(), writeEarlyHints() and
+// writeInformation() is called asynchronously, in order, once the
+// informational headers have been written to the socket.
+{
+ const server = http2.createServer();
+
+ server.on('request', common.mustCall((req, res) => {
+ const { socket } = res.stream.session;
+ const bytesWritten = socket.bytesWritten;
+ const order = [];
+ let sync = true;
+
+ assert.strictEqual(res.writeContinue(common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ assert.strictEqual(sync, false);
+ assert.ok(socket.bytesWritten > bytesWritten);
+ order.push(100);
+ })), true);
+ assert.strictEqual(res.writeEarlyHints({
+ link: '</styles.css>; rel=preload; as=style',
+ }, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ order.push(103);
+ })), true);
+ const onInformation = common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ order.push(110);
+ assert.deepStrictEqual(order, [100, 103, 110]);
+ res.end('done');
+ });
+ assert.strictEqual(
+ res.writeInformation(110, { 'X-Progress': '50%' }, onInformation), true);
+ sync = false;
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ const req = client.request();
+
+ const seen = [];
+ req.on('headers', (headers) => seen.push(headers[':status']));
+ req.on('response', common.mustCall((headers) => {
+ assert.strictEqual(headers[':status'], 200);
+ assert.deepStrictEqual(seen, [100, 103, 110]);
+ }));
+
+ req.resume();
+ req.on('end', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// The headers can be omitted, with or without a callback.
+{
+ const server = http2.createServer();
+
+ server.on('request', common.mustCall((req, res) => {
+ const order = [];
+
+ assert.strictEqual(res.writeInformation(102), true);
+ assert.strictEqual(res.writeInformation(102, { 'X-Call': 'headers' }), true);
+ assert.strictEqual(res.writeInformation(
+ 102, { 'X-Call': 'headers-callback' }, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ order.push('headers-callback');
+ })), true);
+ assert.strictEqual(res.writeInformation(
+ 102, undefined, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ order.push('undefined-callback');
+ assert.deepStrictEqual(
+ order, ['headers-callback', 'undefined-callback']);
+ res.end('done');
+ })), true);
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ const req = client.request();
+
+ const seen = [];
+ req.on('headers', (headers) => {
+ seen.push([headers[':status'], headers['x-call']]);
+ });
+ req.on('response', common.mustCall((headers) => {
+ assert.strictEqual(headers[':status'], 200);
+ assert.deepStrictEqual(seen, [
+ [102, undefined],
+ [102, 'headers'],
+ [102, 'headers-callback'],
+ [102, undefined],
+ ]);
+ }));
+
+ req.resume();
+ req.on('end', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// The callback is not called when nothing is sent, and a non-function
+// callback is rejected.
+{
+ const server = http2.createServer();
+
+ server.on('request', common.mustCall((req, res) => {
+ for (const cb of [null, 1, 'cb', {}]) {
+ assert.throws(() => res.writeContinue(cb),
+ { code: 'ERR_INVALID_ARG_TYPE' });
+ assert.throws(() => res.writeInformation(110, undefined, cb),
+ { code: 'ERR_INVALID_ARG_TYPE' });
+ assert.throws(() => res.writeEarlyHints({ link: '</a>' }, cb),
+ { code: 'ERR_INVALID_ARG_TYPE' });
+ }
+
+ res.writeHead(200);
+ assert.strictEqual(res.writeContinue(common.mustNotCall()), false);
+ assert.strictEqual(
+ res.writeInformation(110, undefined, common.mustNotCall()), false);
+ res.end();
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ const req = client.request();
+ req.resume();
+ req.on('end', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
diff --git a/test/parallel/test-http2-info-headers-callback-reentrant.js b/test/parallel/test-http2-info-headers-callback-reentrant.js
new file mode 100644
index 00000000000..767dcd72e8b
--- /dev/null
+++ b/test/parallel/test-http2-info-headers-callback-reentrant.js
@@ -0,0 +1,75 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+ common.skip('missing crypto');
+
+const assert = require('assert');
+const http2 = require('http2');
+const { duplexPair } = require('stream');
+const { setImmediate } = require('timers/promises');
+
+// Informational headers that are sent from the completion callback of another
+// write belong to the next write to the underlying stream. Their callback must
+// not be called before that write has finished.
+
+(async () => {
+ const [clientSide, serverSide] = duplexPair();
+ let hold = false;
+ let pendingWrite;
+ const originalWrite = serverSide._write;
+ serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) {
+ if (hold) {
+ // Deliver the data, but do not complete the write.
+ assert.strictEqual(pendingWrite, undefined);
+ originalWrite.call(this, buf, enc, common.mustCall(() => {
+ pendingWrite = cb;
+ }));
+ return;
+ }
+ originalWrite.call(this, buf, enc, cb);
+ });
+
+ const server = http2.createServer();
+ let called = false;
+ let first;
+ server.on('stream', common.mustCall((stream) => {
+ if (first === undefined) {
+ first = stream;
+ return;
+ }
+ first.respond();
+ first.write('data', common.mustCall(() => {
+ // This runs while the write that carried the DATA frame is being
+ // completed. Closing the first stream starts the next write, which
+ // carries the informational headers of the second stream.
+ hold = true;
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ called = true;
+ }));
+ first.close();
+ }));
+ }, 2));
+ server.emit('connection', serverSide);
+
+ const client = http2.connect('http://localhost', {
+ createConnection: () => clientSide,
+ });
+ const req1 = client.request();
+ req1.on('error', () => {});
+ req1.resume();
+ const req2 = client.request();
+ req2.resume();
+ await new Promise((resolve) => req2.on('headers', common.mustCall(resolve)));
+
+ assert.strictEqual(typeof pendingWrite, 'function');
+ assert.strictEqual(called, false);
+ hold = false;
+ pendingWrite();
+ await setImmediate();
+ assert.strictEqual(called, true);
+
+ client.destroy();
+ server.close();
+})().then(common.mustCall());
diff --git a/test/parallel/test-http2-info-headers-callback.js b/test/parallel/test-http2-info-headers-callback.js
new file mode 100644
index 00000000000..e59e339069e
--- /dev/null
+++ b/test/parallel/test-http2-info-headers-callback.js
@@ -0,0 +1,171 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto) common.skip('missing crypto');
+
+const assert = require('node:assert');
+const http2 = require('node:http2');
+const { duplexPair } = require('node:stream');
+
+// The callback passed to additionalHeaders() is called once the HEADERS frame
+// has been written to the socket.
+{
+ const server = http2.createServer();
+
+ server.on('stream', common.mustCall((stream) => {
+ const { socket } = stream.session;
+ const bytesWritten = socket.bytesWritten;
+ let sync = true;
+
+ for (const callback of [null, 1, 'callback', {}]) {
+ assert.throws(() => stream.additionalHeaders({ ':status': 103 }, callback),
+ { code: 'ERR_INVALID_ARG_TYPE' });
+ }
+
+ // Informational headers without a callback do not shift the callbacks of
+ // the ones that follow.
+ stream.additionalHeaders({ ':status': 102 });
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ assert.strictEqual(sync, false);
+ assert.ok(socket.bytesWritten > bytesWritten);
+ stream.respond();
+ stream.end('done');
+ }));
+ sync = false;
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ const req = client.request();
+
+ const seen = [];
+ req.on('headers', (headers) => seen.push(headers[':status']));
+ req.on('response', common.mustCall((headers) => {
+ assert.strictEqual(headers[':status'], 200);
+ assert.deepStrictEqual(seen, [102, 103]);
+ }));
+
+ req.resume();
+ req.on('end', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// The callback is called with an error if the session is destroyed before the
+// HEADERS frame is written.
+{
+ const server = http2.createServer();
+
+ server.on('stream', common.mustCall((stream) => {
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err.code, 'ECANCELED');
+ server.close();
+ }));
+ stream.session.destroy();
+ }));
+
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ client.on('error', () => {});
+ const req = client.request();
+ req.on('headers', common.mustNotCall());
+ req.on('error', () => {});
+ req.on('close', common.mustCall(() => client.destroy()));
+ req.resume();
+ }));
+}
+
+// The callback is called with an error if the write to the underlying stream
+// that carries the HEADERS frame fails.
+{
+ const kHeadersFrameType = 1;
+ const hasHeadersFrame = (buf) => {
+ for (let offset = 0; offset + 9 <= buf.length;) {
+ if (buf[offset + 3] === kHeadersFrameType)
+ return true;
+ offset += 9 + buf.readUIntBE(offset, 3);
+ }
+ return false;
+ };
+
+ const [clientSide, serverSide] = duplexPair();
+ const originalWrite = serverSide._write;
+ serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) {
+ if (hasHeadersFrame(buf))
+ return cb(new Error('write failed'));
+ originalWrite.call(this, buf, enc, cb);
+ });
+
+ const server = http2.createServer();
+ server.on('sessionError', common.mustCall());
+ server.on('stream', common.mustCall((stream) => {
+ stream.on('error', common.mustCall());
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err.code, 'EPIPE');
+ assert.strictEqual(err.syscall, 'write');
+ client.destroy();
+ }));
+ }));
+ server.emit('connection', serverSide);
+
+ const client = http2.connect('http://localhost', {
+ createConnection: () => clientSide,
+ });
+ client.on('error', () => {});
+ const req = client.request();
+ req.on('headers', common.mustNotCall());
+ req.on('error', () => {});
+ req.resume();
+}
+
+// The callback is called with an error if the stream is destroyed before the
+// HEADERS frame has been serialized. This happens when another write to the
+// underlying stream is still in progress, so that the frame is still queued.
+{
+ const [clientSide, serverSide] = duplexPair();
+ let hold = false;
+ let pendingWrite;
+ let onHold;
+ const originalWrite = serverSide._write;
+ serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) {
+ if (!hold)
+ return originalWrite.call(this, buf, enc, cb);
+ // Deliver the data, but do not complete the write yet.
+ originalWrite.call(this, buf, enc, common.mustCall(() => {
+ pendingWrite = cb;
+ onHold();
+ }));
+ });
+
+ const server = http2.createServer();
+ server.on('stream', common.mustCall((stream) => {
+ onHold = common.mustCall(() => {
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err.code, 'ECANCELED');
+ hold = false;
+ pendingWrite();
+ }));
+ stream.destroy();
+ });
+ hold = true;
+ stream.additionalHeaders({ ':status': 102 });
+ }));
+ server.emit('connection', serverSide);
+
+ const client = http2.connect('http://localhost', {
+ createConnection: () => clientSide,
+ });
+ client.on('error', () => {});
+ const req = client.request();
+ const seen = [];
+ req.on('headers', (headers) => seen.push(headers[':status']));
+ req.on('error', () => {});
+ req.on('close', common.mustCall(() => {
+ assert.deepStrictEqual(seen, [102]);
+ client.destroy();
+ }));
+ req.resume();
+}
diff --git a/test/parallel/test-http2-info-headers-errors.js b/test/parallel/test-http2-info-headers-errors.js
index aa1e28222c4..72f23553457 100644
--- a/test/parallel/test-http2-info-headers-errors.js
+++ b/test/parallel/test-http2-info-headers-errors.js
@@ -4,6 +4,7 @@
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
+const assert = require('assert');
const http2 = require('http2');
const { internalBinding } = require('internal/test/binding');
const {
@@ -57,7 +58,11 @@ server.on('stream', common.mustCall((stream, headers) => {
stream.on('error', errorMustNotCall);
}
- stream.additionalHeaders({ ':status': 100 });
+ // The callback is called with the same error.
+ stream.additionalHeaders({ ':status': 100 }, common.mustCall((err) => {
+ assert.strictEqual(err.code, currentError.error.code);
+ assert.strictEqual(err.message, currentError.error.message);
+ }));
}, tests.length));
server.listen(0, common.mustCall(() => runTest(tests.shift())));
diff --git a/test/parallel/test-http2-info-headers-reset-pending-write.js b/test/parallel/test-http2-info-headers-reset-pending-write.js
new file mode 100644
index 00000000000..9b9e417086b
--- /dev/null
+++ b/test/parallel/test-http2-info-headers-reset-pending-write.js
@@ -0,0 +1,82 @@
+// Flags: --expose-gc
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+ common.skip('missing crypto');
+
+const assert = require('assert');
+const http2 = require('http2');
+const { duplexPair } = require('stream');
+const { setImmediate } = require('timers/promises');
+
+// The stream can be reset and garbage collected while the write that carries
+// its informational headers is still pending. The callback must not be called
+// before that write has finished, and completing it must not crash.
+
+const { NGHTTP2_CANCEL } = http2.constants;
+const kHeadersFrameType = 1;
+
+function hasHeadersFrame(buf) {
+ for (let offset = 0; offset + 9 <= buf.length;) {
+ if (buf[offset + 3] === kHeadersFrameType)
+ return true;
+ offset += 9 + buf.readUIntBE(offset, 3);
+ }
+ return false;
+}
+
+(async () => {
+ const [clientSide, serverSide] = duplexPair();
+ let pendingWrite;
+ const originalWrite = serverSide._write;
+ serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) {
+ // Deliver the data, but do not complete the write that carries the
+ // informational headers.
+ const hold = hasHeadersFrame(buf);
+ originalWrite.call(this, buf, enc, common.mustCall(() => {
+ if (hold) {
+ assert.strictEqual(pendingWrite, undefined);
+ pendingWrite = cb;
+ } else {
+ cb();
+ }
+ }));
+ });
+
+ const server = http2.createServer();
+ let called = false;
+ let streamClosed;
+ const closed = new Promise((resolve) => { streamClosed = resolve; });
+ server.on('stream', common.mustCall((stream) => {
+ stream.on('close', common.mustCall(streamClosed));
+ stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => {
+ assert.strictEqual(err, null);
+ called = true;
+ }));
+ }));
+ server.emit('connection', serverSide);
+
+ const client = http2.connect('http://localhost', {
+ createConnection: () => clientSide,
+ });
+ const req = client.request();
+ req.on('headers', common.mustCall(() => req.close(NGHTTP2_CANCEL)));
+ req.resume();
+
+ await closed;
+ // Let the deferred native stream cleanup run, then collect the wrapper
+ // while the write is still awaiting completion.
+ for (let i = 0; i < 10; i++) {
+ await setImmediate();
+ global.gc();
+ }
+ assert.strictEqual(typeof pendingWrite, 'function');
+ assert.strictEqual(called, false);
+ pendingWrite();
+ await setImmediate();
+ assert.strictEqual(called, true);
+
+ client.destroy();
+ server.close();
+})().then(common.mustCall());