Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 0ad55e5

Browse files
pimterryaduh95
authored andcommitted
http: fix writableFinished and 'finish' after write errors
Only emit 'finish' and set writableFinished once all data has actually been flushed successfully. end() callbacks now report the outcome like stream.Writable: called with null on finish, or with the error that prevented the flush. Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #64847 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 2cfa96f commit 0ad55e5

4 files changed

Lines changed: 183 additions & 40 deletions

File tree

‎lib/_http_outgoing.js‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ const kChunkedLength = Symbol('kChunkedLength');
8585
constkUniqueHeaders=Symbol('kUniqueHeaders');
8686
constkBytesWritten=Symbol('kBytesWritten');
8787
constkErrored=Symbol('errored');
88+
constkWritableFinished=Symbol('kWritableFinished');
89+
constkEndCallbacks=Symbol('kEndCallbacks');
90+
constkFlushError=Symbol('kFlushError');
8891
constkHighWaterMark=Symbol('kHighWaterMark');
8992
constkRejectNonStandardBodyWrites=Symbol('kRejectNonStandardBodyWrites');
9093

@@ -153,6 +156,9 @@ function OutgoingMessage(options) {
153156
this._onPendingData=nop;
154157

155158
this[kErrored]=null;
159+
this[kWritableFinished]=false;
160+
this[kEndCallbacks]=null;
161+
this[kFlushError]=null;
156162
this[kHighWaterMark]=options?.highWaterMark??getDefaultHighWaterMark();
157163
this[kRejectNonStandardBodyWrites]=options?.rejectNonStandardBodyWrites??false;
158164
}
@@ -203,11 +209,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'closed', {
203209
ObjectDefineProperty(OutgoingMessage.prototype,'writableFinished',{
204210
__proto__: null,
205211
get(){
206-
return(
207-
this.finished&&
208-
this.outputSize===0&&
209-
(!this[kSocket]||this[kSocket].writableLength===0)
210-
);
212+
returnthis[kWritableFinished];
211213
},
212214
});
213215

@@ -1074,8 +1076,48 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10741076
}
10751077
};
10761078

1077-
functiononFinish(outmsg){
1078-
if(outmsg?.socket?._hadError)return;
1079+
// Deliver end() callbacks, mirroring Writable: null on successful finish,
1080+
// otherwise the error that prevented all data from being flushed.
1081+
functionflushEndCallbacks(msg,err){
1082+
constcallbacks=msg[kEndCallbacks];
1083+
if(callbacks===null)
1084+
return;
1085+
msg[kEndCallbacks]=null;
1086+
for(leti=0;i<callbacks.length;i++)
1087+
callbacks[i](err);
1088+
}
1089+
1090+
functiongetEndCallbackError(msg){
1091+
returnmsg[kErrored]??
1092+
msg[kSocket]?.errored??
1093+
newERR_STREAM_DESTROYED('end');
1094+
}
1095+
1096+
functionqueueEndCallback(msg,callback){
1097+
if(msg[kWritableFinished]){
1098+
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1099+
return;
1100+
}
1101+
if(msg[kFlushError]!==null){
1102+
process.nextTick(callback,msg[kFlushError]);
1103+
return;
1104+
}
1105+
msg[kEndCallbacks]??=[];
1106+
msg[kEndCallbacks].push(callback);
1107+
}
1108+
1109+
functiononFinish(outmsg,err){
1110+
if(err||
1111+
outmsg[kErrored]||
1112+
outmsg[kSocket]?.errored||
1113+
outmsg[kSocket]?._hadError){
1114+
outmsg[kFlushError]=err??getEndCallbackError(outmsg);
1115+
flushEndCallbacks(outmsg,outmsg[kFlushError]);
1116+
return;
1117+
}
1118+
1119+
outmsg[kWritableFinished]=true;
1120+
flushEndCallbacks(outmsg,null);
10791121
outmsg.emit('finish');
10801122
}
10811123

@@ -1104,11 +1146,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11041146
write_(this,chunk,encoding,null,true);
11051147
}elseif(this.finished){
11061148
if(typeofcallback==='function'){
1107-
if(!this.writableFinished){
1108-
this.on('finish',callback);
1109-
}else{
1110-
callback(newERR_STREAM_ALREADY_FINISHED('end'));
1111-
}
1149+
queueEndCallback(this,callback);
11121150
}
11131151
returnthis;
11141152
}elseif(!this._header){
@@ -1121,7 +1159,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
11211159
}
11221160

11231161
if(typeofcallback==='function')
1124-
this.once('finish',callback);
1162+
queueEndCallback(this,callback);
11251163

11261164
if(strictContentLength(this)&&this[kBytesWritten]!==this._contentLength){
11271165
thrownewERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten],this._contentLength);

‎test/parallel/test-http-outgoing-end-multiple.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@ const onWriteAfterEndError = common.mustCall((err) => {
1010
constserver=http.createServer(common.mustCall(function(req,res){
1111
res.end('testing ended state',common.mustCall());
1212
assert.strictEqual(res.writableCorked,0);
13+
// end() before 'finish' has been emitted queues the callback, which then
14+
// reports the outcome of the flush, matching stream.Writable.
1315
res.end(common.mustCall((err)=>{
14-
assert.strictEqual(err.code,'ERR_STREAM_ALREADY_FINISHED');
16+
assert.strictEqual(err,null);
1517
}));
1618
assert.strictEqual(res.writableCorked,0);
1719
res.end('end',onWriteAfterEndError);

‎test/parallel/test-http-outgoing-writableFinished.js‎

Lines changed: 124 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,130 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
consthttp=require('http');
5+
const{ Duplex }=require('stream');
56

6-
constserver=http.createServer(common.mustCall(function(req,res){
7-
assert.strictEqual(res.writableFinished,false);
8-
res
9-
.on('finish',common.mustCall(()=>{
10-
assert.strictEqual(res.writableFinished,true);
11-
server.close();
12-
}))
13-
.end();
14-
}));
15-
16-
server.listen(0);
17-
18-
server.on('listening',common.mustCall(function(){
19-
constclientRequest=http.request({
20-
port: server.address().port,
21-
method: 'GET',
22-
path: '/'
7+
// writableFinished becomes true once all data has been flushed, immediately
8+
// before 'finish' is emitted.
9+
{
10+
constserver=http.createServer(common.mustCall(function(req,res){
11+
assert.strictEqual(res.writableFinished,false);
12+
res
13+
.on('finish',common.mustCall(()=>{
14+
assert.strictEqual(res.writableFinished,true);
15+
server.close();
16+
}))
17+
.end();
18+
}));
19+
20+
server.listen(0);
21+
22+
server.on('listening',common.mustCall(function(){
23+
constclientRequest=http.request({
24+
port: server.address().port,
25+
method: 'GET',
26+
path: '/'
27+
});
28+
29+
assert.strictEqual(clientRequest.writableFinished,false);
30+
clientRequest
31+
.on('finish',common.mustCall(()=>{
32+
assert.strictEqual(clientRequest.writableFinished,true);
33+
}))
34+
.end();
35+
assert.strictEqual(clientRequest.writableFinished,false);
36+
}));
37+
}
38+
39+
// A request whose writes fail never becomes writableFinished and never emits
40+
// 'finish'; the end() callback receives the write error instead.
41+
{
42+
constwriteError=newError('forced write failure');
43+
constsocket=newDuplex({
44+
read(){},
45+
write(chunk,encoding,callback){
46+
callback(writeError);
47+
},
2348
});
49+
constfailedRequest=http.request({
50+
createConnection: common.mustCall(()=>socket),
51+
method: 'POST',
52+
});
53+
54+
failedRequest.on('finish',common.mustNotCall());
55+
failedRequest.on('error',common.mustCall((err)=>{
56+
assert.strictEqual(err,writeError);
57+
}));
58+
failedRequest.on('close',common.mustCall(()=>{
59+
assert.strictEqual(failedRequest.writableFinished,false);
60+
}));
61+
62+
failedRequest.write('body',common.mustCall((err)=>{
63+
assert.strictEqual(err,writeError);
64+
}));
65+
failedRequest.end(common.mustCall((err)=>{
66+
assert.ok(errinstanceofError);
67+
assert.strictEqual(failedRequest.writableFinished,false);
68+
69+
// Ending again after the flush has failed still reports the failure.
70+
failedRequest.end(common.mustCall((endAgainErr)=>{
71+
assert.strictEqual(endAgainErr,err);
72+
}));
73+
}));
74+
}
75+
76+
// The same for a server response whose flush fails (e.g. the connection is
77+
// reset mid-flush). Unlike the client case, the error here only ever
78+
// surfaces through the socket write callbacks.
79+
{
80+
constwriteError=newError('forced write failure');
81+
constsocket=newDuplex({
82+
read(){},
83+
write(chunk,encoding,callback){
84+
callback(writeError);
85+
},
86+
});
87+
88+
constserver=http.createServer(common.mustCall((req,res)=>{
89+
res.on('finish',common.mustNotCall());
90+
res.on('close',common.mustCall(()=>{
91+
assert.strictEqual(res.writableFinished,false);
92+
}));
93+
res.end('hello',common.mustCall((err)=>{
94+
assert.strictEqual(err,writeError);
95+
assert.strictEqual(res.writableFinished,false);
96+
}));
97+
}));
98+
99+
server.emit('connection',socket);
100+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
101+
}
102+
103+
// The same when end() happens after the failed write, with no data left to
104+
// flush: the write failure must still be detected even though end() itself
105+
// has nothing to send.
106+
{
107+
constwriteError=newError('forced write failure');
108+
constsocket=newDuplex({
109+
read(){},
110+
write(chunk,encoding,callback){
111+
callback(writeError);
112+
},
113+
});
114+
115+
constserver=http.createServer(common.mustCall((req,res)=>{
116+
res.on('finish',common.mustNotCall());
117+
res.setHeader('Content-Length','5');
118+
res.write('hello',common.mustCall((err)=>{
119+
assert.strictEqual(err,writeError);
120+
}));
121+
setImmediate(common.mustCall(()=>{
122+
res.end(common.mustCall((err)=>{
123+
assert.strictEqual(err,writeError);
124+
assert.strictEqual(res.writableFinished,false);
125+
}));
126+
}));
127+
}));
24128

25-
assert.strictEqual(clientRequest.writableFinished,false);
26-
clientRequest
27-
.on('finish',common.mustCall(()=>{
28-
assert.strictEqual(clientRequest.writableFinished,true);
29-
}))
30-
.end();
31-
assert.strictEqual(clientRequest.writableFinished,false);
32-
}));
129+
server.emit('connection',socket);
130+
socket.push('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
131+
}

‎test/parallel/test-stream-pipeline.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ tmpdir.refresh();
270270

271271
{
272272
constserver=http.createServer(common.mustCallAtLeast((req,res)=>{
273-
pipeline(req,res,common.mustSucceed());
273+
pipeline(req,res,common.mustCall((err)=>{
274+
// The client destroys the request body source before EOF below, so the
275+
// echoed response cannot finish successfully either.
276+
assert.strictEqual(err?.code,'ERR_STREAM_PREMATURE_CLOSE');
277+
}));
274278
}));
275279

276280
server.listen(0,common.mustCall(()=>{

0 commit comments

Comments
 (0)