ike1504
ike1504

Reputation: 119

Publish on google cloud pub/sub with a cloud function take 3minutes - nodejs

i'm doing a function that will publish the type of an event after recieved a webhook. it's working but it publish the message something like 3 minutes after the function started. this long pause come from the const {PubSub} = require('@google-cloud/pubsub') How can i make it go faster ? thanks !

Source Code:

exports.Challenge = (req,res) => {
    var type = req.body['event']['type']   
    console.log(type)                       
    console.log("start pubsub msg function")
    msgpubsub(type)
    console.log("end pubsub msg function")
}

function msgpubsub(_type){
    const topicName = "NAME_OF_TOPIC"
    console.log(`publishing message to topic: ${topicName}`)

    console.log("start require('@google-cloud/pubsub")
    const {PubSub} = require('@google-cloud/pubsub')
    console.log("end require(@google-cloud/pubsub)")

    console.log("start new pubsub")
    const pubSubClient = new PubSub('ID');
    console.log("end newpubsub")
    
    const messageBuffer = Buffer.from(_type)
    console.log("message buffer : " + messageBuffer)

    try{
        pubSubClient.topic(topicName).publish(messageBuffer)
    } catch(err){
        console.error(err)
    }

logs

Upvotes: 2

Views: 1382

Answers (1)

Kamal Aboul-Hosn
Kamal Aboul-Hosn

Reputation: 17206

It would be best to create the client once and then publish a message using the client when the event is received. As it is now, you are creating a brand new client on every event, which is expensive.

const topicName = "NAME_OF_TOPIC"
const {PubSub} = require('@google-cloud/pubsub')
const pubSubClient = new PubSub('ID');
const topicPublisher = pubSubClient.topic(topicName);

exports.Challenge = (req,res) => {
    var type = req.body['event']['type']   
    console.log(type)                       
    console.log("start pubsub msg function")
    msgpubsub(type)
    console.log("end pubsub msg function")
}

function msgpubsub(_type){    
    const messageBuffer = Buffer.from(_type)
    console.log("message buffer : " + messageBuffer)

    try {
        var publishFuture = topicPublisher.publish(messageBuffer);
        publishFuture.get();
    } catch(err){
        console.error(err)
    }
}

Upvotes: 3

Related Questions