help icon indicating copy to clipboard operation
help copied to clipboard

Heavy Function Traffic and asynch

Open debdansoph opened this issue 8 years ago • 3 comments

  • 9.10.1:
  • linux:
  • runtime:

My Issue/Question is: The Global value is only to show I understand each value will be different. This function will work(in principle) - if, however, this function was getting 'hit' 100+ times per second, due to the nature of the enforced varying 'timeouts' waiting for the query result, what is to stop the values within the function being changed as queries overlap - or even before they overlap - a second incoming function call may change values A-D before the preceding fuction calls query is complete. JS in the browser is less likely to encounter this as it is not usually contacting/writing to databases/files and any 'timeouts' would be self injected. I could also pass my values through a timeout, wheras it appears I can not pass any values into the result function of the sql query. A pointer for understanding and best practice please.

var globalValue = 0;

var commence = function(req, res, conn) {
    // conn/connection is from a pool
    try{
        var data = req.body;
        globalValue++;
        var valueA = data.A;
        var valueB = data.B;
        var valueC = data.C;
        var valueD = data.D;
        var sql;
        // block of code working out a query
        // query may vary considerably
        // meaning query times could very well be different

        conn.query(sql, function (err, result) {
            if (err) { return queryErrorCallback(err) }
            try{
                // block of code working the result

                valueA += queryOutcomeA;
                valueB += queryOutcomeB;
                valueC += queryOutcomeC;
                if (queryOutcomeD) {
                    valueD += queryOutcomeD;
                }
                var returnObj = {
                    vA: valueA,
                    vB: valueB,
                    vC: valueC,
                    vD: valueD,
                    vG: globalValue
                }
                res.end(returnObj);
            }
            catch(err){
                catchErrorCallback(err)
            }
        });
    } catch (err) {
        catchErrorCallback(err)
    }
}

module.exports = {
    start: commence
}

debdansoph avatar May 31 '18 08:05 debdansoph

If you are concerned about the cluttered access of the data by multiple concurrent calls into the methods, that is not the case, those variables are safe. Here is the proof:

#cat 1305.js

var h = require('http')
let id = 0
var s = h.createServer(function foo(q, r) {
  const time = process.hrtime()
  const x = Math.round((Math.random() * 432423)) % 431
  let y = 0
  setTimeout(function bar() {
    y = x - 10
    setTimeout(function zen() {
      const res  = {start: x, end: y}
      r.end(JSON.stringify(res))
    }, Math.round((Math.random() * 13343)) % 1432)
  }, Math.round((Math.random() * 32433)) % 8907)
})
s.listen(12000, () => {
  for(let i=0;i<100;i++) {
    h.get('http://localhost:12000', (m) => {
      m.on('data', (d) => {
        console.log(d.toString())
      })
    })
  }
})

#node 1305.js

{"start":108,"end":98}
{"start":137,"end":127}
{"start":203,"end":193}
{"start":11,"end":1}
{"start":127,"end":117}
{"start":50,"end":40}
{"start":290,"end":280}
{"start":430,"end":420}
{"start":295,"end":285}
{"start":297,"end":287}
{"start":157,"end":147}
{"start":360,"end":350}
{"start":296,"end":286}
{"start":254,"end":244}
{"start":361,"end":351}

As you can see, the values that are computed by different functions at arbitrary delays, are able to keep the data integrity between the concurrent calls.

Here functions foo, bar and zen all are closure functions, and upon their creation, a snap shot of the outer function (the environment in which they operate) is created and isolated for the closure functions own access. When a new client request arrives, a new closure is created and fresh set of data elements created / computed.

  • data integrity becomes problematic if function commence is a closure, and is re-entered from many requests, and have an outer environment that has data elements - those are vulnerable.

  • data integrity becomes problematics if the inner functions bar and zen are re-enterable other than through foo - in that case, those calls manipulate foo's data.

In summary, inner functions that are escaped outside and called from many places are only problematic, this case is not.

Hope this helps!

gireeshpunathil avatar Jun 01 '18 09:06 gireeshpunathil

Thank You - I suspected/hoped there was such a mechanism but was the one thing in all my internet research I could not pinpoint information on. Essentially then the JS engine or Node and how it works has this covered I think. Again - Thank You.

debdansoph avatar Jun 01 '18 12:06 debdansoph

@debdansoph - you are right - though there are vast amount of documentation available handy, associating them for a specific scenario at hand becomes a difficult job, as those docs generally drive their content from the lexical context, not from the usage pattern or application context. For most part of above discussion, this link will provide the base information, and additional details, through the connected links.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Closing this as answered.

gireeshpunathil avatar Jun 01 '18 12:06 gireeshpunathil