Reputation: 1426
I have a firebase application that uses Cloud Functions to talk to a Google Cloud SQL instance. These cloud functions are used to perform CRUD actions. I would like to ensure that the database reflects the CRUD operations, as such, run migration code every time I push new function code to ensure the database is always up to date.
I do this in a global function
const functions = require('firebase-functions')
const pg = require('pg')
// Create if not exists database
(function() {
console.log('create db...')
})()
exports.helloWorld = functions.https.onRequest((request, response) => {
console.log('Hello from Firebase function log!')
response.send('Hello from Firebase!')
})
exports.helloWorld2 = functions.https.onRequest((request, response) => {
console.log('Hello from Firebase function log 2!')
response.send('Hello from Firebase 2!')
})
This console log then runs twice when I deploy.
Now I understand that there is no way of knowing how many instances Cloud Functions will spin up for the functions, as stated in their docs:
The global scope in the function file, which is expected to contain the function definition, is executed on every cold start, but not if the instance has already been initialized.`
If I add a third function, this console log is now shown 3 times in the logs, instead of 2, one for each function. Would it be correct in saying that there's a new instance for every single function uploaded? I am trying to understand what happens under the hood when I upload a set of cloud functions.
If so - is there no reliable way to run migration code inside a global function in cloud functions?
Upvotes: 0
Views: 1435
Reputation: 317372
What you're doing isn't a supported use case for Cloud Functions. Cloud Functions code runs in response to events that occur in your project. There is no "one time" function invocations that happen on deployment. If you need to run code a single time, just run that from your desktop or some other server you control.
You should also strive to minimize the amount of work that happens in the global scope of your functions. Globals will be instantiated and run once for each allocated server instance running a function in your app, as each function runs in full isolation of each other, and each has its own copy of everything. Watch my video about function scaling and isolation to better understand this behavior.
Upvotes: 1