(options: RuntimeNodeHttpServerOptions = {})
| 134 | } |
| 135 | |
| 136 | export async function serveRuntimeNodeHttp(options: RuntimeNodeHttpServerOptions = {}): Promise<RuntimeNodeHttpServer> { |
| 137 | const host = options.host ?? "127.0.0.1" |
| 138 | const port = options.port ?? 0 |
| 139 | const path = options.path ?? "/v1/runtime" |
| 140 | const runtime = |
| 141 | options.runtime ?? |
| 142 | createRuntimeNodeServer({ |
| 143 | serverName: "runtime-node", |
| 144 | ...options.runtimeOptions, |
| 145 | }) |
| 146 | const httpServer = http.createServer((_request, response) => { |
| 147 | response.writeHead(404) |
| 148 | response.end("not found") |
| 149 | }) |
| 150 | const socketServer = new WebSocketServer({ noServer: true }) |
| 151 | const httpSockets = new Set<Socket>() |
| 152 | |
| 153 | httpServer.on("connection", (socket) => { |
| 154 | httpSockets.add(socket) |
| 155 | socket.once("close", () => httpSockets.delete(socket)) |
| 156 | }) |
| 157 | |
| 158 | httpServer.on("upgrade", (request, socket, head) => { |
| 159 | const url = new URL(request.url ?? "/", `http://${host}`) |
| 160 | if (url.pathname !== path) { |
| 161 | socket.destroy() |
| 162 | return |
| 163 | } |
| 164 | |
| 165 | if (!isAuthorized(request, { host, token: options.token, allowUnauthenticatedLoopback: options.allowUnauthenticatedLoopback ?? true })) { |
| 166 | socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n") |
| 167 | socket.destroy() |
| 168 | return |
| 169 | } |
| 170 | |
| 171 | socketServer.handleUpgrade(request, socket, head, (webSocket) => { |
| 172 | attachSocket(runtime, webSocket, request, options) |
| 173 | }) |
| 174 | }) |
| 175 | |
| 176 | await new Promise<void>((resolve, reject) => { |
| 177 | httpServer.once("error", reject) |
| 178 | httpServer.listen(port, host, () => { |
| 179 | httpServer.off("error", reject) |
| 180 | resolve() |
| 181 | }) |
| 182 | }) |
| 183 | |
| 184 | const address = httpServer.address() |
| 185 | const actualPort = typeof address === "object" && address ? address.port : port |
| 186 | return { |
| 187 | runtime, |
| 188 | httpServer, |
| 189 | url: `ws://${host}:${actualPort}${path}`, |
| 190 | async close() { |
| 191 | for (const client of socketServer.clients) client.terminate() |
| 192 | for (const socket of httpSockets) socket.destroy() |
| 193 | await new Promise<void>((resolve) => socketServer.close(() => resolve())) |
no test coverage detected