1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23// Tests of multiple domains happening at once.
24
25const common = require('../common');
26const domain = require('domain');
27const http = require('http');
28
29process.on('warning', common.mustNotCall());
30
31const a = domain.create();
32a.enter(); // This will be our "root" domain
33
34a.on('error', common.mustNotCall());
35
36const server = http.createServer((req, res) => {
37  // child domain of a.
38  const b = domain.create();
39  a.add(b);
40
41  // Treat these EE objects as if they are a part of the b domain
42  // so, an 'error' event on them propagates to the domain, rather
43  // than being thrown.
44  b.add(req);
45  b.add(res);
46
47  b.on('error', common.mustCall((er) => {
48    if (res) {
49      res.writeHead(500);
50      res.end('An error occurred');
51    }
52    // res.writeHead(500), res.destroy, etc.
53    server.close();
54  }));
55
56  // XXX this bind should not be necessary.
57  // the write cb behavior in http/net should use an
58  // event so that it picks up the domain handling.
59  res.write('HELLO\n', b.bind(() => {
60    throw new Error('this kills domain B, not A');
61  }));
62
63}).listen(0, () => {
64  const c = domain.create();
65  const req = http.get({ host: 'localhost', port: server.address().port });
66
67  // Add the request to the C domain
68  c.add(req);
69
70  req.on('response', (res) => {
71    // Add the response object to the C domain
72    c.add(res);
73    res.pipe(process.stdout);
74  });
75
76  c.on('error', common.mustCall());
77});
78