A
A
Alexey2018-06-12 09:33:24
Node.js
Alexey, 2018-06-12 09:33:24

Consistency of a global variable with simultaneous requests to sockets?

Simplified code example, clarification of the question below it.

var SUPERGLOBALVARIABLE = {
  user228: {
    wallet: {
      RUB: 0,
      EUR: 0,
      USD: 0
    }
  },
  user303: {
    wallet: {
      RUB: 100,
      EUR: 0,
      USD: 0
    }
  }
};
io.on('connect,'function(socket) {
  //после магии с авторизацией выяснили что ид юзера 303, соответственно у коннекта будет 100 рублей на счету SUPERGLOBALVARIABLE['user' + '303'].wallet.RUB;
  //два события: один на обмен евро, другой на обмен долларов. Обменивает он всегда по 1 единице валюты и всегда по заданному глобально курсу.
  socket
  .on('exchangeEUR', () => {
    if (SUPERGLOBALVARIABLE['user' + '303'].wallet.RUB > 70)
      SUPERGLOBALVARIABLE['user' + '303'].wallet.RUB -= 70;
      SUPERGLOBALVARIABLE['user' + '303'].wallet.EUR += 1;
    };
  })
  .on('exchangeUSD', () => {
    if (SUPERGLOBALVARIABLE['user' + '303'].wallet.RUB > 65)
      SUPERGLOBALVARIABLE['user' + '303'].wallet.RUB -= 65;
      SUPERGLOBALVARIABLE['user' + '303'].wallet.USD += 1;
    };
  });
});

So here's the question, can at least theoretically happen such a situation that the user in some unknown way will be able to successfully complete both requests for 100r? Due to ddos ​​or something like that.
I hope it is clear that a simplified version of the logic and code is provided above (in practice, there are more calculations and processor loading), but there are no asynchronous operations in the events themselves, only blocking calculations themselves. It's just that the sockets themselves are an asynchronous thing (as far as I know), that's why this question.
When the server starts, it loads all the data from the database and keeps it in the RAM, that is, there are no requests to the database, in the event block either.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2018-06-12
@vshvydky

The node executes code in 1 thread, the developer is guaranteed that only 1 code is executed at 1 point in time

A
Alexander, 2018-06-14
@atcrew

Event loop
Well, in general, read what an event loop is in the implementation of nodeJS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question