From 2af555e35db2591a66ba1f67c0ba6ec365d29c5b Mon Sep 17 00:00:00 2001 From: inoway46 Date: Sun, 15 Nov 2026 00:37:19 +0900 Subject: [PATCH] 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 Assisted-by: claude:opus-5.5 --- doc/api/http2.md | 44 ++++- lib/internal/http2/compat.js | 15 +- lib/internal/http2/core.js | 35 +++- src/node_http2.cc | 67 ++++++- src/node_http2.h | 24 ++- ...http2-compat-write-information-callback.js | 144 +++++++++++++++ ...t-http2-info-headers-callback-reentrant.js | 75 ++++++++ .../test-http2-info-headers-callback.js | 171 ++++++++++++++++++ .../test-http2-info-headers-errors.js | 7 +- ...-http2-info-headers-reset-pending-write.js | 82 +++++++++ 10 files changed, 641 insertions(+), 23 deletions(-) create mode 100644 test/parallel/test-http2-compat-write-information-callback.js create mode 100644 test/parallel/test-http2-info-headers-callback-reentrant.js create mode 100644 test/parallel/test-http2-info-headers-callback.js create mode 100644 test/parallel/test-http2-info-headers-reset-pending-write.js diff --git a/doc/api/http2.md b/doc/api/http2.md index ecaefb0e990d..2729820e5d86 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])` * `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])` +* `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])` * `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]])` * `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 2eedfd39010a..350ef132fa64 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -957,7 +957,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); @@ -965,6 +965,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]; @@ -981,16 +983,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 }; @@ -1013,7 +1014,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 d3695145115f..d369e144d007 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, @@ -188,6 +189,7 @@ const { FileHandle } = internalBinding('fs'); const binding = internalBinding('http2'); const { ShutdownWrap, + WriteWrap, kReadBytesOrError, streamBaseState, } = internalBinding('stream_wrap'); @@ -3460,14 +3462,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'); @@ -3493,12 +3498,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 f00a7a65c32c..5a6d6e85dc5d 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(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 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 stream = FindStream(frame->hd.stream_id); + if (!stream || stream->info_reqs_.empty()) return; + BaseObjectPtr 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 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; } @@ -3296,7 +3350,16 @@ void Http2Stream::Info(const FunctionCallbackInfo& args) { Local headers = args[0].As(); - 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()); + } + + 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 5016cb98ad5f..972b829425e2 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 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> 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 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 req_wrap; + BaseObjectPtr stream; + int status; + }; + std::vector outgoing_info_reqs_; std::vector outgoing_storage_; size_t outgoing_length_ = 0; std::vector 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 000000000000..ecca7897ed2c --- /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: '; 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: '' }, 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 000000000000..767dcd72e8b0 --- /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 000000000000..e59e339069ee --- /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 aa1e28222c4c..72f235534571 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 000000000000..9b9e417086b5 --- /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());