Rodrigo
Rodrigo

Reputation: 321

Using Cloud Run on a PubSub topic

It was not clear to me how to use Cloud Run on a PubSub topic for for medium-run tasks (inside of the time limit of Cloud Run, of course.)

Let's see this example taken from the tutorials[1]:

app.post('/', (req, res) => {

  if (!req.body) {
    const msg = 'no Pub/Sub message received'
    console.error(`error: ${msg}`)
    res.status(400).send(`Bad Request: ${msg}`)
    return
  }
  if (!req.body.message) {
    const msg = 'invalid Pub/Sub message format'
    console.error(`error: ${msg}`)
    res.status(400).send(`Bad Request: ${msg}`)
    return
  }

  const pubSubMessage = req.body.message
  const name = pubSubMessage.data
    ? Buffer.from(pubSubMessage.data, 'base64').toString().trim()
    : 'World'

  console.log(`Hello ${name}!`)
  res.status(204).send()
})

My doubt is: Should it return HTTP 204 only after the task finishes, otherwise the task will terminated sudden?

1 - https://cloud.google.com/run/docs/tutorials/pubsub

Upvotes: 1

Views: 304

Answers (1)

John Hanley
John Hanley

Reputation: 81386

My doubt is: Should it return HTTP 204 only after the task finishes, otherwise the task will terminated sudden?

You do not have a choice. If you return before your task/objective finishes, the CPU will be idled to zero and nothing will happen in your Cloud Run instance.

In your example, you are just processing a pub/sub message and extracting the name. If you return before this is finished, no name will be processed.

Cloud Run is designed for an HTTP Request/Response system. This means processing begins when you receive an HTTP Request (GET, POST, PUT, etc.) and ends when your code returns an HTTP Response (or just returns with no response). You might try to create background threads but there is no guarantee that they will execute once your main function returns.

Upvotes: 3

Related Questions