Unpredictable count jump in cron job, potential race condition?


#1

I am running the code below in cron job, but sometimes the count ‘jump’ and I end up with nasty incomplete logic that finishes in wrong state. Most of the time it is counting up correctly but sometimes I get extra count.

If anyone can see why please let me know thanks

async function conditionalACSStartAction(value, details) {
     if (Object.keys(value).length !== 0) {
        console.log('Count up cycle');

    var p1 = FutureTasks.findOne({userid: details.userid}).count;
        console.log('p1 is :', p1);

        if (Object.keys(getSampleSparkUserIdCount(details.userid)).length !== 0) {
            var p2 = getSampleSparkUserIdCount(value[0]._id); 

            return await Promise.all([p1,p2]) // count up
                .then(countValue => FutureTasks.upsert({userid: details.userid}, {$set: {count: (countValue[0] + countValue[1][0].count)}}, {multi: true}))
                .catch(txt => console.error('Error in Non Zero, already job :', txt));
        } else { 
            // remain as in previous state
            return await FutureTasks.upsert({userid: details.userid}, {$set: {count: p1}}, {multi: true})
                .catch(txt => console.error('Error in Zero, already job :', txt));
        }
}

}

async function getSampleSparkUserIdCount(userid) {  

    var promise = await new Promise(function (resolve, reject) {
        FutureTasks.aggregate([
           
            {
                $match: {
                    "userid": {$eq: userid},

                    $and: [

                        {start_date: {$lt: moment().startOf('minute').local().add(1, 'minutes').format("YYYY-MM-DD HH:mm:ss")}},
                        {start_date: {$gt: moment().startOf('minute').local().subtract(1, 'minutes').format("YYYY-MM-DD HH:mm:ss")}}
                    ]
                }
            },

            {
                $group: {
                    _id: "$userid", count: {$sum: 1}
                }
            }
        ], (err, db) => {
            err ? reject(err) : resolve(db);
        });
    });  
    return promise;
}

Basically I get a timing error that instead of finishing, say with 2 count, I ‘sometimes’ get 3! whenever the cron job runs…