Firebase cloud function error: Maximum call size stack size exceeded - firebase

I've made firebase cloud function which adds the claim to a user that he or she has paid (set paid to true for user):
const admin = require("firebase-admin");
exports.addPaidClaim = functions.https.onCall(async (data, context) => {
// add custom claim (paid)
return admin.auth().setCustomUserClaims(data.uid, {
paid: true,
}).then(() => {
return {
message: `Succes! ${data.email} has paid for the course`,
};
}).catch((err) => {
return err;
});
});
However, when I'm running this function: I'm receiving the following error: "Unhandled Rejection (RangeError): Maximum call stack size exceeded". I really don't understand why this is happening. Does somebody see what could cause what's getting recalled which in turn causes the function to never end?

Asynchronous operations need to return a promise as stated in the documentation. Therefore, Cloud Functions is trying to serialize the data contained by promise returned by transaction, then send it in JSON format to the client. I believe your setCustomClaims does not send any object to consider it as an answer to the promise to finish the process so it keeps in a waiting loop that throws the Range Error.
To avoid this error I can think of two different options:
Add a paid parameter to be able to send a JSON response (and remove the setCustomUserClaim if it there isn’t any need to change the user access control because they are not designed to store additional data) .
Insert a promise that resolves and sends any needed information to the client. Something like:
return new Promise(function(resolve, reject) {
request({
url: URL,
method: "POST",
json: true,
body: queryJSON //A json variable I've built previously
}, function (error, response, body) {
if (error) {
reject(error);
}
else {
resolve(body)
}
});
});

Related

Trigger Email Firebase Extension on modified Document

How do i trigger the sending of an email when a document data is modified ?
Trigger Email only composes and sends an email based on the contents of a document written to a Cloud Firestore collection but not modified
I can’t figure this one out…
From checking the code we can see that the extension already processes all writes to the document:
export const processQueue = functions.handler.firestore.document.onWrite(
...
From looking a bit further it seems that the action the extension takes upon a write depends on the value of the delivery.state field in the document.
async function processWrite(change) {
...
const payload = change.after.data() as QueuePayload;
...
switch (payload.delivery.state) {
case "SUCCESS":
case "ERROR":
return null;
case "PROCESSING":
if (payload.delivery.leaseExpireTime.toMillis() < Date.now()) {
// Wrapping in transaction to allow for automatic retries (#48)
return admin.firestore().runTransaction((transaction) => {
transaction.update(change.after.ref, {
"delivery.state": "ERROR",
error: "Message processing lease expired.",
});
return Promise.resolve();
});
}
return null;
case "PENDING":
case "RETRY":
// Wrapping in transaction to allow for automatic retries (#48)
await admin.firestore().runTransaction((transaction) => {
transaction.update(change.after.ref, {
"delivery.state": "PROCESSING",
"delivery.leaseExpireTime": admin.firestore.Timestamp.fromMillis(
Date.now() + 60000
),
});
return Promise.resolve();
});
return deliver(payload, change.after.ref);
}
}
My guess is that if you clear that field, the extension will pick up on that change and try to mail the document again.

Am I doing Firestore Transactions correct?

I've followed the Firestore documentation with relation to transactions, and I think I have it all sorted correctly, but in testing I am noticing issues with my documents not getting updated properly sometimes. It is possible that multiple versions of the document could be submitted to the function in a very short interval, but I am only interested in only ever keeping the most recent version.
My general logic is this:
New/Updated document is sent to cloud function
Check if document already exists in Firestore, and if not, add it.
If it does exist, check that it is "newer" than the instance in firestore, if it is, update it.
Otherwise, don't do anything.
Here is the code from my function that attempts to accomplish this...I would love some feedback if this is correct/best way to do this:
const ocsFlight = req.body;
const procFlight = processOcsFlightEvent(ocsFlight);
try {
const ocsFlightRef = db.collection(collection).doc(procFlight.fltId);
const originalFlight = await ocsFlightRef.get();
if (!originalFlight.exists) {
const response = await ocsFlightRef.set(procFlight);
console.log("Record Added: ", JSON.stringify(procFlight));
res.status(201).json(response); // 201 - Created
return;
}
await db.runTransaction(async (t) => {
const doc = await t.get(ocsFlightRef);
const flightDoc = doc.data();
if (flightDoc.recordModified <= procFlight.recordModified) {
t.update(ocsFlightRef, procFlight);
console.log("Record Updated: ", JSON.stringify(procFlight));
res.status(200).json("Record Updated");
return;
}
console.log("Record isn't newer, nothing changed.");
console.log("Record:", JSON.stringify("Same Flight:", JSON.stringify(procFlight)));
res.status(200).json("Record isn't newer, nothing done.");
return;
});
} catch (error) {
console.log("Error:", JSON.stringify(error));
res.status(500).json(error.message);
}
The Bugs
First, you are trusting the value of req.body to be of the correct shape. If you don't already have type assertions that mirror your security rules for /collection/someFlightId in processOcsFlightEvent, you should add them. This is important because any database operations from the Admin SDKs will bypass your security rules.
The next bug is sending a response to your function inside the transaction. Once you send a response back the client, your function is marked inactive - resources are severely throttled and any network requests may not complete or crash. As a transaction may be retried a handful of times if a database collision is detected, you should make sure to only respond to the client once the transaction has properly completed.
You use set to write the new flight to Firestore, this can lead to trouble when working with transactions as a set operation will cancel all pending transactions at that location. If two function instances are fighting over the same flight ID, this will lead to the problem where the wrong data can be written to the database.
In your current code, you return the result of the ocsFlightRef.set() operation to the client as the body of the HTTP 201 Created response. As the result of the DocumentReference#set() is a WriteResult object, you'll need to properly serialize it if you want to return it to the client and even then, I don't think it will be useful as you don't seem to use it for the other response types. Instead, a HTTP 201 Created response normally includes where the resource was written to as the Location header with no body, but here we'll pass the path in the body. If you start using multiple database instances, including the relevant database may also be useful.
Fixing
The correct way to achieve the desired result would be to do the entire read->check->write process inside of a transaction and only once the transaction has completed, then respond to the client.
So we can send the appropriate response to the client, we can use the return value of the transaction to pass data out of it. We'll pass the type of the change we made ("created" | "updated" | "aborted") and the recordModified value of what was stored in the database. We'll return these along with the resource's path and an appropriate message.
In the case of an error, we'll return a message to show the user as message and the error's Firebase error code (if available) or general message as the error property.
// if not using express to wrangle requests, assert the correct method
if (req.method !== "POST") {
console.log(`Denied ${req.method} request`);
res.status(405) // 405 - Method Not Allowed
.set("Allow", "POST")
.end();
return;
}
const ocsFlight = req.body;
try {
// process AND type check `ocsFlight`
const procFlight = processOcsFlightEvent(ocsFlight);
const ocsFlightRef = db.collection(collection).doc(procFlight.fltId);
const { changeType, recordModified } = await db.runTransaction(async (t) => {
const flightDoc = await t.get(ocsFlightRef);
if (!flightDoc.exists) {
t.set(ocsFlightRef, procFlight);
return {
changeType: "created",
recordModified: procFlight.recordModified
};
}
// only parse the field we need rather than everything
const storedRecordModified = flightDoc.get('recordModified');
if (storedRecordModified <= procFlight.recordModified) {
t.update(ocsFlightRef, procFlight);
return {
changeType: "updated",
recordModified: procFlight.recordModified
};
}
return {
changeType: "aborted",
recordModified: storedRecordModified
};
});
switch (changeType) {
case "updated":
console.log("Record updated: ", JSON.stringify(procFlight));
res.status(200).json({ // 200 - OK
path: ocsFlightRef.path,
message: "Updated",
recordModified,
changeType
});
return;
case "created":
console.log("Record added: ", JSON.stringify(procFlight));
res.status(201).json({ // 201 - Created
path: ocsFlightRef.path,
message: "Created",
recordModified,
changeType
});
return;
case "aborted":
console.log("Outdated record discarded: ", JSON.stringify(procFlight));
res.status(200).json({ // 200 - OK
path: ocsFlightRef.path,
message: "Record isn't newer, nothing done.",
recordModified,
changeType
});
return;
default:
throw new Error("Unexpected value for 'changeType': " + changeType);
}
} catch (error) {
console.log("Error:", JSON.stringify(error));
res.status(500) // 500 - Internal Server Error
.json({
message: "Something went wrong",
// if available, prefer a Firebase error code
error: error.code || error.message
});
}
References
Cloud Firestore Transactions
Cloud Firestore Node SDK Reference
HTTP Event Cloud Functions

how to make web use firebase cloud function(express) + hosting + firestore

I'm making website on firebase.
now my website is working.
but i don't know how to read firestore data and response with the data.
router.get('/', function(req, res, next) {
admin.firestore().collection('post').get()
.then(snap => {
const data = snap.size;
console.log("size: " + data);
return res.status(200).send(data);
}).catch(err => {
console.log(err);
res.status(500).send(err);
});
});
module.exports = router;
log is work but not response.
RangeError: Invalid status code: 24
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse.writeHead (/user_code/node_modules/express-session/node_modules/on-headers/index.js:55:19)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:573:10)
at ServerResponse.end (/user_code/node_modules/express-session/index.js:354:19)
at ServerResponse.send (/user_code/node_modules/express/lib/response.js:221:10)
at admin.firestore.collection.get.then.snap (/user_code/routes/main.js:14:26)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
const data = snap.size gives you a number type variable which is the size of the collect you just queried. When you pass a number to send(), it looks like that tells Express you want to send that number as an HTTP status code to the client (and apparently it overrides what you set with status()). The API docs for send() doesn't even say that you can pass a number.
If you want to send a number as the body of the response, try converting it to a string instead:
res.status(200).send('' + data);
Or bundle it up into a JSON object for the client to parse, which is probably better.

restarting a queue of API requests if a token refresh happened

I'm having a hard time wrapping my brain around this pattern I am trying to implement so I'm hoping the stack overflow community might be able to help me work through a solution to this.
Currently I use redux-thunk along with superagent to handle calls to me API and syncing it all up with redux
An example of this might look like
export const getUser = (id) => {
return (dispatch) => {
const deferred = new Promise((resolve, reject) => {
const call = () => {
API.get(`/users/${id}`)
.then((response) => response.body)
.then((response) => {
if (response.message === 'User found') {
serializeUser(response.data).then((response) => {
resolve(response);
});
} else {
reject('not found');
}
}).catch((err) => {
handleCatch(err, dispatch).then(call).catch(reject)
});
}
call()
});
return deferred;
};
};
In the case where the server comes back with a 200 and some data I continue on with putting the data into the store and rendering to the page or whatever my application does.
In the case I receive an error I have attempted to write a function that will intercept those and determine if it should show an error on page or in the case of a 401 from our API, attempt a token refresh and then try to recall the method...
import { refreshToken } from '../actions/authentication';
export default (err, dispatch) => {
const deferred = new Promise((resolve, reject) => {
if (err.status === 401) {
dispatch(refreshToken()).then(resolve).catch(reject)
} else {
reject(err);
}
})
return deferred;
};
This works, however, I have to add this to each call, and it doesn't account for concurrent calls that should not attempt to call if there is a refresh in progress.
I've seen some things in my research on this topic that maybe redux-saga could work but I haven't been able to wrap my brain around how I might make this work
Basically, I need something like a queue that all my API requests will go into that is maybe debounced so any concurrent requests will just be pushed to the end and once a timeout ends the calls get stacked up, when the first call gets a 401 it pauses the queue until the token refresh either comes back successful, in which case it continues the queue, or with a failure, in which case it cancels all future requests from the queue and sends the user back to a login page
The thing I would be worried about here is if the first call in the stack takes a long time, I don't want the other calls to then have to wait a long time because it will increase the perceived loading time to the user
Is there a better way to handle keeping tokens refreshed?

How can I prevent "Bad request" when calling Firebase's `.onCall()` method?

I've just upgraded to using Firebase Cloud Functions v1.x. According to this answer
Callable functions are exactly the same as HTTP functions
With that in mind, I've tried to convert my pre-1.x mock-code:
export const myHttpAction = functions.https.onRequest((req, res) => {
try {
const result = await myHttpActionWorker(req.body);
return res.send({ status: 'OK' });
} catch (err) {
console.error(err);
return res.status(500).send({ status: 'Server error' });
}
});
to the following:
export const myHttpAction = functions.https.onCall(async (data, context) => {
console.log(context.auth);
try {
const result = await myHttpActionWorker(data);
return { status: 'OK' };
} catch (err) {
console.error(err);
return { status: 'Server error' };
}
});
But upon submission to my endpoint, /myHttpAction, with the same data that I used in pre-1.x, I get the following back:
{
"error": {
"status": "INVALID_ARGUMENT",
"message": "Bad Request"
}
}
I'm not sure why the request is "bad" since it's exactly the same and Callable functions are "exactly the same". Any idea what gives?
My package.json specifies "firebase-functions": "^1.0.1".
You're misunderstanding what was meant by "exactly the same" (and omitting the entire remainder of the answer!). They're the same in terms of security (as the original question was asking), because a callable function is an HTTP function, with extra stuff going on behind the scenes that managed by the callable client SDK. The answer lists out those differences. Those differences don't have any effect on security. But you can't simply swap in a callable for an HTTP function and expect everything to be the same for existing callers.
If you want to invoke a callable function without using the client SDK, you'll have to follow its protocol specification. The documentation on that is forthcoming, but you can get the basics here:
How to call Firebase Callable Functions with HTTP?

Resources