Variable 'leaking' between users?

Hi,

I’ve extended the sendEmail-function like this in the /server/main.js:

Meteor.startup(() => {
    var sendEmail = _.bind(Email.send, Email);
    _.extend(Email, {
        send: function (options) {
                bolBCC = false;
                //calculate bolBCC
                //depending on bolBCC, CC the mail to other address
        }
    });
});

Yesterday, the servers where a bit busier than usual, which is good for business :slight_smile:
But something strange happend: two of th mails that where send, also got send to the BCC-address.
That is no biggy, as that is only a check for us. The prolem is: I do not understand why?..
Looking at the code, some mails are also send to a bcc-address, and others are not.
The only explanation I can come up with, is that the variable bolBCC ‘leaked’ between those users?
I do not know much (well… nothing, really) about the internal workings of NodeJS, but I would have thought this to be impossible?
I would think that the function sendMail is called every time and starts from a ‘clean slate’. (environment vars etc of course excluded).
But I cannot think of an other explanation in this case…?

Can any of you? :innocent:

Paul

Try putting let or var before bolBCC = false:

Meteor.startup(() => {
    var sendEmail = _.bind(Email.send, Email);
    _.extend(Email, {
        send: function (options) {
                let bolBCC = false;
                //calculate bolBCC
                //depending on bolBCC, CC the mail to other address
        }
    });
});

Normally you would think that because you’re resetting bolBCC to false before doing anything else that it would be ok, but you have to think asynchronously.

If anything asynchronous happens between setting bolBCC = false and that variable actually being used to create the email, then there is a chance that the Email.send function is called again for another user, overwriting the bolBCC variable with a new value, which is then picked up by the first call.

That can happen because without the let or var keyword, bolBCC is a global variable which is shared among all fibers/threads. Putting the let or var keyword creates a new bolBCC variable which is passed privately to subsequent functions (assuming the bolBCC variable is explicitly passed to functions, instead of being picked up as a global variable).

Have a read about variable scope. This is nothing unique to node.js - it’s just that with meteor/node and multiple users hitting your server at the same time, you have to remember to think asyncnronously.

1 Like

Thank you for your kind and studious explanation!
I will keep this in mind in the future. The reason that I did not run in to this before, is, I think, that 98% of my app is programmed in CoffeeScript, which is filescoped by default…

Thanks!

Paul