(runtime: RuntimeServer, socket: WebSocket, request: http.IncomingMessage, options: RuntimeNodeHttpServerOptions)
| 66 | } |
| 67 | |
| 68 | function attachSocket(runtime: RuntimeServer, socket: WebSocket, request: http.IncomingMessage, options: RuntimeNodeHttpServerOptions): void { |
| 69 | const connectionId = `node:${randomUUID()}` |
| 70 | const maxBufferedBytes = options.maxBufferedBytes ?? 16 * 1024 * 1024 |
| 71 | const heartbeatMs = options.heartbeatMs ?? 30_000 |
| 72 | let alive = true |
| 73 | let disposed = false |
| 74 | let heartbeat: ReturnType<typeof setInterval> |
| 75 | |
| 76 | const connection: RuntimeConnection = { |
| 77 | id: connectionId, |
| 78 | permissions: options.permissions, |
| 79 | metadata: { |
| 80 | clientRequestPrincipal: clientRequestPrincipalFromRequest(request), |
| 81 | }, |
| 82 | send(message) { |
| 83 | if (socket.readyState !== WebSocket.OPEN) return |
| 84 | if (socket.bufferedAmount > maxBufferedBytes) { |
| 85 | socket.close(1013, "client is too far behind") |
| 86 | runtime.notify("connection/lagged", { connectionId, bufferedAmount: socket.bufferedAmount }) |
| 87 | return |
| 88 | } |
| 89 | socket.send(JSON.stringify(message)) |
| 90 | }, |
| 91 | close() { |
| 92 | socket.close() |
| 93 | }, |
| 94 | } |
| 95 | |
| 96 | const disposeRuntimeConnection = runtime.connect(connection) |
| 97 | const disposeOnce = () => { |
| 98 | if (disposed) return |
| 99 | disposed = true |
| 100 | clearInterval(heartbeat) |
| 101 | disposeRuntimeConnection() |
| 102 | } |
| 103 | |
| 104 | heartbeat = setInterval(() => { |
| 105 | if (socket.readyState !== WebSocket.OPEN) { |
| 106 | disposeOnce() |
| 107 | return |
| 108 | } |
| 109 | if (!alive) { |
| 110 | socket.terminate() |
| 111 | disposeOnce() |
| 112 | return |
| 113 | } |
| 114 | alive = false |
| 115 | socket.ping() |
| 116 | }, heartbeatMs) |
| 117 | ;(heartbeat as { unref?: () => void }).unref?.() |
| 118 | |
| 119 | socket.on("message", (data) => { |
| 120 | void runtime.handleMessage(connection, rawText(data)) |
| 121 | }) |
| 122 | socket.on("pong", () => { |
| 123 | alive = true |
| 124 | }) |
| 125 | socket.on("close", disposeOnce) |
no test coverage detected