Skip to content

Commit a24bd18

Browse files
committed
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
1 parent 2e59a6d commit a24bd18

10 files changed

Lines changed: 641 additions & 23 deletions

‎doc/api/http2.md‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1818,13 +1818,20 @@ used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server
18181818
provide additional methods such as `http2stream.pushStream()` and
18191819
`http2stream.respond()` that are only relevant on the server.
18201820

1821-
#### `http2stream.additionalHeaders(headers)`
1821+
#### `http2stream.additionalHeaders(headers[, callback])`
18221822

18231823
<!-- YAML
18241824
added: v8.4.0
1825+
changes:
1826+
- version: REPLACEME
1827+
pr-url: https://github.com/nodejs/node/pull/67470
1828+
description: Added the `callback` argument.
18251829
-->
18261830

18271831
* `headers` {HTTP/2 Headers Object}
1832+
* `callback` {Function} Optional, called once the `HEADERS` frame has been
1833+
written to the socket, or with an error if it could not be written.
1834+
* `err` {Error|null}
18281835

18291836
Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer.
18301837

@@ -5057,23 +5064,40 @@ Returns `true` if the entire data was flushed successfully to the kernel
50575064
buffer. Returns `false` if all or part of the data was queued in user memory.
50585065
`'drain'` will be emitted when the buffer is free again.
50595066

5060-
#### `response.writeContinue()`
5067+
#### `response.writeContinue([callback])`
50615068

50625069
<!-- YAML
50635070
added: v8.4.0
5071+
changes:
5072+
- version: REPLACEME
5073+
pr-url: https://github.com/nodejs/node/pull/67470
5074+
description: Added the `callback` argument.
50645075
-->
50655076

5077+
* `callback` {Function} Optional, called once the informational headers
5078+
have been written to the socket, or with an error if they could not be
5079+
written. It is not called if nothing is sent.
5080+
* `err` {Error|null}
5081+
50665082
Sends a status `100 Continue` to the client, indicating that the request body
50675083
should be sent. See the [`'checkContinue'`][] event on `Http2Server` and
50685084
`Http2SecureServer`.
50695085

5070-
#### `response.writeEarlyHints(hints)`
5086+
#### `response.writeEarlyHints(hints[, callback])`
50715087

50725088
<!-- YAML
50735089
added: v18.11.0
5090+
changes:
5091+
- version: REPLACEME
5092+
pr-url: https://github.com/nodejs/node/pull/67470
5093+
description: Added the `callback` argument.
50745094
-->
50755095

50765096
* `hints` {Object}
5097+
* `callback` {Function} Optional, called once the informational headers
5098+
have been written to the socket, or with an error if they could not be
5099+
written. It is not called if nothing is sent.
5100+
* `err` {Error|null}
50775101

50785102
Sends a status `103 Early Hints` to the client with a Link header,
50795103
indicating that the user agent can preload/preconnect the linked resources.
@@ -5097,19 +5121,27 @@ response.writeEarlyHints({
50975121
});
50985122
```
50995123

5100-
#### `response.writeInformation(statusCode[, headers])`
5124+
#### `response.writeInformation(statusCode[, headers[, callback]])`
51015125

51025126
<!-- YAML
51035127
added:
51045128
- v26.2.0
51055129
- v24.18.0
5130+
changes:
5131+
- version: REPLACEME
5132+
pr-url: https://github.com/nodejs/node/pull/67470
5133+
description: Added the `callback` argument.
51065134
-->
51075135

51085136
* `statusCode` {number} An HTTP 1xx informational status code, between `100`
51095137
and `199` inclusive, excluding `101` (Switching Protocols) which is not
51105138
allowed in HTTP/2.
51115139
* `headers` {Object} An optional object of headers to send with the
51125140
informational response.
5141+
* `callback` {Function} Optional, called once the informational headers
5142+
have been written to the socket, or with an error if they could not be
5143+
written. It is not called if nothing is sent.
5144+
* `err` {Error|null}
51135145

51145146
Sends an arbitrary HTTP 1xx informational response, equivalent in HTTP/2 to a
51155147
`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.
53345366
[`response.writableEnded`]: #responsewritableended
53355367
[`response.write()`]: #responsewritechunk-encoding-callback
53365368
[`response.write(data, encoding)`]: http.md#responsewritechunk-encoding-callback
5337-
[`response.writeContinue()`]: #responsewritecontinue
5338-
[`response.writeEarlyHints()`]: #responsewriteearlyhintshints
5369+
[`response.writeContinue()`]: #responsewritecontinuecallback
5370+
[`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback
53395371
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
53405372
[`server.close()`]: #serverclosecallback
53415373
[`server.maxHeadersCount`]: http.md#servermaxheaderscount

‎lib/internal/http2/compat.js‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -957,14 +957,16 @@ class Http2ServerResponse extends Stream {
957957
this[kStream].respond(headers, options);
958958
}
959959

960-
writeInformation(statusCode, headers) {
960+
writeInformation(statusCode, headers, cb) {
961961
if (typeof statusCode !== 'number' ||
962962
statusCode < 100 || statusCode > 199) {
963963
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
964964
}
965965
if (statusCode === 101) {
966966
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
967967
}
968+
if (cb !== undefined)
969+
validateFunction(cb, 'callback');
968970

969971
const stream = this[kStream];
970972

@@ -981,16 +983,15 @@ class Http2ServerResponse extends Stream {
981983
}
982984
outHeaders[HTTP2_HEADER_STATUS] = statusCode;
983985

984-
stream.additionalHeaders(outHeaders);
986+
stream.additionalHeaders(outHeaders, cb);
985987
return true;
986988
}
987989

988-
// TODO doesn't support callbacks
989-
writeContinue() {
990-
return this.writeInformation(HTTP_STATUS_CONTINUE);
990+
writeContinue(cb) {
991+
return this.writeInformation(HTTP_STATUS_CONTINUE, undefined, cb);
991992
}
992993

993-
writeEarlyHints(hints) {
994+
writeEarlyHints(hints, cb) {
994995
validateObject(hints, 'hints');
995996

996997
const headers = { __proto__: null };
@@ -1013,7 +1014,7 @@ class Http2ServerResponse extends Stream {
10131014

10141015
headers.Link = linkHeaderValue;
10151016

1016-
return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers);
1017+
return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers, cb);
10171018
}
10181019
}
10191020

‎lib/internal/http2/core.js‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ const { AsyncResource } = require('async_hooks');
6767

6868
const {
6969
AbortError,
70+
ErrnoException,
7071
aggregateTwoErrors,
7172
codes: {
7273
ERR_HTTP2_ALTSVC_INVALID_ORIGIN,
@@ -188,6 +189,7 @@ const { FileHandle } = internalBinding('fs');
188189
const binding = internalBinding('http2');
189190
const {
190191
ShutdownWrap,
192+
WriteWrap,
191193
kReadBytesOrError,
192194
streamBaseState,
193195
} = internalBinding('stream_wrap');
@@ -3460,14 +3462,17 @@ class ServerHttp2Stream extends Http2Stream {
34603462
// such that HEADERS may only be sent *before* or *after* DATA frames.
34613463
// If the block of headers being sent includes a status code, it MUST be
34623464
// a 1xx informational code and it MUST be sent before the request/response
3463-
// headers are sent, or an error will be thrown.
3464-
additionalHeaders(headers) {
3465+
// headers are sent, or an error will be thrown. The optional callback is
3466+
// called once the HEADERS frame has been written to the socket.
3467+
additionalHeaders(headers, callback) {
34653468
if (this.destroyed || this.closed)
34663469
throw new ERR_HTTP2_INVALID_STREAM();
34673470
if (this.headersSent)
34683471
throw new ERR_HTTP2_HEADERS_AFTER_RESPOND();
34693472

34703473
assertIsObject(headers, 'headers');
3474+
if (callback !== undefined)
3475+
validateFunction(callback, 'callback');
34713476
headers = ObjectAssign({ __proto__: null }, headers);
34723477

34733478
debugStreamObj(this, 'sending additional headers');
@@ -3493,12 +3498,32 @@ class ServerHttp2Stream extends Http2Stream {
34933498
else
34943499
this[kInfoHeaders].push(headers);
34953500

3496-
const ret = this[kHandle].info(headersList);
3497-
if (ret < 0)
3498-
this.destroy(new NghttpError(ret));
3501+
let req;
3502+
if (callback !== undefined) {
3503+
req = new WriteWrap();
3504+
req.oncomplete = onInfoHeadersComplete;
3505+
req.callback = callback;
3506+
}
3507+
3508+
const ret = this[kHandle].info(headersList, req);
3509+
if (ret < 0) {
3510+
const err = new NghttpError(ret);
3511+
this.destroy(err);
3512+
if (callback !== undefined)
3513+
process.nextTick(callback, err);
3514+
}
34993515
}
35003516
}
35013517

3518+
// Called once an informational HEADERS frame has been written to the socket,
3519+
// or once it is known that it will not be.
3520+
function onInfoHeadersComplete(status) {
3521+
if (status < 0)
3522+
this.callback(new ErrnoException(status, 'write', this.error));
3523+
else
3524+
this.callback(null);
3525+
}
3526+
35023527
ServerHttp2Stream.prototype[kProceed] = ServerHttp2Stream.prototype.respond;
35033528

35043529
class ClientHttp2Stream extends Http2Stream {

‎src/node_http2.cc‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1320,6 +1320,9 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle,
13201320
Debug(session, "frame type %d was not sent, code: %d",
13211321
frame->hd.type, error_code);
13221322

1323+
if (frame->hd.type == NGHTTP2_HEADERS)
1324+
session->HandleInfoHeadersFrame(frame, UV_ECANCELED);
1325+
13231326
if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
13241327
error_code == NGHTTP2_ERR_STREAM_CLOSED ||
13251328
error_code == NGHTTP2_ERR_STREAM_CLOSING) {
@@ -1361,6 +1364,9 @@ int Http2Session::OnFrameSent(nghttp2_session* handle,
13611364
Http2Session* session = static_cast<Http2Session*>(user_data);
13621365
session->statistics_.frame_sent += 1;
13631366

1367+
if (frame->hd.type == NGHTTP2_HEADERS)
1368+
session->HandleInfoHeadersFrame(frame, 0);
1369+
13641370
// If nghttp2 has internally terminated the session (e.g. due to a protocol
13651371
// error like oversized frames, padding errors, or HPACK compression
13661372
// failures), it calls nghttp2_session_terminate_session() directly which
@@ -2005,6 +2011,12 @@ void Http2Session::ClearOutgoing(int status) {
20052011

20062012
set_sending(false);
20072013

2014+
// Completing a request can start the next write. Take the requests that
2015+
// belong to the write that has just finished before completing any of them,
2016+
// so that the ones of the next write are left alone.
2017+
std::vector<OutgoingInfoReq> info_reqs;
2018+
info_reqs.swap(outgoing_info_reqs_);
2019+
20082020
if (!outgoing_buffers_.empty()) {
20092021
outgoing_storage_.clear();
20102022
outgoing_length_ = 0;
@@ -2022,6 +2034,11 @@ void Http2Session::ClearOutgoing(int status) {
20222034
}
20232035
}
20242036

2037+
for (const OutgoingInfoReq& req : info_reqs) {
2038+
WriteWrap::FromObject(req.req_wrap)
2039+
->Done(req.status != 0 ? req.status : status);
2040+
}
2041+
20252042
// Now that we've finished sending queued data, if there are any pending
20262043
// RstStreams we should try sending again and then flush them one by one.
20272044
if (status == 0 && !pending_rst_streams_.empty()) {
@@ -2039,6 +2056,24 @@ void Http2Session::ClearOutgoing(int status) {
20392056
}
20402057
}
20412058

2059+
// Called when nghttp2 has serialized a HEADERS frame, or has given up on
2060+
// sending it. Informational HEADERS frames are always sent before any other
2061+
// HEADERS frame of the same stream, and in the order they were submitted in,
2062+
// so if the stream still has informational headers pending, this frame is the
2063+
// oldest of them. Its request is completed in ClearOutgoing(), once the
2064+
// current write to the underlying stream has finished.
2065+
void Http2Session::HandleInfoHeadersFrame(const nghttp2_frame* frame,
2066+
int status) {
2067+
BaseObjectPtr<Http2Stream> stream = FindStream(frame->hd.stream_id);
2068+
if (!stream || stream->info_reqs_.empty()) return;
2069+
BaseObjectPtr<AsyncWrap> req_wrap = std::move(stream->info_reqs_.front());
2070+
stream->info_reqs_.pop();
2071+
if (req_wrap) {
2072+
outgoing_info_reqs_.push_back(
2073+
{std::move(req_wrap), std::move(stream), status});
2074+
}
2075+
}
2076+
20422077
void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) {
20432078
outgoing_length_ += write.buf.len;
20442079
outgoing_buffers_.emplace_back(std::move(write));
@@ -2314,6 +2349,9 @@ bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) {
23142349
for (const NgHttp2StreamWrite& wr : outgoing_buffers_) {
23152350
if (wr.stream.get() == stream) return true;
23162351
}
2352+
for (const OutgoingInfoReq& req : outgoing_info_reqs_) {
2353+
if (req.stream.get() == stream) return true;
2354+
}
23172355
return false;
23182356
}
23192357

@@ -2418,6 +2456,7 @@ Http2Stream::~Http2Stream() {
24182456
void Http2Stream::MemoryInfo(MemoryTracker* tracker) const {
24192457
tracker->TrackField("current_headers", current_headers_);
24202458
tracker->TrackField("queue", queue_);
2459+
tracker->TrackField("info_reqs", info_reqs_);
24212460
}
24222461

24232462
std::string Http2Stream::diagnostic_name() const {
@@ -2542,6 +2581,7 @@ void Http2Stream::CompleteDestroyCleanup() {
25422581
WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED);
25432582
queue_.pop();
25442583
}
2584+
CancelPendingInfoRequests();
25452585

25462586
// We can destroy the stream now if there are no writes for it
25472587
// already on the socket. Otherwise, we'll wait for the garbage collector
@@ -2588,7 +2628,15 @@ int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) {
25882628

25892629

25902630
// Submit informational headers for a stream.
2591-
int Http2Stream::SubmitInfo(const Http2Headers& headers) {
2631+
void Http2Stream::CancelPendingInfoRequests() {
2632+
while (!info_reqs_.empty()) {
2633+
BaseObjectPtr<AsyncWrap> req_wrap = std::move(info_reqs_.front());
2634+
info_reqs_.pop();
2635+
if (req_wrap) WriteWrap::FromObject(req_wrap)->Done(UV_ECANCELED);
2636+
}
2637+
}
2638+
2639+
int Http2Stream::SubmitInfo(const Http2Headers& headers, WriteWrap* req_wrap) {
25922640
CHECK(!this->is_destroyed());
25932641
Http2Scope h2scope(this);
25942642
Debug(this, "sending %d informational headers", headers.length());
@@ -2601,6 +2649,12 @@ int Http2Stream::SubmitInfo(const Http2Headers& headers) {
26012649
headers.length(),
26022650
nullptr);
26032651
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
2652+
if (ret == 0) {
2653+
info_reqs_.emplace(req_wrap != nullptr ? req_wrap->GetAsyncWrap()
2654+
: nullptr);
2655+
} else if (req_wrap != nullptr) {
2656+
req_wrap->Dispose();
2657+
}
26042658
return ret;
26052659
}
26062660

@@ -3296,7 +3350,16 @@ void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
32963350

32973351
Local<Array> headers = args[0].As<Array>();
32983352

3299-
args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers)));
3353+
// The optional request object is completed once the HEADERS frame has been
3354+
// written to the socket.
3355+
WriteWrap* req_wrap = nullptr;
3356+
if (args[1]->IsObject()) {
3357+
AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(stream);
3358+
req_wrap = stream->CreateWriteWrap(args[1].As<Object>());
3359+
}
3360+
3361+
args.GetReturnValue().Set(
3362+
stream->SubmitInfo(Http2Headers(env, headers), req_wrap));
33003363
}
33013364

33023365
// Submits trailing headers on the Http2Stream

0 commit comments

Comments
 (0)