diff --git a/src/handlers/aws/aws-stream.handler.ts b/src/handlers/aws/aws-stream.handler.ts index ffe573bb..e657687e 100644 --- a/src/handlers/aws/aws-stream.handler.ts +++ b/src/handlers/aws/aws-stream.handler.ts @@ -296,19 +296,9 @@ export class AwsStreamHandler 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; }, diff --git a/src/network/response-stream.ts b/src/network/response-stream.ts index a966ffe7..52d06188 100644 --- a/src/network/response-stream.ts +++ b/src/network/response-stream.ts @@ -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', { @@ -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;