Firebase Function shutdown requested via /__/quitquitquit Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

huangapple go评论72阅读模式
英文:

Firebase Function shutdown requested via /__/quitquitquit Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

问题

以下是 firebase deploy --only functions 的输出部分翻译:

i  正在部署函数
运行命令:npm --prefix "$RESOURCE_DIR" run lint

> lint
> eslint --ext .js,.ts .

运行命令:npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

✔  函数:已完成运行预部署脚本。
i  函数:准备默认的代码库以进行部署
i  函数:确保已启用所需的 API cloudfunctions.googleapis.com...
i  函数:确保已启用所需的 API cloudbuild.googleapis.com...
i  artifactregistry: 确保已启用所需的 API artifactregistry.googleapis.com...
✔  函数:已启用所需的 API cloudbuild.googleapis.com
✔  函数:已启用所需的 API cloudfunctions.googleapis.com
✔  artifactregistry: 已启用所需的 API artifactregistry.googleapis.com
i  函数:加载和分析用于代码库 default 的源代码,以确定要部署的内容
正在侦听端口 8907

通过 /__/quitquitquit 请求关闭


错误:无法成功分析函数代码库。可能存在语法或运行时错误

此外,以下是您的代码部分翻译:

/* eslint-disable max-len */
import "dotenv/config";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";
import { onDocumentCreated, onDocumentDeleted } from "firebase-functions/v2/firestore";

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

// eslint-disable-next-line @typescript-eslint/no-var-requires
const client = require("twilio")(accountSid, authToken);

export const sendSMSOnContactWrite = onDocumentCreated("/contact/{contactSubmissionId}", async (event) => {
  const data = event.data?.data();
  console.log(data);
  return await client.messages.create({
    // eslint-disable-next-line
    "body": `New contact submission from ${data?.name} at ${data?.email} with message: ${data?.message}. ${data?.name} said ${data?.hasWebsite} when asked if they have a website.${data?.hasWebsite === "yes" ? " Their website is at " + data?.websiteAddress : ""}`,
    "from": twilioPhoneNumber,
    "to": process.env.MY_PHONE_NUMBER,
  });
});

export const sendSMSOnContentItemDelete = onDocumentDeleted("/websites/{websiteId}/content/{contentGroupId}/data/{contentId}", async (event) => {
  initializeApp();
  const db = getFirestore();
  const websiteDocRef = db.doc("websites/" + event.params.websiteId);
  const websiteDoc = await websiteDocRef.get();
  const websiteDocData = websiteDoc.data();
  if (!websiteDocData) {
    // TODO: Log error
    return;
  }
  const users = websiteDocData["users"];
  for (const userId of users) {
    const userDocRef = db.doc("users/" + userId);
    const userDoc = await userDocRef.get();
    const userDocData = userDoc.data();
    if (!userDocData) {
      // TODO: Log error
      return;
    }
    const deletionPreference = userDocData["preferences"]["deletion_sms"];
    if (deletionPreference) {
      const data = event.data?.data();
      console.log(data);
      return await client.messages.create({
        "body": `Content item with title ${data?.title} was deleted from website ${websiteDocData["url"]}`,
        "from": twilioPhoneNumber,
        "to": userDocData["phone_number"],
      });
    } else {
      return;
    }
  }
});

请注意,我已经翻译了输出和代码中的文本部分,如果您需要进一步的帮助,请告诉我。

英文:

I am trying to deploy my functions. I added a second one and refactored the first and now I can't deploy. I tried deploying manually bypassing CI/CD but it still is giving the error. This is a 2.0 function and I did run tsc. Since I last deployed I did reinstall the firebase-tools package. Other than what I mentioned, nothing is different from when it did work.

Here are the output of firebase deploy --only functions:

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint --ext .js,.ts .
Running command: npm --prefix "$RESOURCE_DIR" run build
> build
> tsc
✔  functions: Finished running predeploy script.
i  functions: preparing codebase default for deployment
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
i  functions: Loading and anaylzing source code for codebase default to determine what to deploy
Serving at port 8907
shutdown requested via /__/quitquitquit
Error: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

And my code:

/* eslint-disable max-len */
import "dotenv/config";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";
import { onDocumentCreated, onDocumentDeleted } from "firebase-functions/v2/firestore";

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

// eslint-disable-next-line @typescript-eslint/no-var-requires
const client = require("twilio")(accountSid, authToken);

export const sendSMSOnContactWrite = onDocumentCreated("/contact/{contactSubmissionId}", async (event) => {
  const data = event.data?.data();
  console.log(data);
  return await client.messages.create({
    // eslint-disable-next-line
    "body": `New contact submission from ${data?.name} at ${data?.email} with message: ${data?.message}. ${data?.name} said ${data?.hasWebsite} when asked if they have a website.${data?.hasWebsite === "yes" ? " Their website is at " + data?.websiteAddress : ""}`,
    "from": twilioPhoneNumber,
    "to": process.env.MY_PHONE_NUMBER,
  });
});

export const sendSMSOnContentItemDelete = onDocumentDeleted("/websites/{websiteId}/content/{contentGroupId}/data/{contentId}", async (event) => {
  initializeApp();
  const db = getFirestore();
  const websiteDocRef = db.doc("websites/" + event.params.websiteId);
  const websiteDoc = await websiteDocRef.get();
  const websiteDocData = websiteDoc.data();
  if (!websiteDocData) {
    // TODO: Log error
    return;
  }
  const users = websiteDocData["users"];
  for (const userId of users) {
    const userDocRef = db.doc("users/" + userId);
    const userDoc = await userDocRef.get();
    const userDocData = userDoc.data();
    if (!userDocData) {
      // TODO: Log error
      return;
    }
    const deletionPreference = userDocData["preferences"]["deletion_sms"];
    if (deletionPreference) {
      const data = event.data?.data();
      console.log(data);
      return await client.messages.create({
        "body": `Content item with title ${data?.title} was deleted from website ${websiteDocData["url"]}`,
        "from": twilioPhoneNumber,
        "to": userDocData["phone_number"],
      });
    } else {
      return;
    }
  }
});

答案1

得分: 5

在我的情况下,我必须将const firestore = admin.firestore();移到函数内部,而不是放在函数外部。

英文:

In my case, I had to move const firestore = admin.firestore(); inside the function instead of having it outside the function.

答案2

得分: 2

如果您正在使用Gen 2的云函数:

请检查您是否正确使用onRequest()函数。我因为声明函数错误而遇到相同的错误。

请使用以下方式进行更正:

exports.functionName = onRequest((data, context) => { ... });

而不是:

exports.functionName = functions.onRequest((data, context) => { ... });

并且通过以下方式导入:

const { onRequest } = require("firebase-functions/v2/https");
英文:

If you're working with Cloud Functions of Gen 2:

Check if you're you're using onRequest() Function correctly. I got the same error because i declared my function wrong.

Do exports.functionName = onRequest((data, context) => { ...
instead of exports.functionName = functions.onRequest((data, context) => { ...

and import it via const {onRequest} = require("firebase-functions/v2/https");

答案3

得分: 2

在我的情况下,我在使用 firebase-tools <= 12.4.4 时使用的是 NodeJS v20.0.0。

之前,我尝试过在使用 firebase-tools <= 12.4.4 时使用 Node v19.5.0,而且我能够成功部署,没有错误。

今天,我尝试使用 NodeJS v20.0.0 并安装了 npm install firebase-tools@12.4.5 --save。在我的端上不再出现部署错误。

英文:

In my case, I was on NodeJS v20.0.0 while using firebase-tools <= 12.4.4

Previously, I tried Node v19.5.0 while using firebase-tools <= 12.4.4 and I was able to deploy with no errors.

Today, I tried using NodeJS v20.0.0 and installed npm install firebase-tools@12.4.5 --save. No more deploy errors on my end.

答案4

得分: 2

在我的情况下,它是 Slack Bolt API。

const { App, ExpressReceiver } = require('@slack/bolt');
const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
});

这段代码在部署后应该可以无错误运行,因为参数被设置为机密。

firebase functions:secrets:set SECRET_NAME

然而,似乎 firebase deploy 在代码分析期间未能应用这些机密,因此 Bolt App 崩溃,因为它缺少所需的参数。

我的解决方案是使用本地的 .env 文件,只是为了通过分析,

const { App, ExpressReceiver } = require('@slack/bolt');
require('dotenv').config();

const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
});

但要在 firebase.json 中排除它。

   "ignore": [
        ".env",
   ]
英文:

In my case, it was slack bolt api.

const { App, ExpressReceiver } = require(&#39;@slack/bolt&#39;);
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
});

This code should work without error if deployed since the parameters were set as secrets

firebase functions:secrets:set SECRET_NAME

However it seems like firebase deploy failed to apply those secrets during codebase analysis, thus the bolt App crashes not having required parameters.

My solution is to use local .env, just to pass the analysis,

const { App, ExpressReceiver } = require(&#39;@slack/bolt&#39;);
require(&#39;dotenv&#39;).config();
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
});

but to exclude it from deploying in firebase.json.

   &quot;ignore&quot;: [
&quot;.env&quot;,
]

答案5

得分: 2

通用故障排除方法

  1. 尝试使用 firebase emulators:start 启动 Firebase 模拟器
  2. 当此操作失败时,将在项目根目录创建一个新的 firebase-debug.log 文件
  3. 打开 firebase-debug.log 并滚动到底部查找错误信息

常见问题

英文:

General Troubleshooting Approach

  1. Try to start the Firebase emulators using firebase emulators:start
  2. When this fails, a new firebase-debug.log file will be created at the root of your project
  3. Open firebase-debug.log and scroll to the bottom to find the error

答案6

得分: 1

我们已经找到了解决方案和原因:在部署时访问函数配置参数。

显然,它们只能在运行时访问,而不能在部署时访问。将这些访问移到实际函数代码内部可以使事情恢复正常。

英文:

We have found a solution and the cause: accessing function config params at deploy time.

Apparently they can only be accessed at runtime, not deploy time. Moving those accesses inside the actual function code makes things work again.

答案7

得分: 1

Firebase函数似乎由于不正确的初始化而出现问题。为了解决这个问题,我建议你在 index.js 文件中全局初始化你的 Firebase 应用程序。

你应该将以下代码添加到你的 index.js 文件中:

// 全局初始化 Firebase 应用程序:
const admin = require('firebase-admin');
const functions = require('firebase-functions');

if (admin.apps.length === 0) {
  admin.initializeApp(functions.config().firebase);
}

上述代码段检查是否已经初始化了任何 Firebase 应用程序。如果没有(admin.apps.length === 0),它会使用 Firebase 配置进行初始化。

此外,你还应该确保如果你的函数没有在全局初始化 Firebase,它会进行初始化。你可以通过将以下代码添加到你的函数中来实现这一点:

if (admin.apps.length === 0) {
  admin.initializeApp();
}

通过采取这些步骤,你可以确保你的 Firebase 函数不会因为缺乏正确的初始化而关闭。

英文:

It seems that the Firebase Function might be experiencing difficulties due to an improper initialization. To resolve this issue, I suggest you initialize your Firebase app globally in the index.js file.

You should add the following code to your index.js:

// Initialize Firebase app globally:
const admin = require(&#39;firebase-admin&#39;);
const functions = require(&#39;firebase-functions&#39;);
if (admin.apps.length === 0) {
admin.initializeApp(functions.config().firebase);
}

The above code snippet checks if any Firebase apps have been initialized. If not (admin.apps.length === 0), it initializes the app using the Firebase config.

In addition, you should also ensure that your function initializes Firebase if it hasn't been initialized globally. You can accomplish this by adding the following code to your function:

if (admin.apps.length === 0) {
admin.initializeApp();
}

By taking these steps, you're making sure that your Firebase Function doesn't get shut down due to a lack of proper initialization.

答案8

得分: 0

可以由不同原因引起,要精确了解您情况下的问题是什么,运行时使用--debug选项。

因此,它将导致类似以下的结果:firebase deploy --only functions --debug

然后检查消息 错误:无法成功分析函数代码库 之前的最后一段。

希望这有所帮助。

英文:

It can be caused by different things, to know precisely what the issue is for your case, run with the --debug option.

So it will result in something like firebase deploy --only functions --debug

Then check the last paragraph before the message Error: Functions codebase could not be analyzed successfully

Hope it will help.

huangapple
  • 本文由 发表于 2023年6月29日 12:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定