Skip to content

Commit d24c5ef

Browse files
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: nodejs#32063 Refs: nodejs#32060 Refs: nodejs#32062 (comment) Co-authored-by: Gireesh Punathil <[email protected]>
1 parent de6cbd0 commit d24c5ef

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
const assert = require('assert');
5+
const { AsyncLocalStorage } = require('async_hooks');
6+
const http = require('http');
7+
const cls = new AsyncLocalStorage();
8+
const NUM_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+
let index = 0;
19+
const server = http.createServer((q, r) => {
20+
// Send a large chunk as response, otherwise the data
21+
// may be coalesced, and the callback in the client
22+
// may be called only once, defeating the purpose of test
23+
r.end((index++).toString().repeat(1024 * 1024));
24+
});
25+
26+
server.listen(0, common.mustCall(() => {
27+
for (let i = 0; i < NUM_CLIENTS; i++) {
28+
cls.run(new Map(), common.mustCall(() => {
29+
const options = { port: server.address().port };
30+
const req = http.get(options, common.mustCall((res) => {
31+
const store = cls.getStore();
32+
store.set('data', '');
33+
34+
// Make ondata and onend non-closure
35+
// functions and fully dependent on ALS
36+
res.on('data', ondata);
37+
res.on('end', onend);
38+
}));
39+
req.end();
40+
}));
41+
}
42+
}));
43+
44+
// Accumulate the instantaneous data with the store data
45+
function ondata(d) {
46+
const store = cls.getStore();
47+
assert.notStrictEqual(store, undefined);
48+
let chunk = store.get('data');
49+
chunk += d;
50+
store.set('data', chunk);
51+
}
52+
53+
// Retrieve the store data, and test for homogeneity
54+
let endCount = 0;
55+
function onend() {
56+
const store = cls.getStore();
57+
assert.notStrictEqual(store, undefined);
58+
const chunk = store.get('data');
59+
const re = new RegExp(chunk[0], 'g');
60+
assert.strictEqual(chunk.replace(re, '').length, 0);
61+
if (++endCount === NUM_CLIENTS) {
62+
server.close();
63+
}
64+
}

0 commit comments

Comments
 (0)