Why are all of my firebase cloud functions timing out?

Viewed 4569

I'm trying to use firebase cloud functions to create a proxy to an external json api. But right now I'm just trying to get it all set up.

I wrote this function:

exports.helloWorld = functions.https.onRequest((request, response) => {
  request.get('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body) // Print the google web page.
    }
  })
});

I then run the firebase functions emulator and run

curl http://localhost:5000/<project-id>/us-central1/helloWorld

It returns a message saying the function was triggered, starting execution, but then it just sits there and spins until eventually it times out.

{"error":{"code":500,"status":"INTERNAL","message":"function execution attempt timed out"}}

I'm not sure what I'm doing wrong.

........

EDIT

This function works perfectly:

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send('test');
})
2 Answers

With Cloud Functions, HTTPS type functions are obliged to write a result to the client to indicate that the function is done executing. Until a result is written, the function is assumed to still be running something asynchronous work.

So, when your request is complete, you should be sending some response, even if it's empty. Unfortunately, you've shadowed your primary response object with another one, so you should probably rename one of them:

exports.helloWorld = functions.https.onRequest((request, response) => {
  request.get('http://www.google.com', function (error, res, body) {
    if (!error && res.statusCode == 200) {
      console.log(body) // Print the google web page.
    }
    return response.send("") // this terminates the function
  })
})

HTTPS functions don't complete until you send something on the response. Here's an example that just pipes the content from the proxied request as the output (I had to change the name of the variables to avoid shadowing:

exports.helloWorld = functions.https.onRequest((req, res) => {
  request.get('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      return res.send(body) // Print the google web page.
    }
    return res.send('ERROR: ' + error.message);
  })
});
Related