Google Scheduled functions: There was an error deploying functions? - firebase

I have a fresh project but was looking to test scheduled functions. Am I missing anything?
$ firebase deploy
=== Deploying to 'testing-db'...
i deploying functions
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
! functions: missing required API cloudbuild.googleapis.com. Enabling now...
+ functions: required API cloudfunctions.googleapis.com is enabled
+ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (24.45 KB) for uploading
i functions: ensuring required API pubsub.googleapis.com is enabled...
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
! functions: missing required API cloudscheduler.googleapis.com. Enabling now...
+ functions: required API pubsub.googleapis.com is enabled
+ functions: required API cloudscheduler.googleapis.com is enabled
+ functions: functions folder uploaded successfully
i functions: creating Node.js 14 function scheduledFunction(us-central1)...
Functions deploy had errors with the following functions:
scheduledFunction(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
Index.js
const functions = require('firebase-functions');
exports.scheduledFunction = functions.pubsub
.schedule('every 1 minutes')
.onRun((context) => {
return console.log('This will be run every 1 minutes!');
});
Firebase log shows:
Error: Failed to upsert schedule function scheduledFunction in region europe-west1

I ran into this issue as well, but the solution was not region related like #Priyashree's answer. Rather, when I ran firebase deploy --only functions --debug the logs revealed that my scheduler had an error.
The bottom of the log had this error:
Error: Failed to upsert schedule function foo in region us-central1
But scrolling up a bit revealed:
<<< HTTP RESPONSE BODY {"error":{"code":400,"message":"Schedule or time zone is invalid.","status":"INVALID_ARGUMENT"}}
I had a typo in my function schedule:
functions.pubsub.schedule("every 1 minute").onRun((context) => {}
every 1 minute should have been every 1 minutes. Note the missing 's'.
In general, I think it's useful to enable '--debug' on the firebase deploy command so you can see detailed log output of the exact error.

When you are using scheduled functions in Firebase Functions, an App Engine instance is created that is needed for Cloud Scheduler to work. You can read about it here.They use the location that has been set by default for resources. I think that you are getting that error because there is a difference between the default GCP resource location you specified and the region of your scheduled cloud function. If you click on the cogwheel next to project-overview in Firebase you can see where your resources are located.
Check your Cloud Scheduler function details and see which region it has been deployed to. By default, functions run in the us-central1 region. Check this link to see how we can change the region of the function.

Related

firebase deploy fuctions error Upload Error: HTTP Error: 403

firebase deploy --only functions
=== Deploying to 'rouda-****'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build
build
tsc
functions: Finished running predeploy script.
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 cloudfunctions.googleapis.com is enabled
artifactregistry: required API artifactregistry.googleapis.com is enabled
functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
i functions: preparing functions directory for uploading...
i functions: packaged D:\IonicApps\RoudaApp\functions (59.1 KB) for uploading
! functions: Upload Error: HTTP Error: 403, UserProjectAccountProblemThe project to be billed is associated with an absent billing account.The billing account for the owning project is disabled in state absent
Error: HTTP Error: 403, UserProjectAccountProblemThe project to be billed is associated with an absent billing account.The billing account for the owning project is disabled in state absent
i tried firebase logout & login,
Pay as you go(plaze ) firebase project,
GC billing Account Enabled,
i changed the GC Billing Account for the project,
tried to deploy other firebase projects - same issue,
downgrade to firebase tools --version 11.1.0 & 11.14.3,
installed latest firebase-functions,
installed firebase-tools11.14.4,
could not deploy either..
The error message is telling you there is a problem with your billing account. Specifically that it is in a disabled state. You will need to resolve it in the billing console: https://console.cloud.google.com/billing

Failed to load function definition from source: Failed to generate manifest from function source: Error: username is required

When I run firebase deploy I get the following output:
> build
> tsc
✔ functions: Finished running predeploy script.
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...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing codebase default for deployment
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: username is required
Which is odd because the same command has been working for weeks. Is there some "username" field that I need to put into firebase.json or something?
The proper way to initialize Firebase within a Cloud Function would be to use the firebase-admin client as shown here.
I would recommend you try using the below while initializing the app and see if this works:
import {initializeApp} from "firebase-admin/app";
Another thing to check are the firebase function dependencies whether they are still built intact.
As seen per your code, it looks like you're trying to use the Cloud Functions for TypeScript, and npm run build -- --watch takes care of updating the built code as you are coding. Cloud Functions would run with the built JS code and not the TypeScript code.
The problem could be that the setup at the entry point of Cloud Functions is a .ts file and not .js. In your package.json for Functions, you have
"main": "src/index.ts"
Try changing it to:
"main": "lib/index.js"
That way the entry point of Cloud Functions will be a JavaScript file, and also, will be the JavaScript that was built from your TypeScript code. lib/index.js is used because, by default, that is where the tsc command will build your src/index.ts file into.
Also do check this helpful document for troubleshooting the function deploy issues.

Deploying to FIREBASE - Error: There was an error deploying functions

I was looking to test a function but getting this error. Am I missing anything? Can anyone help me?
This is the error message in my terminal:
firebase deploy --only functions
=== Deploying to 'procuradoria-15967'...
i deploying functions
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i functions: ensuring required API artifactregistry.googleapis.com is enabled...
+ functions: required API artifactregistry.googleapis.com is enabled
+ functions: required API cloudfunctions.googleapis.com is enabled
+ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (52.22 KB) for uploading
+ functions: functions folder uploaded successfully
i functions: updating Node.js 12 function testeadm(us-central1)...
Functions deploy had errors with the following functions:
testeadm(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
This is my Index.js:
// Initialize Cloud Firestore through Firebase
const { initializeApp } = require("firebase-admin/app")
const { getFirestore } = require("firebase-admin/firestore")
const functions = require('firebase-functions');
const { GoogleSpreadsheet } = require('google-spreadsheet');
initializeApp();
exports.testeadm = functions.https.onRequest(async(req, res) => {
console.log("teste")
const doc = new GoogleSpreadsheet("...")
await doc.useServiceAccountAuth({"private_key": "...",
"client_email": "..."});
await doc.loadInfo();
console.log(doc.title)
})
This is the register Firebase log error message:
testeadm
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."},"authenticationInfo":{"principalEmail":"..."},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/.../locations/us-central1/functions/testeadm"}

Firebase Cloud functions stop working after Cloud Build deploy

I am using Cloud Build to deploy my firebase project (hosting and cloud functions) trigged by a commit to a branch in a github repo. The deploy is successful and the site works, but the cloud functions don't run after the deploy. They don't even show up in the log as being called, so there are no errors.
I click a button from the UI that calls a cloud function, which saves some data to the real-time database. The code to call the function is run in a try catch, and the catch code runs. The logs for the cloud function show nothing -- the function isn't even run. When I then deploy the project locally from my laptop instead of via cloud build, the cloud function runs when the button is clicked and the data is saved to the database and the logs indicate that the function was invoked. None of the cloud functions are invoked when triggering an event from the front end, however, when I have deployed from Cloud Build
It's only when the project is deployed by Cloud Build that the functions don't run when they are called. I am wondering if this could be a permissions issue?
Front end code:
const createTeam = (payload) => {
return async (dispatch, getState, getFirebase) => {
debugger;
const createTeam = getFirebase().functions().httpsCallable("createTeam");
console.log("create team===>", createTeam);
try {
console.log("about to run");
await createTeam(payload);
dispatch(
sendNotification({
severity: "success",
message: "Team Created",
isOpen: true,
})
);
} catch (e) {
dispatch(
sendNotification({
severity: "error",
message: "An error occurred and team was not created.",
isOpen: true,
})
);
}
};
};
Build file:
steps:
- name: "gcr.io/cloud-builders/npm"
dir: "functions"
args: ["install"]
# Install
- name: "gcr.io/cloud-builders/npm"
args: ["install"]
# Build
- name: "gcr.io/cloud-builders/npm"
args: ["run", "build"]
# Deploy
- name: "gcr.io/$PROJECT_ID/firebase"
args: ["deploy", "--project=$PROJECT_ID"]
from the deployment logs:
Hosting URL: xxxx
Project Console: xxxx
✔ Deploy complete!
✔ hosting[agile-boost]: release complete
i hosting[agile-boost]: releasing new version...
✔ hosting[agile-boost]: version finalized
i hosting[agile-boost]: finalizing version...
✔ functions[launchAssessments(us-central1)]: Successful update operation.
✔ functions[createTeam(us-central1)]: Successful update operation.
✔ functions[sendParticipantEmailWhenAssessmentOpens(us-central1)]: Successful update operation.
✔ functions[completeAssessments(us-central1)]: Successful update operation.
✔ functions[refreshMetricCategoryAvg(us-central1)]: Successful update operation.
✔ functions[saveParticipantAnswer(us-central1)]: Successful update operation.
✔ functions[updateParticipant(us-central1)]: Successful update operation.
✔ functions[closeAssessmentsWhenTeamIsDeleted(us-central1)]: Successful update operation.
✔ functions[getParticipantsData(us-central1)]: Successful update operation.
✔ functions[createAccount(us-central1)]: Successful update operation.
✔ functions[addParticipantToAssessment(us-central1)]: Successful update operation.
✔ functions[createAssessment(us-central1)]: Successful update operation.
✔ functions[reviseAssessmentMetrics(us-central1)]: Successful update operation.
✔ functions[refreshMetricQuestionAvg(us-central1)]: Successful update operation.
✔ functions[updateParticipantWhenTeamParticipantUpdates(us-central1)]: Successful update operation.
✔ functions[refreshMetricTagAvg(us-central1)]: Successful update operation.
✔ functions[updateMetricsWhenParticipantStatusChanges(us-central1)]: Successful update operation.
✔ functions[addNewTeamParticipantToActiveAssessments(us-central1)]: Successful update operation.
✔ functions[getSurveyData(us-central1)]: Successful update operation.
i functions: scheduler job firebase-schedule-completeAssessments-us-central1 is up to date, no changes required
i functions: scheduler job firebase-schedule-launchAssessments-us-central1 is up to date, no changes required
✔ pubsub: required API pubsub.googleapis.com is enabled
✔ scheduler: required API cloudscheduler.googleapis.com is enabled
i pubsub: ensuring required API pubsub.googleapis.com is enabled...
i scheduler: ensuring required API cloudscheduler.googleapis.com is enabled...
i functions: updating Node.js 10 function completeAssessments(us-central1)...
i functions: updating Node.js 10 function launchAssessments(us-central1)...
i functions: updating Node.js 10 function getParticipantData(us-central1)...
i functions: updating Node.js 10 function getParticipantsData(us-central1)...
i functions: updating Node.js 10 function closeAssessmentsWhenTeamIsDeleted(us-central1)...
i functions: updating Node.js 10 function updateParticipantWhenTeamParticipantUpdates(us-central1)...
i functions: updating Node.js 10 function updateMetricsWhenParticipantStatusChanges(us-central1)...
i functions: updating Node.js 10 function sendParticipantEmailWhenAssessmentOpens(us-central1)...
i functions: updating Node.js 10 function addNewTeamParticipantToActiveAssessments(us-central1)...
i functions: updating Node.js 10 function saveParticipantAnswer(us-central1)...
i functions: updating Node.js 10 function getSurveyData(us-central1)...
i functions: updating Node.js 10 function updateParticipant(us-central1)...
i functions: updating Node.js 10 function addParticipantToAssessment(us-central1)...
i functions: updating Node.js 10 function createAssessment(us-central1)...
i functions: updating Node.js 10 function createTeam(us-central1)...
i functions: updating Node.js 10 function createAccount(us-central1)...
i functions: updating Node.js 10 function reviseAssessmentMetrics(us-central1)...
i functions: updating Node.js 10 function refreshMetricQuestionAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricTagAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricCategoryAvg(us-central1)...
✔ database: rules for database xxxx released successfully
i database: releasing rules...
✔ hosting[agile-boost]: file upload complete
i hosting: uploading new files [4/6] (66%)
i hosting: hashing files [34/35] (97%)
i hosting: hashing files [34/35] (97%)
i hosting[agile-boost]: found 35 files in build
i hosting[agile-boost]: beginning deploy...
✔ functions: functions folder uploaded successfully
i functions: packaged functions (52.61 KB) for uploading
i functions: preparing functions directory for uploading...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
✔ database: rules syntax for database agile-boost is valid
i database: checking rules syntax...
✔ functions: Finished running predeploy script.
> tsc
> functions# build /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run build
> tslint --project tsconfig.json
> functions# lint /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
i deploying database, functions, hosting
=== Deploying to 'xxxx'...
gcr.io/agile-boost/firebase:latest
Status: Downloaded newer image for gcr.io/agile-boost/firebase:latest
Digest: sha256:063a10dfecc2b3bb4245316fb89ae1588f594bb8bb6e950ecf6a9488015e20bb
38ee9b020816: Pull complete
ddf8c3713c7d: Pull complete
9819791ca1ba: Pull complete
19c9987a828c: Pull complete
40ba0f817ab5: Pull complete
8cdf70a16731: Pull complete
9819791ca1ba: Download complete
9819791ca1ba: Verifying Checksum
8cdf70a16731: Download complete
8cdf70a16731: Verifying Checksum
38ee9b020816: Download complete
38ee9b020816: Verifying Checksum
ddf8c3713c7d: Download complete
ddf8c3713c7d: Verifying Checksum
40ba0f817ab5: Download complete
40ba0f817ab5: Verifying Checksum
19c9987a828c: Download complete
19c9987a828c: Verifying Checksum
38ee9b020816: Waiting
ddf8c3713c7d: Waiting
9819791ca1ba: Waiting
38ee9b020816: Pulling fs layer
ddf8c3713c7d: Pulling fs layer
9819791ca1ba: Pulling fs layer
19c9987a828c: Pulling fs layer
40ba0f817ab5: Pulling fs layer
8cdf70a16731: Pulling fs layer
e5c5821cd889: Already exists
55abbc6cc158: Already exists
8439168fd8dc: Already exists
c159512f4cc2: Already exists
1b49aa113642: Already exists
4f250268ed6a: Already exists
latest: Pulling from agile-boost/firebase
Using default tag: latest
Pulling image: gcr.io/agile-boost/firebase

Using the local emulator - Firebase Serve - Error: Certificate object must be an object

Goal
Use the firebase emulator and deploy firebase cloud functions locally for test and debug.
Issue
When firebase serve is run, it fails with - Error: Certificate object must be an object.
What's been tried
Following Google's documentation here, the instructions include
these steps:
To set up admin credentials for emulated functions (other than Cloud
Firestore and Realtime Database):
Open the Service Accounts pane of the Google Cloud Console.
Make sure that App Engine default service account is selected, and use the options menu at right to select Create key.
When prompted, select JSON
for the key type, and click Create. Set your Google default
credentials to point to the downloaded key:
$ export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json"
$ firebase functions:shell
OR
$ firebase serve --only functions
Completing these instructions and running firebase serve... fails. Here are the logs:
Silver-Sliver:functions dchaddportwine$ firebase serve --only functions
=== Serving from '/Users/dchaddportwine/Sites/people-is-cloud-functions/functions'...
i functions: Preparing to emulate functions.
Warning: You're using Node.js v8.11.1 but Google Cloud Functions only supports v6.11.5.
⚠ functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
⚠ functions: Error from emulator. Error occurred while parsing your function triggers.
Error: Certificate object must be an object.
at FirebaseAppError.FirebaseError [as constructor] (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseAppError (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/utils/error.js:119:28)
at new Certificate (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/auth/credential.js:106:19)
at new CertCredential (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/auth/credential.js:189:64)
at Object.cert (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/node_modules/firebase-admin/lib/firebase-namespace.js:220:58)
at Object.<anonymous> (/Users/dchaddportwine/Sites/people-is-cloud-functions/functions/index.js:21:32)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
Question
How do I fix these two errors?
I have firebase-functions installed, and have tried npm i --save firebase-functions
⚠ functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
Thinking this has to do with GOOGLE_APPLICATION_CREDENTIALS, but I'm not sure how to verify or check what's happening here.
⚠ functions: Error from emulator. Error occurred while parsing your function triggers.
Error: Certificate object must be an object.
UPDATE
Further along in the documentation, it reads:
If you're using custom functions configuration variables, run the
following command in the functions directory of your project before
running firebase serve.
firebase functions:config:get > .runtimeconfig.json
After running this command, I no longer get the certificate error. Woot! However, I am getting new failures and not many hints from the logs.
=== Serving from '/Users/dchaddportwine/Sites/people-is-cloud-functions/functions'...
i functions: Preparing to emulate functions.
i hosting[development-is]: Serving hosting files from: ./
✔ hosting[development-is]: Local server: http://localhost:5000
Warning: You're using Node.js v8.11.1 but Google Cloud Functions only supports v6.11.5.
⚠ functions: Failed to emulate app
⚠ functions: Failed to emulate helloSlack
⚠ functions: Failed to emulate helloIssy
⚠ functions: Failed to emulate interactiveIssy
i functions: No HTTPS functions found. Use firebase functions:shell if you would like to emulate other types of functions.
Code
Here is the firebase cloud functions for helloSlack
exports.helloSlack = functions.https.onRequest((req, res) => {
if (req) {
res.status(200).send(req.body);
} else {
console.log("req Error...");
throw res.status(500);
}
});
Answer
Further along in the documentation, it reads:
If you're using custom functions configuration variables, run the
following command in the functions directory of your project before
running firebase serve.
firebase functions:config:get > .runtimeconfig.json
This project is using custom functions configuration variables. So, after running the config command, I no longer get the certificate error. Woot!

Resources