|
1
|
import { Server } from "http" |
|
2
|
import { Socket } from "net" |
|
3
|
import Timeout = NodeJS.Timeout |
|
4
|
|
|
5
|
interface SocketState extends Socket { |
|
6
|
_idle: boolean |
|
7
|
_connectionId: number |
|
8
|
} |
|
9
|
|
|
10
|
export abstract class GracefulShutdownServer { |
|
11
|
public isShuttingDown: boolean |
|
12
|
public abstract shutdown(timeout?: number): Promise<void> |
|
13
|
public static create<T extends Server>( |
|
14
|
originalServer: T, |
|
15
|
waitingResponseTime: number = 200 |
|
16
|
): T & GracefulShutdownServer { |
|
17
|
let connectionId = 0 |
|
18
|
let shutdownPromise: Promise<void> |
|
19
|
|
|
20
|
const allSockets: { [id: number]: SocketState } = {} |
|
21
|
|
|
22
|
const server = originalServer as T & GracefulShutdownServer |
|
23
|
server.isShuttingDown = false |
|
24
|
server.shutdown = async (timeout: number = 0): Promise<void> => { |
|
25
|
if (server.isShuttingDown) { |
|
26
|
return shutdownPromise |
|
27
|
} |
|
28
|
|
|
29
|
server.isShuttingDown = true |
|
30
|
|
|
31
|
shutdownPromise = new Promise((ok, nok) => { |
|
32
|
let forceQuit = false |
|
33
|
let cleanInterval: Timeout |
|
34
|
|
|
35
|
try { |
|
36
|
// stop accepting new incoming connections |
|
37
|
server.close(() => { |
|
38
|
clearInterval(cleanInterval) |
|
39
|
ok() |
|
40
|
}) |
|
41
|
|
|
42
|
if (+timeout > 0) { |
|
43
|
setTimeout(() => { |
|
44
|
forceQuit = true |
|
45
|
}, timeout).unref() |
|
46
|
} |
|
47
|
|
|
48
|
cleanInterval = setInterval(() => { |
|
49
|
if (!Object.keys(allSockets).length) { |
|
50
|
clearInterval(cleanInterval) |
|
51
|
} |
|
52
|
|
|
53
|
for (const key of Object.keys(allSockets)) { |
|
54
|
const socketId = +key |
|
55
|
if (forceQuit || allSockets[socketId]._idle) { |
|
56
|
allSockets[socketId].destroy() |
|
57
|
delete allSockets[socketId] |
|
58
|
} |
|
59
|
} |
|
60
|
}, waitingResponseTime) |
|
61
|
} catch (error) { |
|
62
|
clearInterval(cleanInterval!) |
|
63
|
return nok(error) |
|
64
|
} |
|
65
|
}) |
|
66
|
|
|
67
|
return shutdownPromise |
|
68
|
} |
|
69
|
|
|
70
|
const onConnect = (originalSocket) => { |
|
71
|
connectionId++ |
|
72
|
const socket = originalSocket as SocketState |
|
73
|
socket._idle = true |
|
74
|
socket._connectionId = connectionId |
|
75
|
allSockets[connectionId] = socket |
|
76
|
|
|
77
|
socket.on("close", () => { |
|
78
|
delete allSockets[socket._connectionId] |
|
79
|
}) |
|
80
|
} |
|
81
|
|
|
82
|
server.on("connection", onConnect) |
|
83
|
server.on("secureConnection", onConnect) |
|
84
|
|
|
85
|
server.on("request", (req, res) => { |
|
86
|
const customSocket = req.socket as SocketState |
|
87
|
customSocket._idle = false |
|
88
|
|
|
89
|
res.on("finish", () => { |
|
90
|
customSocket._idle = true |
|
91
|
}) |
|
92
|
}) |
|
93
|
|
|
94
|
return server |
|
95
|
} |
|
96
|
} |