Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 38 additions & 6 deletions doc/api/http2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand All @@ -5097,19 +5121,27 @@ 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`
and `199` inclusive, excluding `101` (Switching Protocols) which is not
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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 8 additions & 7 deletions lib/internal/http2/compat.js
Original file line number Diff line number Diff line change
Expand Up @@ -957,14 +957,16 @@ 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);
}
if (statusCode === 101) {
throw new ERR_HTTP2_STATUS_INVALID(statusCode);
}
if (cb !== undefined)
validateFunction(cb, 'callback');

const stream = this[kStream];

Expand All @@ -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 };
Expand All @@ -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);
}
}

Expand Down
35 changes: 30 additions & 5 deletions lib/internal/http2/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const { AsyncResource } = require('async_hooks');

const {
AbortError,
ErrnoException,
aggregateTwoErrors,
codes: {
ERR_HTTP2_ALTSVC_INVALID_ORIGIN,
Expand Down Expand Up @@ -188,6 +189,7 @@ const { FileHandle } = internalBinding('fs');
const binding = internalBinding('http2');
const {
ShutdownWrap,
WriteWrap,
kReadBytesOrError,
streamBaseState,
} = internalBinding('stream_wrap');
Expand Down Expand Up @@ -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');
Expand All @@ -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 {
Expand Down
67 changes: 65 additions & 2 deletions src/node_http2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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()) {
Expand All @@ -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));
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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());
Expand All @@ -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;
}

Expand Down Expand Up @@ -3296,7 +3350,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
Expand Down
Loading
Loading