Firebase Functions: Unclear "connection error" - firebase

I am getting this error every so many runs with my HTTP Firebase Cloud Function:
Function execution took ****ms, finished with status: 'connection error'
It happens inconsistently but I can't quite narrow down what the problem is. I don't believe the error is in my app as it's not showing an error printout. And my own connection with firebase while running this cloud function isn't cutting out.
Any ideas why Firebase randomly fails cloud function executions with "connection error"?

Function execution took ****ms, finished with status: 'connection error' or ECONNRESET usually happens when a function doesn’t know whether a promise resolved or not.
Every promise must be returned, as mentioned in the docs here. There is also a blog post (with helpful video!) about this.
A couple of examples of unreturned promises:
exports.someFunc = functions.database.ref('/some/path').onCreate(event => {
let db = admin.database();
// UNRETURNED PROMISE
db.ref('/some/path').remove();
return db.ref('/some/other/path').set(event.data.val());
});
exports.makeUppercase = functions.database.ref('/hello/{pushId}').onWrite(event => {
return event.data.ref.set('world').then(snap => {
// UNRETURNED PROMISE
admin.database().ref('lastwrite').set(admin.database.ServerValue.TIMESTAMP);
});
});
exports.makeUppercase = functions.database.ref('/hello/{pushId}').onWrite(event => {
// UNRETURNED PROMISE
event.data.ref.set('world').then(snap => {
return admin.database().ref('lastwrite').set(admin.database.ServerValue.TIMESTAMP);
});
});
To help catch this mistake before deploying code, check out this eslint rule.
For an in-depth look at promises, here are some helpful resources:
Mozilla docs
Ponyfoo promises deep dive
Links to the ECMA standard
Egghead.io course

Even though this question has an approved answer, you may have followed the steps in that answer and still reached a point where the error was still occurring.
In that case, we were informed by GCP that there's a known issue with Node 8 CFs and this connection error, for which the workaround is to update the node version to 10.
Related github issue: https://github.com/firebase/firebase-functions/issues/429
Specific comment: https://github.com/firebase/firebase-functions/issues/429#issuecomment-577324193

I think it might be too many simultaneous firebase database connections :/ https://groups.google.com/forum/#!topic/firebase-talk/4RjyYIDqMVQ

I faced the same issue while deploying uninstallTracking event to firebase for android device,
Turns out that the property I was trying to access was available for only some users ,
So when it couldn't find the property for those other users it gives this error
So first just check the property you are trying to access is there or not

I've been getting this on an HTTP trigger that immediately calls response.end() with no other code!
I had a very complex function that was working great then it stopped working due to this error. I tried for hours playing with my code until there was nothing left but a response.end() and still the error persisted.
I found that by deleting the trigger (deploying my triggers with the offending trigger commented out), then deploying again with the trigger uncommented seems to have fixed it.
Perhaps there is a bug that works in that gets reset when you delete the trigger in the cloud.
Hope this saves somebody some frustration.

it could be outdated libraries.
go to terminal
inside functions folder write command
npm outdated
this will show all libraries to require to be updated.
To update libraries write command
npm update
deploy cloud functions with
firebase deploy --only functions

For debugging purposes, I did the following:
response.send(someArray.length)
...which resulted in the following:
response.send(218)
...which resulted in a bodyless response, just a "status code" (namely 218) being sent. To fix this, I did:
response.send("count: " + someArray.length)

Related

Firebase: Function Triggers: A function used to work, now fails with "CANCELLED: The operation was cancelled."

I built this function months ago and has been working fine until two days ago, after updating Flutter (unrelated I presume). The function essentially reviews a users upload photo for inappropriate content before moving the documents for the public to see.
I can see the images and documents uploading correctly from app to Firestore. This then triggers the function which uses vision.ImageAnnotatorClient() to label the images ('#google-cloud/vision'). Almost immediately the function console throws this error:
onCreatePost:
Error: 1 CANCELLED: The operation was cancelled.
at Object.callErrorFromStatus (/srv/node_modules/#grpc/grpc-js/build/src/call.js:30:26)
at Http2CallStream.call.on (/srv/node_modules/#grpc/grpc-js/build/src/client.js:96:33)
at emitOne (events.js:121:20)
at Http2CallStream.emit (events.js:211:7)
at process.nextTick (/srv/node_modules/#grpc/grpc-js/build/src/call-stream.js:97:22)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)
At what level is this cancellation occuring? I don't even know where to narrow down my search to.
How did this happen? Can I expect random functions to fail in the future?
Am I taking crazy pills? Feels like i'm going crazy looking for material on this.
Edit:
I have narrowed the error down to this line in my function:
var [dataTest] = await visionClient.annotateImage(request)
visionClient being an instance of vision.ImageAnnotatorClient();
vision coming from '#google-cloud/vision'
I also noticed that these errors started appearing after an unusual unique error:
onCreatePost
Error: function crashed out of request scope Function invocation was interrupted.
Solved the issue:
I had to go into my Flutter apps functions folder, where I hold my firebase cloud functions. I then had to update 'google-cloud/vision' using the following command:
npm install --save #google-cloud/vision
I deployed the new update to firebase and everything started working again... How am I supposed to catch updates on packages like this changing and breaking my code?

Why do I get "Client is not yet ready to issue requests" - Firestore get() fails when called by Schedule function

In my Firebase project I have a functions.pubsub.schedule().onRun() that runs every 5 minutes to perform some calendar related tasks. It needs to look up in my Firestore collections and does so with a .get() query.
This has been working fine until sometime 2020-03-13 in the morning where the function started to throw
2020-03-13 09:36:02.326 CET scheduledHooks 1042277797598294
Error: INTERNAL ERROR: Client is not yet ready to issue requests.
at Firestore.get projectId [as projectId] (/srv/functions/node_modules/#google-cloud/firestore/build/src/index.js:401:19)
at Query.toProto (/srv/functions/node_modules/#google-cloud/firestore/build/src/reference.js:1556:42) at Query._get (/srv/functions/node_modules/#google-cloud/firestore/build/src/reference.js:1466:30)
at Query.get (/srv/functions/node_modules/#google-cloud/firestore/build/src/reference.js:1457:21)
at FirebaseActivitiesCollection.<anonymous> (/srv/functions/lib/collections/activities/FirebaseActivitiesCollection.js:32:40)
at Generator.next (<anonymous>) at /srv/functions/lib/collections/activities/FirebaseActivitiesCollection.js:8:71
at new Promise (<anonymous>) at __awaiter (/srv/functions/lib/collections/activities/FirebaseActivitiesCollection.js:4:12)
at FirebaseActivitiesCollection.getActivitiesByInterval (/srv/functions/lib/collections/activities/FirebaseActivitiesCollection.js:27:16)
I can't track that I have changed anything, could it be that Firebase made some changes that I should be aware of or am I missing an obvious clue in this error message?
My other Cloud Functions and the Firebase JavaScript SDK still work fine.
Extra info: The same code works on my other environment where I have not deployed. This of course led me to search for changes in the deployed code, but I can't find any!?
It seems by the error, that the project was not connected and initialized correctly. As per the official API here, this error occurs when:
Returns the Project ID for this Firestore instance. Validates that
initializeIfNeeded() was called before.
I would recommend you to check that. In case you are still facing, I would say for you to contact the Firebase Free Support. Since you mentioned that it was working until yesterday morning, it might be some change on their side.
Hope this helps!
This turned out to be a very simple matter of initialization of Firebase:
Before I had:
// Initialize firebase
admin.initializeApp(functions.config().firebase)
..And it worked fine until it didn't anymore.
Now I have:
// Initialize firebase
admin.initializeApp()
... And it works again
Got the same error while running some jest tests involving firebase. Problem was that I didn't have GOOGLE_APPLICATION_CREDENTIALS environment variable set.
Since I was running them locally on my machine, exporting this variable in terminal before running the tests was sufficient for my case:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials/file.json

Flutter Crashlytics log caught exception

Looking for some clarification as to how one can log caught exceptions using flutter's firebase_crashlytics package.
If I understand correctly (and from running some sample code) Crashlytics.instance.log('text'); will only add logs to the next crash report, rather than send off a non-fatal issue itself.
I'm looking for functionality which is equivalent to Crashlytics.logException(e); on Android, e.g.
try {
throwException();
} catch (e) {
Crashlytics.logException(e);
}
which allows you to log caught exceptions so they appear as non-fatal issues in the Crashlytics dashboard.
Is this currently possible with flutter's firebase_crashlytics package?
Is calling Crashlytics.instance.recordError('text', StackTrace.current) the way to achieve this for now?
Many thanks!
Short answer, yes.
Crashlytics.instance.recordError() is the equivalent of Crashlytics.logException()
If you dig into the Flutter firebase_crashlytics source code, you can actually see what Android APIs are involved.
Flutter’s recordError() invokes the method Crashlytics#onError in the Android library.
And tracing Crashlytics#onError, you’ll see that it goes to Crashlytics.logException(exception);
Additional note, you’ll also notice why Crashlytics.instance.log() ”will only add logs to the next crash report”. These logs are added to a ListQueue<String> _logs which is then packaged into the next call of recordError()
A snippet of Flutter’s invocation of Crashlytics.logException():
_recordError(...) {
...
final String result = await channel
.invokeMethod<String>('Crashlytics#onError', <String, dynamic>{
'exception': "${exception.toString()}",
'context': '$context',
'information': _information,
'stackTraceElements': stackTraceElements,
'logs': _logs.toList(),
'keys': _prepareKeys(),
});
}
And some reference notes for Crashlytics.logException():
To reduce your users’ network traffic, Crashlytics batches logged
exceptions together and sends them the next time the app launches.
For any individual app session, only the most recent 8 logged
exceptions are stored.
To add to the accepted answer, Crashlytics.instance.recordError() has now been deprecated for the new method FirebaseCrashlytics.instance.recordError(exception, stack).
BONUS TIP:
I had this problem where all the logged exceptions are grouped under the same issue in Crashlytics dashboard. These might be different crashes of the same or different code components. Due to this, I had to manually go through each instance of the crash to verify.
From my own testing, I found out the grouping is based on the top-most line in the stack trace you passed into the method above. Luckily, Dart has an easy way to get the current stack trace using StackTrace.current.
So to properly group the issues: get the current stack trace at the time of the exception and pass it in FirebaseCrashlytics.instance.recordError(exception, stack).
Hope this helps someone out there, I looked everywhere on the internet for a similar issue but can't find any.

FIREBASE WARNING: Invalid query string segment - Warning when deploying simple Firebase Cloud function

This morning I started noticing a large amount of "FIREBASE WARNING: Invalid query string segment" errors in my functions log. In an attempt to figure out what was going on I ended up making various changes to function and deploying all my cloud functions several times.
While doing this I noticed that I was getting the error on a function that:
Does not have a Firebase Query in it.
Has not been invoked in months (it's a test function).
This leads me to believe that a change was made Firebase Cloud Functions recently that may be sporadically generating this error on deploy and/or execution of cloud functions regardless of whether the function has anything to do with real time database queries. Has anybody else noticed this error or have any insight into why it is occurring?
Relevant part of my cloud index.js file is as follows (should be enough to replicate the issue):
const cors = require('cors')({origin: true});
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebaseRef = admin.database().ref();
const firestoreRef = admin.firestore();
exports.testCloudFunctions = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const params = request.query;
console.log(params)
response.status(200).send({success: true, message: "Test Successful", params: params});
});
});
After talking with Firebase support, I learned this bug was introduced in the npm dependency #firebase/database: 0.1.10. You will have this dependency if you also have the latest firebase-admin dependency.
The warning
shouldn't have any impact on the function's overall processing.
If you want to remove the warning, you can force the npm dependency of #firebase/database: 0.1.9. I tested this adjustment and the warning was removed from my Firebase Console Logs.
The support agent also stated the fix has been made, but not released, so I would expect #firebase/database: 0.1.11+ to not experience this bug.
Looks like a recently introduced bug which will hopefully be fixed soon.
We having the same problem today. Maybe some maintenance in the platform. Maybe some Google dev will soon say something about this.
It seems they are having issues with notification.
You can check for the status here: https://status.firebase.google.com/
I am new to Firebase today.
The code snippet I generated for the Firebase db connection had this firebase.js :
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
This is generating the message : 'FIREBASE WARNING: Invalid query string segment:', but is also returning the data.
If I use a different version of firebase.js, either .../4.8.0/... or .../4.9.0/... , no error/warning message is generated.
I am running Google Chrome on Windows 10.
Update: It's officially a bug and you can ignore it until they release a fix in the next update or add version of #firebase/database: 0.1.9 to dependencies if you don't want to wait.
Seems like an internal error or change. Also getting this firebase warning and my code was working fine yesterday using '' syntax as well. However my function still works. Looks like they're doing some heavy dev work on it as its in beta and issues are coming up now and then.
Wait for fix or report here:
https://firebase.google.com/support/contact/bugs-features/
Status here (fixes usually take time to appear on here):
https://status.firebase.google.com/
Copy of 48830081 and possibly 48832566

Firebase React Native Functions seemingly not executing

I have been using one machine to develop and recently had to switch over to another. I have been going crazy all day because I thought the code was broken (worked on one machine) but then I realized, for some reason anything firebase related will not run. Such as the example code, just seemingly will not execute at all.
Just fyi I am using react native. I read that firebase just recently started supporting it, so I figured there might be some problems. I did the npm install and all that..
This block just simply auth the user. I have used it before and know it works. But for some reason just simply will not execute.
console.log("Start")
firebaseObject.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function() {
console.log("Sign In, Go to login")
}.bind(this), function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
console.log("end")
if I run this, it will print "Start" and "end" but not run that signInWithEmailandPassword
I've been struggling with the same problem for a week...
I have tried running Firebase in redux-thunks as well as in Redux Sagas, besides trying it directly in a component.
Have you had any luck? It seems Firebase itself is working in on itself (I can make refs), but all async calls just hang there forever, no resolve, no errors either.

Resources