-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsockets.js
72 lines (65 loc) · 2.12 KB
/
sockets.js
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
66
67
68
69
70
71
72
const {Future} = require("./future");
/**
* Abstracts out how to retrieve an address of a socket when being bound as a listener. The resulting socket is the
* result of the 'listen' command. For `net` and `tls` style services this is most the socket itself. For things like
* `express` this is the actual HTTP server backing the server.
*
* The address is a promise of the address in the format {host, port, family}.
*
* `stop` provides a function to terminate the service
*
* @param server the socket, http, etc which exposes a "listen" function to bind
* @param port the port to be bound to (can be 0)
* @param address the interface to bind to, if null will bind to all
* @returns {{socket: *, address: Promise<any>, stop: function}}
*/
function addressOnListen( server, port = 0, address ){
const addressFuture = new Future();
function done() {
if(socket){
socket.close();
}
}
function errorListener( problem ){
if( !addressFuture.resolved) { addressFuture.reject(problem) }
done();
}
const socket = server.listen( port, address, () => {
const addr = socket.address();
const rawHost = addr.address;
const host = (rawHost == "::") ? "localhost" : rawHost;
const result = {
host,
port: addr.port,
family: addr.family
};
addressFuture.accept(result);
socket.removeListener("error", errorListener);
});
socket.on("error", errorListener);
return {
socket,
address: addressFuture.promised,
stop: done
}
}
async function listen(context, server, port, bindToAddress){
const result = addressOnListen(server, port, bindToAddress);
result.socket.on("close", function(){
context.logger.trace("Server socket closed");
});
context.onCleanup(async () => {
context.logger.trace("Cleaning up server",{address});
//TODO: This should be merged with addressOnListen, making this state management easier
// const promiseClosed = promiseEvent(result.socket, "close");
result.stop();
// await promiseClosed;
});
const address = await result.address;
context.logger.trace("Server bound to",{address});
return address.host + ":" + address.port;
}
module.exports = {
addressOnListen,
listen
};