I spent the last 2 days trying to find a way to modify a virtually unlimited amount of data in my cloud function.
I am aware it’s a topic already heavily discussed but despite trying every single solution I found, I always end up with a similar scenario so I guess it’s not only the way iI treat my batches.
The goal here is to be able to scale up our activity and anticipate the growth of users so I’m running some stress tests.
I’m skipping the entire app idea because it would take a while but here is the problem :
1) I am feeding an array with the list of the desired actions for the batch :
tempFeeObject["star"]=FieldValue.increment(restartFee)
let docRefFees = db.collection(collectedFeesDb).doc(element); // log action
finalArray.push([docRefFees,tempFeeObject,"set"])
2) I try to resolve all the final arrays. In this case, for the stress test, we talk about 6006 documents.
Here is the code for it :
try
{
const batches = []
finalArray.forEach((data, i) => {
if (i % 400 === 0) {
let newBatch = db.batch();
batches.push(newBatch)
}
const batch = batches[batches.length - 1]
let tempCommit = {...data[1]}
Object.keys(tempCommit).forEach(key => {
if(data[1][key] && data[1][key].seconds && !Number.isNaN(data[1][key].seconds)){
let sec = 0
let nano = 0
if(Object.keys(data[1][key])[1].includes("nano")){
sec = parseInt(data[1][key][Object.keys(data[1][key])[0]],10)
nano = parseInt(data[1][key][Object.keys(data[1][key])[1]],10)
}else{
sec = parseInt(data[1][key][Object.keys(data[1][key])[1]],10)
nano = parseInt(data[1][key][Object.keys(data[1][key])[0]],10)
}
let milliseconds = (sec*1000)+(nano/1000000)
tempCommit[key] = admin.firestore.Timestamp.fromMillis(milliseconds)
}
});
if(data[2]==="set"){
batch.set(data[0], tempCommit, {merge: true});
}else if(data[2]==="delete"){
batch.delete(data[0]);
}
})
await Promise.all(batches.map(batch => batch.commit()))
console.log(`${finalArray.length} documents updated`)
return {
result:"success"
}
}
catch (error) {
console.log(`***ERROR: ${error}`)
return {
result:"error"
}
}
The middle part might seem confusing but it is made to recreate the timestamp (i had errors when instead of a timestamp I had the array of values instead. And I test the array to find the seconds and nanoseconds because I also had cases where my script found seconds either in the first or second position).
So my script checks each key of the committed document and recreates the timestamp if he finds one.
3) Results :
The results are my main problem :
On one side it is working since my database is being updated with the correct values.
But it is not happening the way it should.
Here are the function logs :
4:04:01.790 PM
autoStationEpochMakerTestNet
Function execution started <=== Function START
4:04:02.576 PM
autoStationEpochMakerTestNet
Auto epoch function treating : 1 actions
4:04:02.577 PM
autoStationEpochMakerTestNet
atation : Arcturian Space Station has 1 actions
4:04:02.582 PM
autoStationEpochMakerTestNet
Function execution took 791 ms. Finished with status: ok <== function END
4:04:02.682 PM
autoStationEpochMakerTestNet
list used : 1 <== But the functions called by the previous one are still printing
4:04:04.926 PM
autoStationEpochMakerTestNet
***ERROR: Error: 4 DEADLINE_EXCEEDED: Deadline exceeded
4:04:05.726 PM
autoStationEpochMakerTestNet
result : { result: 'error' }
4:04:05.726 PM
autoStationEpochMakerTestNet
Arcturian Space Station function epoch generator failed. testmode = true
4:07:02.107 PM
autoStationEpochMakerTestNet
Function execution started <== Second function Trigger START
4:07:02.156 PM
autoStationEpochMakerTestNet
6006 documents updated <== Receiving logs from what i assume is the previous function trigger
4:07:02.158 PM
autoStationEpochMakerTestNet
result : { result: 'success' }
4:07:02.210 PM
autoStationEpochMakerTestNet
Auto epoch function treating : 0 actions <== As expected there is no more action to treat since it was actually processed on the previous call
4:07:02.212 PM
autoStationEpochMakerTestNet
Function execution took 104 ms. Finished with status: ok
So my comprehension of what is happening is as follows :
The function triggers and builds the batches but is somehow instantly finished without waiting for the function or returning anything.
Meantimes there are still logs coming from the function including this one :
***ERROR: Error: 4 DEADLINE_EXCEEDED: Deadline exceeded
So I feel my batch array isn’t working as expected.
Then on the following function triggers (scheduled function, every 3 min). All the functions seem to finish to execute properly.
Once again, my database is being updated as it should be.
A few elements might be noticing:
- Some of the data being committed are timestamps which I think counts for more than 1 action ?
- In this case, one document has more than 2000 fields updated (simple int value)
- await promise.all() is new to me so it’s also one of my leads.
- I set the function ram at 2Go and timeout at 540sec.
Also here is the code for the main function (the scheduled one, which is here to dispatch actions and wait for the answer) :
Object.keys(finalObject).forEach(async (stationName) => {
if(finalObject[stationName].finalList.length>0){
let epochDbUsed = stationsEpochDb[stationName]
let resultGenerator = await generateEpochsForStation(finalObject[stationName].finalList,finalObject[stationName].actionsToRemove,actionsDb,epochDbUsed,testMode)
if(resultGenerator.result==="success"){
await db.collection(logsDb).add({
"user":"cloudFunction",
"type": `createdEpochs${stationName}`,
"station":stationName,
"testMode":testMode,
"actionQty":actionCount,
"note":`New epoch has been created on ${stationName}. testmode : ${testMode}`,
"date":FieldValue.serverTimestamp()
});
}else{
console.log(`${stationName} function epoch generator failed. testmode = ${testMode}`)
await db.collection(logsDb).add({
"user":"cloudFunction",
"type": `createdEpochs${stationName}Failure`,
"station":stationName,
"testMode":testMode,
"actionQty":actionCount,
"note":`New epoch has been created on ${stationName}. testmode : ${testMode}, FAILED`,
"date":FieldValue.serverTimestamp()
});
}
}
});
return null
I am not sure if the return null at the end could mess things up, since its a scheduled function, I’m not sure what I’m supposed to return (actually never really thought of that, and realizing as I write, I’m going to look that up after posting that 🙂 ).
Well, I think this is enough data to understand the situation, feel free to ask any more details of course.
Thanks a lot to whoever will take the time to help 🙂