|
| 1 | +'use strict'; |
| 2 | +constcommon=require('../common'); |
| 3 | +constCountdown=require('../common/countdown'); |
| 4 | +constassert=require('assert'); |
| 5 | +const{ AsyncLocalStorage }=require('async_hooks'); |
| 6 | +consthttp=require('http'); |
| 7 | +constcls=newAsyncLocalStorage(); |
| 8 | +constNUM_CLIENTS=10; |
| 9 | + |
| 10 | +// Run multiple clients that receive data from a server |
| 11 | +// in multiple chunks, in a single non-closure function. |
| 12 | +// Use the AsyncLocalStorage (ALS) APIs to maintain the context |
| 13 | +// and data download. Make sure that individual clients |
| 14 | +// receive their respective data, with no conflicts. |
| 15 | + |
| 16 | +// Set up a server that sends large buffers of data, filled |
| 17 | +// with cardinal numbers, increasing per request |
| 18 | +letindex=0; |
| 19 | +constserver=http.createServer((q,r)=>{ |
| 20 | +// Send a large chunk as response, otherwise the data |
| 21 | +// may be sent in a single chunk, and the callback in the |
| 22 | +// client may be called only once, defeating the purpose of test |
| 23 | +r.end((index++%10).toString().repeat(1024*1024)); |
| 24 | +}); |
| 25 | + |
| 26 | +constcountdown=newCountdown(NUM_CLIENTS,()=>{ |
| 27 | +server.close(); |
| 28 | +}); |
| 29 | + |
| 30 | +server.listen(0,common.mustCall(()=>{ |
| 31 | +for(leti=0;i<NUM_CLIENTS;i++){ |
| 32 | +cls.run(newMap(),common.mustCall(()=>{ |
| 33 | +constoptions={port: server.address().port}; |
| 34 | +constreq=http.get(options,common.mustCall((res)=>{ |
| 35 | +conststore=cls.getStore(); |
| 36 | +store.set('data',''); |
| 37 | + |
| 38 | +// Make ondata and onend non-closure |
| 39 | +// functions and fully dependent on ALS |
| 40 | +res.setEncoding('utf8'); |
| 41 | +res.on('data',ondata); |
| 42 | +res.on('end',common.mustCall(onend)); |
| 43 | +})); |
| 44 | +req.end(); |
| 45 | +})); |
| 46 | +} |
| 47 | +})); |
| 48 | + |
| 49 | +// Accumulate the current data chunk with the store data |
| 50 | +functionondata(d){ |
| 51 | +conststore=cls.getStore(); |
| 52 | +assert.notStrictEqual(store,undefined); |
| 53 | +letchunk=store.get('data'); |
| 54 | +chunk+=d; |
| 55 | +store.set('data',chunk); |
| 56 | +} |
| 57 | + |
| 58 | +// Retrieve the store data, and test for homogeneity |
| 59 | +functiononend(){ |
| 60 | +conststore=cls.getStore(); |
| 61 | +assert.notStrictEqual(store,undefined); |
| 62 | +constdata=store.get('data'); |
| 63 | +assert.strictEqual(data,data[0].repeat(data.length)); |
| 64 | +countdown.dec(); |
| 65 | +} |
0 commit comments