Skip to content

Commit 9313db8

Browse files
pimterryjuanarbol
authored andcommitted
http: add writeInformation to send arbitrary 1xx status codes
Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #63155 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
1 parent 5346cc9 commit 9313db8

7 files changed

Lines changed: 306 additions & 34 deletions

File tree

‎doc/api/http.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2675,6 +2675,35 @@ been transmitted are equal or not.
26752675
Attempting to set a header field name or value that contains invalid characters
26762676
will result in a [`TypeError`][] being thrown.
26772677

2678+
### `response.writeInformation(statusCode[, headers][, callback])`
2679+
2680+
<!-- YAML
2681+
added: REPLACEME
2682+
-->
2683+
2684+
*`statusCode` {number} An HTTP 1xx informational status code, between `100`
2685+
and `199` inclusive, excluding `101` (Switching Protocols) which is only
2686+
available through the [`'upgrade'`][] event.
2687+
*`headers` {Object|Array} An optional set of headers to send with the
2688+
informational response. Accepts the same shapes as
2689+
[`response.writeHead()`][].
2690+
*`callback` {Function} Optional, called once the message has been written
2691+
to the socket.
2692+
2693+
Sends an arbitrary HTTP/1.1 1xx informational response to the client. This
2694+
is a generic equivalent of [`response.writeContinue()`][],
2695+
[`response.writeProcessing()`][] and [`response.writeEarlyHints()`][], and
2696+
can be called multiple times before the final response. After the final
2697+
response headers have been sent (via [`response.writeHead()`][] or an
2698+
implicit header), calling this method throws `ERR_HTTP_HEADERS_SENT`.
2699+
2700+
Clients receive these responses via the [`'information'`][information event]
2701+
event on `http.ClientRequest`.
2702+
2703+
```js
2704+
response.writeInformation(110, { 'X-Progress':'50%' });
2705+
```
2706+
26782707
### `response.writeProcessing()`
26792708

26802709
<!-- YAML
@@ -4548,7 +4577,9 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
45484577
[`response.write()`]: #responsewritechunk-encoding-callback
45494578
[`response.write(data, encoding)`]: #responsewritechunk-encoding-callback
45504579
[`response.writeContinue()`]: #responsewritecontinue
4580+
[`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback
45514581
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
4582+
[`response.writeProcessing()`]: #responsewriteprocessing
45524583
[`server.close()`]: #serverclosecallback
45534584
[`server.headersTimeout`]: #serverheaderstimeout
45544585
[`server.keepAliveTimeoutBuffer`]: #serverkeepalivetimeoutbuffer
@@ -4569,4 +4600,5 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
45694600
[`writable.destroyed`]:stream.md#writabledestroyed
45704601
[`writable.uncork()`]:stream.md#writableuncork
45714602
[`writable.write()`]:stream.md#writablewritechunk-encoding-callback
4603+
[information event]: #event-information
45724604
[initial delay]:net.md#socketsetkeepaliveenable-initialdelay

‎doc/api/http2.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4769,6 +4769,30 @@ response.writeEarlyHints({
47694769
});
47704770
```
47714771

4772+
#### `response.writeInformation(statusCode[, headers])`
4773+
4774+
<!-- YAML
4775+
added: REPLACEME
4776+
-->
4777+
4778+
*`statusCode` {number} An HTTP 1xx informational status code, between `100`
4779+
and `199` inclusive, excluding `101` (Switching Protocols) which is not
4780+
allowed in HTTP/2.
4781+
*`headers` {Object} An optional object of headers to send with the
4782+
informational response.
4783+
4784+
Sends an arbitrary HTTP 1xx informational response, equivalent in HTTP/2 to a
4785+
`HEADERS` frame whose `:status` pseudo-header is a 1xx code. May be called
4786+
multiple times before the final response. After the final response headers
4787+
have been sent, this method is a no-op and returns `false`.
4788+
4789+
This is the generic equivalent of [`response.writeContinue()`][] and
4790+
[`response.writeEarlyHints()`][].
4791+
4792+
```js
4793+
response.writeInformation(110, { 'X-Progress':'50%' });
4794+
```
4795+
47724796
#### `response.writeHead(statusCode[, statusMessage][, headers])`
47734797

47744798
<!-- YAML
@@ -4976,6 +5000,7 @@ you need to implement any fall-back behavior yourself.
49765000
[`response.write()`]: #responsewritechunk-encoding-callback
49775001
[`response.write(data, encoding)`]: http.md#responsewritechunk-encoding-callback
49785002
[`response.writeContinue()`]: #responsewritecontinue
5003+
[`response.writeEarlyHints()`]: #responsewriteearlyhintshints
49795004
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
49805005
[`server.close()`]: #serverclosecallback
49815006
[`server.maxHeadersCount`]: http.md#servermaxheaderscount

‎lib/_http_server.js‎

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -306,18 +306,66 @@ ServerResponse.prototype.detachSocket = function detachSocket(socket) {
306306
this.socket=null;
307307
};
308308

309+
ServerResponse.prototype.writeInformation=functionwriteInformation(
310+
statusCode,headers,cb){
311+
if(this._header){
312+
thrownewERR_HTTP_HEADERS_SENT('write');
313+
}
314+
315+
validateInteger(statusCode,'statusCode',100,199);
316+
if(statusCode===101){
317+
thrownewERR_HTTP_INVALID_STATUS_CODE(statusCode);
318+
}
319+
320+
conststatusMessage=STATUS_CODES[statusCode]||'unknown';
321+
lethead=`HTTP/1.1 ${statusCode}${statusMessage}\r\n`;
322+
323+
if(headers!==undefined&&headers!==null){
324+
if(ArrayIsArray(headers)){
325+
if(headers.length&&ArrayIsArray(headers[0])){
326+
for(leti=0;i<headers.length;i++){
327+
constentry=headers[i];
328+
head+=processInformationHeader(entry[0],entry[1]);
329+
}
330+
}else{
331+
if(headers.length%2!==0){
332+
thrownewERR_INVALID_ARG_VALUE('headers',headers);
333+
}
334+
for(leti=0;i<headers.length;i+=2){
335+
head+=processInformationHeader(headers[i],headers[i+1]);
336+
}
337+
}
338+
}else{
339+
validateObject(headers,'headers');
340+
constkeys=ObjectKeys(headers);
341+
for(leti=0;i<keys.length;i++){
342+
constkey=keys[i];
343+
head+=processInformationHeader(key,headers[key]);
344+
}
345+
}
346+
}
347+
348+
head+='\r\n';
349+
350+
returnthis._writeRaw(head,'ascii',cb);
351+
};
352+
353+
functionprocessInformationHeader(name,value){
354+
validateHeaderName(name);
355+
validateHeaderValue(name,value);
356+
return`${name}: ${value}\r\n`;
357+
}
358+
309359
ServerResponse.prototype.writeContinue=functionwriteContinue(cb){
310-
this._writeRaw('HTTP/1.1 100 Continue\r\n\r\n','ascii',cb);
360+
this.writeInformation(100,null,cb);
311361
this._sent100=true;
312362
};
313363

314364
ServerResponse.prototype.writeProcessing=functionwriteProcessing(cb){
315-
this._writeRaw('HTTP/1.1 102 Processing\r\n\r\n','ascii',cb);
365+
this.writeInformation(102,null,cb);
316366
};
317367

318368
ServerResponse.prototype.writeEarlyHints=functionwriteEarlyHints(hints,cb){
319-
lethead='HTTP/1.1 103 Early Hints\r\n';
320-
321369
validateObject(hints,'hints');
322370

323371
if(hints.link===null||hints.link===undefined){
@@ -334,22 +382,16 @@ ServerResponse.prototype.writeEarlyHints = function writeEarlyHints(hints, cb) {
334382
thrownewERR_INVALID_CHAR('header content','Link');
335383
}
336384

337-
head+='Link: '+link+'\r\n';
338-
385+
constheaders={__proto__: null,Link: link};
339386
constkeys=ObjectKeys(hints);
340387
for(leti=0;i<keys.length;i++){
341388
constkey=keys[i];
342389
if(key!=='link'){
343-
validateHeaderName(key);
344-
constvalue=hints[key];
345-
validateHeaderValue(key,value);
346-
head+=key+': '+value+'\r\n';
390+
headers[key]=hints[key];
347391
}
348392
}
349393

350-
head+='\r\n';
351-
352-
this._writeRaw(head,'ascii',cb);
394+
this.writeInformation(103,headers,cb);
353395
};
354396

355397
ServerResponse.prototype._implicitHeader=function_implicitHeader(){

‎lib/internal/http2/compat.js‎

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -902,17 +902,39 @@ class Http2ServerResponse extends Stream {
902902
this[kStream].respond(headers,options);
903903
}
904904

905-
// TODO doesn't support callbacks
906-
writeContinue(){
905+
writeInformation(statusCode,headers){
906+
if(typeofstatusCode!=='number'||
907+
statusCode<100||statusCode>199){
908+
thrownewERR_HTTP2_STATUS_INVALID(statusCode);
909+
}
910+
if(statusCode===101){
911+
thrownewERR_HTTP2_STATUS_INVALID(statusCode);
912+
}
913+
907914
conststream=this[kStream];
915+
908916
if(stream.headersSent||this[kState].closed)
909917
returnfalse;
910-
stream.additionalHeaders({
911-
[HTTP2_HEADER_STATUS]: HTTP_STATUS_CONTINUE,
912-
});
918+
919+
constoutHeaders={__proto__: null};
920+
if(headers!==undefined&&headers!==null){
921+
validateObject(headers,'headers');
922+
constkeys=ObjectKeys(headers);
923+
for(leti=0;i<keys.length;i++){
924+
outHeaders[keys[i]]=headers[keys[i]];
925+
}
926+
}
927+
outHeaders[HTTP2_HEADER_STATUS]=statusCode;
928+
929+
stream.additionalHeaders(outHeaders);
913930
returntrue;
914931
}
915932

933+
// TODO doesn't support callbacks
934+
writeContinue(){
935+
returnthis.writeInformation(HTTP_STATUS_CONTINUE);
936+
}
937+
916938
writeEarlyHints(hints){
917939
validateObject(hints,'hints');
918940

@@ -934,18 +956,9 @@ class Http2ServerResponse extends Stream {
934956
returnfalse;
935957
}
936958

937-
conststream=this[kStream];
959+
headers.Link=linkHeaderValue;
938960

939-
if(stream.headersSent||this[kState].closed)
940-
returnfalse;
941-
942-
stream.additionalHeaders({
943-
...headers,
944-
[HTTP2_HEADER_STATUS]: HTTP_STATUS_EARLY_HINTS,
945-
'Link': linkHeaderValue,
946-
});
947-
948-
returntrue;
961+
returnthis.writeInformation(HTTP_STATUS_EARLY_HINTS,headers);
949962
}
950963
}
951964

‎test/parallel/test-http-information-headers.js‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,7 @@ const countdown = new Countdown(2, () => server.close());
99

1010
constserver=http.createServer((req,res)=>{
1111
console.error('Server sending informational message #1...');
12-
// These function calls may rewritten as necessary
13-
// to call res.writeHead instead
14-
res._writeRaw('HTTP/1.1 102 Processing\r\n');
15-
res._writeRaw('Foo: Bar\r\n');
16-
res._writeRaw('\r\n',common.mustCall());
12+
res.writeInformation(102,{Foo: 'Bar'},common.mustCall());
1713
console.error('Server sending full response...');
1814
res.writeHead(200,{
1915
'Content-Type': 'text/plain',
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
constassert=require('node:assert');
4+
consthttp=require('node:http');
5+
6+
// Happy flow: arbitrary 1xx status with custom headers, observed by the
7+
// client's 'information' event.
8+
{
9+
constserver=http.createServer(common.mustCall((req,res)=>{
10+
res.writeInformation(110,{'X-Progress': '50%','X-Stage': 'reading'});
11+
res.writeInformation(199,[['X-Custom','one'],['X-Custom-2','two']]);
12+
res.end('done');
13+
}));
14+
15+
server.listen(0,common.mustCall(()=>{
16+
constreq=http.request({port: server.address().port});
17+
18+
constseen=[];
19+
req.on('information',(res)=>{
20+
seen.push({
21+
statusCode: res.statusCode,
22+
headers: res.headers,
23+
});
24+
});
25+
26+
req.on('response',common.mustCall((res)=>{
27+
assert.strictEqual(res.statusCode,200);
28+
29+
assert.strictEqual(seen.length,2);
30+
assert.strictEqual(seen[0].statusCode,110);
31+
assert.strictEqual(seen[0].headers['x-progress'],'50%');
32+
assert.strictEqual(seen[0].headers['x-stage'],'reading');
33+
assert.strictEqual(seen[1].statusCode,199);
34+
assert.strictEqual(seen[1].headers['x-custom'],'one');
35+
assert.strictEqual(seen[1].headers['x-custom-2'],'two');
36+
37+
res.resume();
38+
res.on('end',common.mustCall(()=>server.close()));
39+
}));
40+
41+
req.end();
42+
}));
43+
}
44+
45+
// Headers argument is optional / nullable.
46+
{
47+
constserver=http.createServer(common.mustCall((req,res)=>{
48+
res.writeInformation(150);
49+
res.writeInformation(151,null);
50+
res.end();
51+
}));
52+
53+
server.listen(0,common.mustCall(()=>{
54+
constreq=http.request({port: server.address().port});
55+
letcount=0;
56+
req.on('information',()=>count++);
57+
req.on('response',common.mustCall((res)=>{
58+
assert.strictEqual(count,2);
59+
res.resume();
60+
res.on('end',common.mustCall(()=>server.close()));
61+
}));
62+
req.end();
63+
}));
64+
}
65+
66+
// Error cases.
67+
{
68+
constserver=http.createServer(common.mustCall((req,res)=>{
69+
assert.throws(()=>res.writeInformation(101),
70+
{code: 'ERR_HTTP_INVALID_STATUS_CODE'});
71+
assert.throws(()=>res.writeInformation(99),
72+
{code: 'ERR_OUT_OF_RANGE'});
73+
assert.throws(()=>res.writeInformation(200),
74+
{code: 'ERR_OUT_OF_RANGE'});
75+
assert.throws(()=>res.writeInformation('100'),
76+
{code: 'ERR_INVALID_ARG_TYPE'});
77+
assert.throws(()=>res.writeInformation(150,{'X-Bad\n': 'v'}),
78+
{code: 'ERR_INVALID_HTTP_TOKEN'});
79+
80+
res.writeHead(200);
81+
assert.throws(()=>res.writeInformation(150),
82+
{code: 'ERR_HTTP_HEADERS_SENT'});
83+
res.end();
84+
}));
85+
86+
server.listen(0,common.mustCall(()=>{
87+
constreq=http.request({port: server.address().port});
88+
req.on('response',common.mustCall((res)=>{
89+
res.resume();
90+
res.on('end',common.mustCall(()=>server.close()));
91+
}));
92+
req.end();
93+
}));
94+
}

0 commit comments

Comments
 (0)