Disable cloud function through billing alert?

38 Views Asked by At

I am meeting the same issue and found this answer[1] What is the easiest way to make Cloud Function inactive/paused?

But in this case although I can save a bool value in firebase rtdb, but since the cloud function has to keep active to check this bool value, just the rest part of this cloud function will be inactive, the cost exists already. Is there any better solution, such as setting a billing alert and then connect to pub/sub? I just have no idea how to disable the cloud function totally to save the cost that user triggers the cloud function.

here is the some code although I am not sure if it works:

const cloudfunctions = google.cloudfunctions('v1');
exports.disableFunctionOnBillingAlert = functions.pubsub.topic('wellWavel_remove_cloudFunction_whenCostTooHigh').onPublish(async (message, context) => {
  const messageData = message.json;

 
  if (messageData && messageData.costAmount && messageData.budgetAmount && messageData.costAmount >= messageData.budgetAmount) {
    
    const authClient = await google.auth.getClient({
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });
    google.options({ auth: authClient });

    const functionName = `projects/wellwave-cfc72/locations/us-central1/functions/incrementQuota`;
    try {
      await cloudfunctions.projects.locations.functions.patch({
        name: functionName,
        updateMask: 'status',
        requestBody: {
          status: 'INACTIVE',
        },
      });
      console.log(`Cloud Function ${functionName} has been disabled.`);
    } catch (error) {
      console.error(`Failed to disable Cloud Function ${functionName}:`, error);
      throw new Error(`Failed to disable Cloud Function ${functionName}: ${error}`);
    }
  }
0

There are 0 best solutions below