GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — http2: add callback to informational header methods · nodejs/node@0a67a05

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • doc/api
    • http2.md
  • lib/internal/http2
    • compat.js
    • core.js
  • src
    • node_http2.cc
    • node_http2.h
  • test/parallel
    • test-http2-compat-write-information-callback.js
    • test-http2-info-headers-callback-reentrant.js
    • test-http2-info-headers-callback.js
    • test-http2-info-headers-errors.js
    • test-http2-info-headers-reset-pending-write.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎doc/api/http2.md‎

Copy file name to clipboardExpand all lines: doc/api/http2.md
+38-6Lines changed: 38 additions & 6 deletions
  • Display the source diff
  • Display the rich diff
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
Collapse file

‎lib/internal/http2/compat.js‎

Copy file name to clipboardExpand all lines: lib/internal/http2/compat.js
+8-7Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -970,14 +970,16 @@ class Http2ServerResponse extends Stream {
970970
this[kStream].respond(headers, options);
971971
}
972972

973-
writeInformation(statusCode, headers) {
973+
writeInformation(statusCode, headers, cb) {
974974
if (typeof statusCode !== 'number' ||
975975
statusCode < 100 || statusCode > 199) {
976976
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
977977
}
978978
if (statusCode === 101) {
979979
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
980980
}
981+
if (cb !== undefined)
982+
validateFunction(cb, 'callback');
981983

982984
const stream = this[kStream];
983985

@@ -994,16 +996,15 @@ class Http2ServerResponse extends Stream {
994996
}
995997
outHeaders[HTTP2_HEADER_STATUS] = statusCode;
996998

997-
stream.additionalHeaders(outHeaders);
999+
stream.additionalHeaders(outHeaders, cb);
9981000
return true;
9991001
}
10001002

1001-
// TODO doesn't support callbacks
1002-
writeContinue() {
1003-
return this.writeInformation(HTTP_STATUS_CONTINUE);
1003+
writeContinue(cb) {
1004+
return this.writeInformation(HTTP_STATUS_CONTINUE, undefined, cb);
10041005
}
10051006

1006-
writeEarlyHints(hints) {
1007+
writeEarlyHints(hints, cb) {
10071008
validateObject(hints, 'hints');
10081009

10091010
const headers = { __proto__: null };
@@ -1026,7 +1027,7 @@ class Http2ServerResponse extends Stream {
10261027

10271028
headers.Link = linkHeaderValue;
10281029

1029-
return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers);
1030+
return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers, cb);
10301031
}
10311032
}
10321033

Collapse file

‎lib/internal/http2/core.js‎

Copy file name to clipboardExpand all lines: lib/internal/http2/core.js
+30-5Lines 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,
@@ -190,6 +191,7 @@ const { FileHandle } = internalBinding('fs');
190191
const binding = internalBinding('http2');
191192
const {
192193
ShutdownWrap,
194+
WriteWrap,
193195
kReadBytesOrError,
194196
streamBaseState,
195197
} = internalBinding('stream_wrap');
@@ -3501,14 +3503,17 @@ class ServerHttp2Stream extends Http2Stream {
35013503
// such that HEADERS may only be sent *before* or *after* DATA frames.
35023504
// If the block of headers being sent includes a status code, it MUST be
35033505
// a 1xx informational code and it MUST be sent before the request/response
3504-
// headers are sent, or an error will be thrown.
3505-
additionalHeaders(headers) {
3506+
// headers are sent, or an error will be thrown. The optional callback is
3507+
// called once the HEADERS frame has been written to the socket.
3508+
additionalHeaders(headers, callback) {
35063509
if (this.destroyed || this.closed)
35073510
throw new ERR_HTTP2_INVALID_STREAM();
35083511
if (this.headersSent)
35093512
throw new ERR_HTTP2_HEADERS_AFTER_RESPOND();
35103513

35113514
assertIsObject(headers, 'headers');
3515+
if (callback !== undefined)
3516+
validateFunction(callback, 'callback');
35123517
headers = ObjectAssign({ __proto__: null }, headers);
35133518

35143519
debugStreamObj(this, 'sending additional headers');
@@ -3534,12 +3539,32 @@ class ServerHttp2Stream extends Http2Stream {
35343539
else
35353540
this[kInfoHeaders].push(headers);
35363541

3537-
const ret = this[kHandle].info(headersList);
3538-
if (ret < 0)
3539-
this.destroy(new NghttpError(ret));
3542+
let req;
3543+
if (callback !== undefined) {
3544+
req = new WriteWrap();
3545+
req.oncomplete = onInfoHeadersComplete;
3546+
req.callback = callback;
3547+
}
3548+
3549+
const ret = this[kHandle].info(headersList, req);
3550+
if (ret < 0) {
3551+
const err = new NghttpError(ret);
3552+
this.destroy(err);
3553+
if (callback !== undefined)
3554+
process.nextTick(callback, err);
3555+
}
35403556
}
35413557
}
35423558

3559+
// Called once an informational HEADERS frame has been written to the socket,
3560+
// or once it is known that it will not be.
3561+
function onInfoHeadersComplete(status) {
3562+
if (status < 0)
3563+
this.callback(new ErrnoException(status, 'write', this.error));
3564+
else
3565+
this.callback(null);
3566+
}
3567+
35433568
ServerHttp2Stream.prototype[kProceed] = ServerHttp2Stream.prototype.respond;
35443569

35453570
class ClientHttp2Stream extends Http2Stream {
Collapse file

‎src/node_http2.cc‎

Copy file name to clipboardExpand all lines: src/node_http2.cc
+65-2Lines 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

@@ -3309,7 +3363,16 @@ void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) {
33093363

33103364
Local<Array> headers = args[0].As<Array>();
33113365

3312-
args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers)));
3366+
// The optional request object is completed once the HEADERS frame has been
3367+
// written to the socket.
3368+
WriteWrap* req_wrap = nullptr;
3369+
if (args[1]->IsObject()) {
3370+
AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(stream);
3371+
req_wrap = stream->CreateWriteWrap(args[1].As<Object>());
3372+
}
3373+
3374+
args.GetReturnValue().Set(
3375+
stream->SubmitInfo(Http2Headers(env, headers), req_wrap));
33133376
}
33143377

33153378
// Submits trailing headers on the Http2Stream

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.