GCP : error PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR when trying to Connect a Cloud functions 2nd gen to a Cloud SQL Database

  • Modifié il y à1 semaine 
  • Temps de lecture :2Minutes

Example with a Node.js Cloud Function with the mysql dependency deployed as a 2nd gend Cloud Function.

const mysql = require('mysql');

const connectionConfig = {
    user: 'test',
    password: 'test',
    database: 'my-db',
    socketPath: '/cloudsql/deddy-exelcia:us-central1:my-db'
};

const connection = mysql.createConnection(connectionConfig);

exports.retrieveUsers = async (event, context) => {
    // Retrieve users
    connection.query(
        'SELECT * FROM users',
        (error, results) => {
            if (error) {
                console.error('Error retrieve users from database error :', error);
            } else {
                console.log(`Results : ${results}.`);
            }
        }
    );
};
{
  "name": "retrieve-users",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mysql": "^2.18.1"
  }
}

If you get the error PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR

Error updating database: Error: Cannot enqueue Query after fatal error.
    at Protocol._validateEnqueue (/workspace/node_modules/mysql/lib/protocol/Protocol.js:212:16)
    at Protocol._enqueue (/workspace/node_modules/mysql/lib/protocol/Protocol.js:138:13)
    at Connection.query (/workspace/node_modules/mysql/lib/Connection.js:198:25)
    at exports.updateCarAvailability (/workspace/index.js:29:16)
    at /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/function_wrappers.js:141:25
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
  fatal: false

Solution

You must add your Cloud SQL database instance in the “CloudSQL Connections” parameter of the Cloud Run service generated by the creation of your Cloud Functions 2nd gen.

Creating a 2nd gen Cloud Function generates a Cloud Run service, but for a Cloud Run service to access a Cloud SQL instance it is necessary to configure the “Cloud SQL Connections” parameter.

  • Go to Cloud Run
  • Locate the Cloud Run service which has the same name as your Cloud Function
  • Access the service setting
  • “Cloud SQL connections” parameter > Add the connection to your Cloud SQL database instance.
  • Click on Save

Cloud SQL connections setting

Laisser un commentaire