Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(response-stream): fix response with no content doesn't correctly end the writable stream #206

Merged
merged 1 commit into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading