• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4const { AsyncLocalStorage } = require('async_hooks');
5const dc = require('diagnostics_channel');
6const assert = require('assert');
7const http = require('http');
8
9const incomingStartChannel = dc.channel('http.server.request.start');
10const outgoingFinishChannel = dc.channel('http.server.response.finish');
11
12const als = new AsyncLocalStorage();
13let context;
14
15// Bind requests to an AsyncLocalStorage context
16incomingStartChannel.subscribe(common.mustCall((message) => {
17  als.enterWith(message);
18  context = message;
19}));
20
21// When the request ends, verify the context has been maintained
22// and that the messages contain the expected data
23outgoingFinishChannel.subscribe(common.mustCall((message) => {
24  const data = {
25    request,
26    response,
27    server,
28    socket: request.socket
29  };
30
31  // Context is maintained
32  compare(als.getStore(), context);
33
34  compare(context, data);
35  compare(message, data);
36}));
37
38let request;
39let response;
40
41const server = http.createServer(common.mustCall((req, res) => {
42  request = req;
43  response = res;
44
45  setTimeout(() => {
46    res.end('done');
47  }, 1);
48}));
49
50server.listen(() => {
51  const { port } = server.address();
52  http.get(`http://localhost:${port}`, (res) => {
53    res.resume();
54    res.on('end', () => {
55      server.close();
56    });
57  });
58});
59
60function compare(a, b) {
61  assert.strictEqual(a.request, b.request);
62  assert.strictEqual(a.response, b.response);
63  assert.strictEqual(a.socket, b.socket);
64  assert.strictEqual(a.server, b.server);
65}
66