Skip to content

Commit fd80c21

Browse files
HarshithaKPMylesBorins
authored andcommitted
test: add new scenario for async-local storage
Add a new scenario of multiple clients sharing a single data callback function managing their response data through AsyncLocalStorage APIs Refs: #32063 Refs: #32060 Refs: #32062 (comment) Co-authored-by: Gireesh Punathil <gpunathi@in.ibm.com> PR-URL: #32082 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent d2fea9f commit fd80c21

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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

Comments
 (0)