Skip to content

Commit

Permalink
fix(response-stream): fix response with no content doesn't correctly …
Browse files Browse the repository at this point in the history
…end the writable stream
  • Loading branch information
stackia committed Feb 28, 2024
1 parent 250221f commit bded8cf
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
16 changes: 3 additions & 13 deletions src/handlers/aws/aws-stream.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,19 +296,9 @@ export class AwsStreamHandler<TApp> extends BaseHandler<
awsMetadata,
);

// some status do not return body, and
// for some unknown reason, we cannot finish the stream without writing at least once
// so I have this thing just to fix this issue
// ref: https://stackoverflow.com/a/37303151
const isHundreadStatus = status >= 100 && status < 200;
const isNoContentStatus = status === 304 || status === 204;
const isHeadRequest = requestValues.method === 'HEAD';

if (isHundreadStatus || isNoContentStatus || isHeadRequest) {
finalResponse.write('');
// end the response to avoid waiting for nothing
response.end();
}
// We must call write with an empty string to trigger the awsMetadata to be sent
// https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/blob/2ce88619fd176a5823bc5f38c5484d1cbdf95717/src/HttpResponseStream.js#L22
finalResponse.write('');

return finalResponse;
},
Expand Down
7 changes: 6 additions & 1 deletion src/network/response-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,11 @@ export class ServerlessStreamResponse extends ServerResponse {
const stringData = getString(data);
const endStatusIndex = stringData.indexOf(endStatusSeparator);
const status = +stringData.slice(0, endStatusIndex).split(' ')[1];
const endHeaderIndex = stringData.indexOf(headerEnd);

const headerData = stringData.slice(
endStatusIndex + 2,
stringData.indexOf(headerEnd),
endHeaderIndex,
);
const headers = parseHeaders(headerData);
log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS', {
Expand All @@ -118,6 +119,10 @@ export class ServerlessStreamResponse extends ServerResponse {

writesToIgnore = 1;
internalWritable = onReceiveHeaders(status, headers);

// If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable
if (stringData.substring(endHeaderIndex + 4) === endChunked)
internalWritable.end();
}

return true;
Expand Down

0 comments on commit bded8cf

Please sign in to comment.