1'use strict';
2
3const common = require('../common');
4const assert = require('assert');
5const { executionAsyncResource, createHook } = require('async_hooks');
6const { createServer, get } = require('http');
7const sym = Symbol('cls');
8
9// Tests continuation local storage with the executionAsyncResource API
10
11assert.ok(executionAsyncResource());
12
13createHook({
14  init(asyncId, type, triggerAsyncId, resource) {
15    const cr = executionAsyncResource();
16    resource[sym] = cr[sym];
17  }
18}).enable();
19
20const server = createServer(function(req, res) {
21  executionAsyncResource()[sym] = { state: req.url };
22  setTimeout(function() {
23    const { state } = executionAsyncResource()[sym];
24    res.setHeader('content-type', 'application/json');
25    res.end(JSON.stringify({ state }));
26  }, 10);
27});
28
29function test(n) {
30  get(`http://localhost:${server.address().port}/${n}`, common.mustCall(function(res) {
31    res.setEncoding('utf8');
32
33    let body = '';
34    res.on('data', function(chunk) {
35      body += chunk;
36    });
37
38    res.on('end', common.mustCall(function() {
39      assert.deepStrictEqual(JSON.parse(body), { state: `/${n}` });
40    }));
41  }));
42}
43
44server.listen(0, common.mustCall(function() {
45  server.unref();
46  for (let i = 0; i < 10; i++) {
47    test(i);
48  }
49}));
50