Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase onWrite timeout

I return transaction promise which should wait for transaction to finish before stopping the function. The transaction executes fine, but the promise seems to never resolve.

I see in the Firebase console that this function always times out after 60s.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
const db = admin.database();


export let countFollowers = functions.database.ref('followers/{followee}/{follower}').onWrite(event => {
    const followee = event.params.followee;
    let path = `posts/${followee}/cnt_foll`;
    const countRef = db.ref(path);
    let out = countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1;
        }
    });

    return out;
});

EDIT:

I solve the problem with the following "hack", I create a promise myself, because whatever .transaction is returning is not working:

return new Promise(function(resolve, reject) {
    countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (parseInt(current) || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (parseInt(current) || 0) - 1; 
        }
    }, () => resolve(null));
});
like image 950
Alex Peterson Avatar asked Mar 31 '17 23:03

Alex Peterson


People also ask

How long can a Firebase function run?

Time Limits60 minutes for HTTP functions. 10 minutes for event-driven functions.

What is the maximum execution time for a cloud function?

In Cloud Functions (2nd gen), the maximum timeout duration is 60 minutes (3600 seconds) for HTTP functions and 9 minutes (540 seconds) for event-driven functions.

How many requests can handle a single cloud function?

By default each Cloud Run container instance can receive up to 80 requests at the same time; you can increase this to a maximum of 1000.

Can I use Cloud Functions Firebase for free?

Cloud Functions includes a perpetual free tier for invocations to allow you to experiment with the platform at no charge. Note that even for free tier usage, we require a valid billing account.


1 Answers

There was a known issue with older versions of the firebase-admin SDK where Firebase Database references and snapshots couldn't be JSON serialized and thus couldn't be used in return values for Cloud Functions. This includes transaction return values since they also have snapshots.

Your hack works around the bug; you should also get the fix if you update your version of firebase-admin.

like image 76
Thomas Bouldin Avatar answered Sep 28 '22 08:09

Thomas Bouldin