I am trying to deploy my Cloud Function using Cloud Firestore as Trigger. The Cloud function simply listens to any new document creation on my firestore path and logs the new data to the console. However, the function deployment is failing and there is no clear error message. Could you please help me identify what could be the issue?
Cloud Function Code:
const functions = require('firebase-functions');
exports.createUser = functions.firestore
.document('test_restaurant/{id}/reviews/{id}')
.onCreate((snap, context) => {
console.log(snap.data());
});
Error Log:
2020-06-28 18:51:03.110 IST
Cloud Functions
UpdateFunction
asia-east2:function-test-2
abc#gmail.com
Function failed on loading 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
Expand all | Collapse all
{
insertId: "5u231ccch0"
logName: "projects/fs-22/logs/cloudaudit.googleapis.com%2Factivity"
operation: {
id: "operations/ZmlyZXN0b3JlLTI0OTcwNS9hc2lhLWVhc3QyL2Z1bmN0aW9uLXRlc3QtMi9xOVJCbHpESzdjSQ"
last: true
producer: "cloudfunctions.googleapis.com"
}
protoPayload: {
#type: "type.googleapis.com/google.cloud.audit.AuditLog"
authenticationInfo: {
principalEmail: "abc#gmail.com"
}
methodName: "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction"
resourceName: "projects/fs-22/locations/asia-east2/functions/function-test-2"
serviceName: "cloudfunctions.googleapis.com"
status: {
code: 3
message: "Function failed on loading 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"
}
}
receiveTimestamp: "2020-06-28T13:21:03.364975479Z"
resource: {
labels: {
function_name: "function-test-2"
project_id: "fs-22"
region: "asia-east2"
}
type: "cloud_function"
}
severity: "ERROR"
timestamp: "2020-06-28T13:21:03.110Z"
}
The issue resolved. Basically the error was using the same wildcard twice in the document path. The reference causing the problem was {id}, I just changed one of those references. The new path is: .document('test_restaurant/{id}/reviews/{reviewsId}') and the deployment succeeded.
Check if you have some dependencies installed on your root folder. You should have all your modules installed inside the functions folder. Only firebase dependencies should be in your root folder. Try to do npm uninstall yourDependencie inside your root folder and then npm i yourDependencie inside root/functions folder.
If you are using lint, you need to make sure your code is passing eslint . command, other wise youl'll get that error deploying to firebase
{
"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{
"code":3,
"message":"Function failed on loading 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"
},
"authenticationInfo":{
"principalEmail":"your_email"
},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/your_project/locations/us-central1/functions/your_func"
}
For my case I fix it by dissabling prettier on index, also, if you have more files you have to disable it for each one.
/* eslint-disable prettier/prettier */
Related
I’m trying to get Sentry working with winston (using winston-transport-sentry-node) but it doesn’t seem to work, despite using just a very basic configuration. So out of curiosity, I tried writing my own very simple winston transport class that sends Sentry message for every log like so
import * as Sentry from '#sentry/node'
import * as TransportStream from 'winston-transport'
export class SentryCustomTransport extends TransportStream {
constructor(opts) {
super(opts)
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.ENV_NAME,
sampleRate: 1,
tracesSampleRate: 1,
})
Sentry.captureMessage('Test message constructor')
}
log(info, callback) {
setImmediate(() => {
this.emit('logged', info);
})
console.log('Called log function')
const eventId = Sentry.captureMessage('Test message log')
console.log('Event ID:', eventId)
callback()
}
}
After calling winston logger, I can see an entry in Sentry with message "Test message constructor" but not "Test message log". What's even weirder is I can see the console log prints, including the event ID returned from the calls to Sentry.captureMessage() in the log() function.
I'm not sure what's going on, and kind of have no idea how to make it work. What am I missing here?
winston version: 3.8.2
#sentry/node version: 7.37.2
winston-transport-sentry-node version: 2.7.0
I managed to find the cause of the issue myself. The context of my issue was I'm writing a CLI command in NestJS. Part of the command's implementation (rather incorrectly) include a call to process.exit() function which immediately terminates the command without giving it a chance to do proper clean up (and flushing of data). I'm guessing it's because of this the Sentry module didn't get the chance to actually push the created Sentry event to Sentry server.
Removing the calls to process.exit() and letting the command finishes normally resolves the issue.
When I try to make a call from my front-end (NextJS) I get the following error Error: Body must be a string. Received: undefined.
I can successfully make a call from my AppSync console, but not from my front-end. I have pushed the following schema.graphql file with amplify push:
type Mutation {
...
cancelCard(input: CancelCardInput!): AWSJSON
#function(name: "myp-service-prod-cancel-stepfunction-lambda")
}
I'm seeing logs in CloudWatch when I trigger the Lambda from the Lambda and AppSync consoles, but something is blocking the calls from my javascript:
import { cancelCard } from "../src/graphql/mutations";
const lambdaResponse = await API.graphql(
graphqlOperation(cancelCard, {
input: { id: cardId },
})
)
The problem was that I had performed amplify codegen configure and updated from javascript to typescript. As a result, Amplify had updated my src/ folder to have .ts files in, but not removed the .js files. This meant that where I had:
src/graphql/
mutations.ts
mutations.js
My app was ignoring the mutations.ts file.
Deleting the js files solved the issue.
I want to send message through firebase cloud message via firebase cloud function. Here's my code below
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const axios = require('axios');
//import axios from 'axios';
exports.abc = functions.pubsub.schedule('every 50 minutes').onRun(async (context) => {
let response=await axios.get(
'https://coronavirus-19-api.herokuapp.com/countries/bangladesh'
);
console.log(response.data);
let body=response.data.todayDeaths;
console.log(body);
let message = {
notification: {
'title': 'Today death',
'body': `${body}`,
},
topic:'allUser'
};
admin.messaging().send(message)
.then(response=>{
console.log("Successfully sent",response);
}).catch(error=>{
console.log("failed",response);
});
console.log('This will be run every 2 minutes!');
return null;
});
But when I tried to deploy my function, I am getting an error
Functions deploy had errors with the following functions:
abc(us-central1)
To try redeploying those functions, run:
firebase deploy --only "functions:abc"
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
And this the error notification from log of firebase cloud function
Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'axios'
Require stack:
and also
Error: function terminated. Recommended action: inspect logs for termination reason.
Additional troubleshooting documentation can be found at
https://cloud.google.com/functions/docs/troubleshooting#logging Function cannot be
initialized.
{"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":
how to solve this?
Following the documentation, I tried declaring environment variables in the serverless.yml file under provider:
provider:
cfLogs: true
name: aws
runtime: nodejs4.3
stage: dev
region: eu-west-1
profile: serverless-admin
environmnent:
IS_REMOTE: ${file(./config.yml):IS_REMOTE}
REMOTE_ENV: "YES"
None of these are available to me when trying to get them using process.env.IS_REMOTE or process.env.REMOTE_ENV.
This is the log of trying to console.log them:
2017-01-01 06:22:57.777 (+02:00) undefined REMOTE_ENV: undefined
2017-01-01 06:22:57.777 (+02:00) undefined IS_REMOTE: undefined
This is inside Lambda when using serverless invoke (not locally).
Hope someone can help me figure this out, as it seems like I'm following the docs about right.
From the code, it looks like environmnent is misspelt.
This feature works fine for me. I believe that you have mistyped something.
Could you please create a new project and test the following steps? Maybe we can find what is your issue through a MCVE. Give me a feedback if this code does not work for you.
Check your Serverless version (expected: 1.4.0)
serverless --version
Create a new project
serverless create --template aws-nodejs --name test-project
Use the following serverless.yml
service: test-project
provider:
name: aws
runtime: nodejs4.3
environment:
VAR_1: foo
functions:
hello:
handler: handler.hello
Use the following handler.js
module.exports.hello = (event, context, callback) => {
console.log(process.env.VAR_1);
const response = {
statusCode: 200,
body: JSON.stringify({
message: process.env.VAR_1
}),
};
callback(null, response);
};
Deploy
serverless deploy
Test
serverless invoke --function hello
HTTP result:
{
"statusCode": 200,
"body": "{\"message\":\"foo\"}"
}
Log:
2017-01-02T20:13:58.551Z fg57ea3c-e127-11e6-bf5a-93b2958503d8 foo
I have developed a node application which I would like to have called as an AWS Lambda Application.
The application works as intended as an AWS Lambda, however my CloudWatch logs always finish with the following error: Process exited before completing request.
I wrote some code to ensure that my context.succeed() and context.fail() calls were taking place and they are. However, when ran locally, I also noted a lag between my logging of success in start.js and the command prompt appearing again, making me believe there could be some node processes still taking place once those calls have been made. Could that be causing the error, and if so what is a good way to triage and resolve the issue?
The relevant code is below:
lambda-handle.js
import log from './log';
import database from './database';
import User from './database/models/user';
export function handle(event, context) {
log.info('CS Blogs Feed Aggregator Started');
database.sync()
.then(() =>
User.findAll({
attributes: ['id', 'blogFeedURI']
}))
.then(users => {
users.forEach(user => {
log.info({ user }, 'User loaded from database');
});
})
.then(() => {
// context.done() called so AWS knows function completed successfully
context.succeed();
})
.catch(error => {
context.fail(error);
});
}
start.js (used to test context.succeed/fail being called)
// This function invokes the AWS Lambda Handle as AWS would
// but allows you to do it from your local machine for development
// or from a non-AWS server
import { handle } from './lambda-handle';
import log from './log';
handle({}, {
succeed: result => {
log.info({ result: result || 'No result returned' }, 'Process succeeded');
},
fail: error => {
log.error({ error: error || 'No error returned' }, 'Process failed');
}
});
The code is being transpiled by babel before being deployed. However, I suspect there is more of a logic issue so I have shown you the original source code.
If any more information is required the repository is available here: https://github.com/csblogs/feed-downloader/tree/fix/lambda-implementation-details
Thanks
I am pretty sure this is caused by at least 1 native module dependency in bunyan(dtrace-provider). Native modules need to be built/installed on the system that they will run on. So in the case of Lambda you need to run npm install on a linux ec2 instance or possibly vagrant to get the right version of dtrace-provider built.
See:
Cross-compile node module with native bindings with node-gyp
https://aws.amazon.com/blogs/compute/nodejs-packages-in-lambda/ (scroll to Native Modules)
You could probably just remove Bunyan to verify it works and then go down the ec2/vagrant compile route if that fixes it.