-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.ts
169 lines (150 loc) · 4.31 KB
/
server.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import {
type IncomingMessage,
type Server,
type ServerResponse,
createServer as createServer_,
} from 'node:http'
import type { AddressInfo } from 'node:net'
import httpProxy from 'http-proxy'
import { type DefinePoolParameters, definePool } from './pool.js'
import { extractPath } from './utils.js'
const { createProxyServer } = httpProxy
export type CreateServerParameters = DefinePoolParameters<number> &
(
| {
/** Host to run the server on. */
host?: string | undefined
/** Port to run the server on. */
port: number
}
| {
host?: undefined
port?: undefined
}
)
export type CreateServerReturnType = Omit<
Server<typeof IncomingMessage, typeof ServerResponse>,
'address'
> & {
address(): AddressInfo | null
start(): Promise<() => Promise<void>>
stop(): Promise<void>
}
/**
* Creates a server that manages a pool of instances via a proxy.
*
* @example
* ```
* import { createServer } from 'prool'
* import { anvil } from 'prool/instances'
*
* const server = createServer({
* instance: anvil(),
* })
*
* const server = await server.start()
* // Instances accessible at:
* // "http://localhost:8545/1"
* // "http://localhost:8545/2"
* // "http://localhost:8545/3"
* // "http://localhost:8545/n"
* // "http://localhost:8545/n/start"
* // "http://localhost:8545/n/stop"
* // "http://localhost:8545/n/restart"
* // "http://localhost:8545/healthcheck"
* ```
*/
export function createServer(
parameters: CreateServerParameters,
): CreateServerReturnType {
const { host = '::', instance, limit, port } = parameters
const pool = definePool({ instance, limit })
const proxy = createProxyServer({
ignorePath: true,
ws: true,
})
const server = createServer_(async (request, response) => {
try {
const url = request.url
if (!url) {
response.end()
return
}
const { id, path } = extractPath(url)
if (typeof id === 'number') {
if (path === '/') {
const { host, port } = pool.get(id) || (await pool.start(id))
return proxy.web(request, response, {
target: `http://${host}:${port}`,
})
}
if (path === '/start') {
const { host, port } = await pool.start(id)
return done(response, 200, { host, port })
}
if (path === '/stop') {
await pool.stop(id)
return done(response, 200)
}
if (path === '/restart') {
await pool.restart(id)
return done(response, 200)
}
if (path === '/messages') {
const messages = pool.get(id)?.messages.get() || []
return done(response, 200, messages)
}
}
if (path === '/healthcheck') return done(response, 200)
return done(response, 404)
} catch (error) {
return done(response, 400, { message: (error as Error).message })
}
})
proxy.on('proxyReq', (proxyReq, req) => {
;(req as any)._proxyReq = proxyReq
})
proxy.on('error', (err, req) => {
if (req.socket.destroyed && (err as any).code === 'ECONNRESET') {
;(req as any)._proxyReq.abort()
}
})
server.on('upgrade', async (request, socket, head) => {
const url = request.url
if (!url) {
socket.destroy(new Error('Unsupported request'))
return
}
const { id, path } = extractPath(url)
if (typeof id === 'number' && path === '/') {
const { host, port } = pool.get(id) || (await pool.start(id))
proxy.ws(request, socket, head, {
target: `ws://${host}:${port}`,
})
return
}
socket.destroy(new Error('Unsupported request'))
return
})
return Object.assign(server as any, {
start() {
return new Promise<() => Promise<void>>((resolve) => {
if (port) server.listen(port, host, () => resolve(this.stop))
else server.listen(() => resolve(this.stop))
})
},
async stop() {
await Promise.allSettled([
new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
),
pool.destroyAll(),
])
},
})
}
function done(res: ServerResponse, statusCode: number, json?: unknown) {
return res
.writeHead(statusCode, { 'Content-Type': 'application/json' })
.end(json ? JSON.stringify(json) : undefined)
}