summaryrefslogtreecommitdiff
path: root/test/parallel/test-diagnostics-channel-http-server-start.js
blob: 9a8136d4cc5839c79a2467c338d311791fd40eb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use strict';

const common = require('../common');
const { AsyncLocalStorage } = require('async_hooks');
const dc = require('diagnostics_channel');
const assert = require('assert');
const http = require('http');

const incomingStartChannel = dc.channel('http.server.request.start');
const outgoingFinishChannel = dc.channel('http.server.response.finish');

const als = new AsyncLocalStorage();
let context;

// Bind requests to an AsyncLocalStorage context
incomingStartChannel.subscribe(common.mustCall((message) => {
  als.enterWith(message);
  context = message;
}));

// When the request ends, verify the context has been maintained
// and that the messages contain the expected data
outgoingFinishChannel.subscribe(common.mustCall((message) => {
  const data = {
    request,
    response,
    server,
    socket: request.socket
  };

  // Context is maintained
  compare(als.getStore(), context);

  compare(context, data);
  compare(message, data);
}));

let request;
let response;

const server = http.createServer(common.mustCall((req, res) => {
  request = req;
  response = res;

  setTimeout(() => {
    res.end('done');
  }, 1);
}));

server.listen(() => {
  const { port } = server.address();
  http.get(`http://localhost:${port}`, (res) => {
    res.resume();
    res.on('end', () => {
      server.close();
    });
  });
});

function compare(a, b) {
  assert.strictEqual(a.request, b.request);
  assert.strictEqual(a.response, b.response);
  assert.strictEqual(a.socket, b.socket);
  assert.strictEqual(a.server, b.server);
}