I would like to share reference to a Cloud Spanner instance and database within each instance of my cloud function so that each invocation of the cloud function does not create a new connection to Spanner. See Optimizing Networking.
Is there a teardown function where I can close the connection to the database in this Node.js 8 beta implementation?
myFunction/index.js
const Spanner = require("@google-cloud/spanner");
const spanner = Spanner();
/**
* Maintain a persistent connection instead of creating a new
* connection upon every function invocation
*/
const instance = spanner.instance("test-instance");
const database = instance.database("example-db");
const myTable = database.table("my-table");
/**
* Creates a Spanner record from data in a pubsub message
*
* @param {!Object} event Event payload.
*/
exports.insertRowToMyTable = (event) => {
const pubsubMessage = event.data;
const decodedMessage = JSON.parse(Buffer.from(pubsubMessage, "base64").toString())
console.log("Decoded Message: ", decodedMessage);
const tableRow = {
fieldOne: decodedMessage.fieldOne,
fieldTwo: decodedMessage.fieldTwo,
fieldThree: decodedMessage.fieldThree,
};
console.log("Inserting: ", tableRow);
myTable.insert([tableRow])
.then(() => {
console.log("Inserted: ", tableRow);
})
.catch(err => {
console.error(err);
})
};
/**
* Is there a teardown function where I can place this such that
* the connection pool is closed when the cloud function instance
* shuts down?
*
* // Close the database when finished.
* database.close();
*/
A server instance running your code in Cloud Functions will simply stop running when it's no longer needed. There is no way to know or intercept a notification when that happens. You won't need to close any connections because they will all be forced to close when the instance terminates. Think of it like simply flipping the power switch off.