I have a cloud function that is calling a complex task (with many differents asynchronous tasks). At the end of those tasks, an event 'finished' is sent and catched by the cloud function that will terminate such as :
exports.myFunction = functions.https.onRequest(async (request: any, response: any) => {
cors(request, response, async () => {
doSomethingComplex(); // no returned value possible here, but many asynchronous tasks done
eventEmitter.on('finished', (data) => { // finished is properly sent at the end of the asynchronous tasks
functions.logger.debug('done : ', data); // is always clean with only 1 occurence at each function call
response.send({something: data.something}); // <--- THIS IS WHERE THE ERROR OCCURE
}
});
});
Currently, every asynchronous tasks are done perfectly on every calls. But EXACTLY one time out of two, the response.send()
goes in error with the following error stack :
at ServerResponse.send (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:267:15)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:530:11)
at ServerResponse.send (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:158:21)
at ServerResponse.header (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:771:10)
at EventEmitter.<anonymous> (/workspace/lib/src/index.js:235:37)
Function execution took 3354 ms, finished with status: 'crash'
I tried to use a response.end()
, i tried to return the response.send()
but everything kept to fail successfully.
I also logged every asynchronous tasks to be sure they were all finished before the 'finished' event was sent and everything is clean on that part.
I dont understand how the response.send() can be call exactly once anytime the cloud function is called but still trigger the Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
exactly One time every two calls (1 success, 1 error, 1 success, 1 error).
It doest make sense to me, just like if the cloud function was not closed after the response.send() (which is impossible according to this answer)
Does anyone have ideas ? Would be greatly appreciated !