Repository navigation
Expand file tree
/
Copy pathcontrol-server.ts
More file actions
189 lines (181 loc) · 8.05 KB
/
Copy pathcontrol-server.ts
File metadata and controls
189 lines (181 loc) · 8.05 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { Effect, Fiber, FiberSet, Queue, Stream } from "effect"
import { SimulationProtocol } from "./protocol"
export interface Server {
readonly url: string
}
interface Request {
readonly id?: string | number | null
}
export interface SocketData {
readonly drive?: true
attachment?: Fiber.Fiber<void>
closed?: true
}
export interface Socket {
readonly data: SocketData
readonly send: (message: string) => Effect.Effect<void>
}
const maxOutboundBytes = 64 * 1024 * 1024
export function start<RequestType extends Request, Error, Services>(options: {
readonly endpoint: string
readonly label: string
readonly data: () => SocketData
readonly decode: (input: string) => Effect.Effect<RequestType, Error>
readonly handle: (socket: Socket, request: RequestType) => Effect.Effect<unknown, unknown, Services>
readonly close?: (socket: Socket) => Effect.Effect<void, never, Services>
}) {
return Effect.gen(function* () {
const messages = yield* Queue.bounded<{ readonly socket: Socket; readonly input: string }>(256)
yield* Stream.fromQueue(messages).pipe(
Stream.runForEach((message) =>
options.decode(message.input).pipe(
Effect.flatMap((request) =>
options.handle(message.socket, request).pipe(
Effect.matchEffect({
onFailure: (error) => send(message.socket, SimulationProtocol.JsonRpc.failure(request.id, error)),
onSuccess: (result) => send(message.socket, SimulationProtocol.JsonRpc.success(request.id, result)),
}),
),
),
Effect.catch((error) => send(message.socket, SimulationProtocol.JsonRpc.failure(undefined, error))),
Effect.catchCause((cause) => Effect.logWarning(`${options.label}: request failed`, cause)),
),
),
Effect.forkScoped,
)
const url = yield* Effect.try({ try: () => new URL(options.endpoint), catch: (cause) => cause })
const websocket = yield* Effect.promise(() => import("ws"))
const runPromise = yield* FiberSet.makeRuntimePromise<Services, void, never>()
const endpoint = yield* Effect.acquireRelease(
Effect.tryPromise(
() =>
new Promise<{
readonly close: () => Promise<void>
readonly url: string
}>((resolve, reject) => {
const server = new websocket.WebSocketServer({ host: url.hostname, port: Number(url.port) })
const sockets = new Map<
InstanceType<typeof websocket.WebSocket>,
{ socket: Socket; cleanup: () => Promise<void> }
>()
const report = (scope: string, cause: unknown) =>
void runPromise(Effect.logWarning(`${options.label}: ${scope} error`, cause))
const onServerError = (cause: Error) => report("server", cause)
const onStartupError = (cause: Error) => {
server.off("listening", onListening)
server.on("error", onServerError)
reject(cause)
}
const onListening = () => {
server.off("error", onStartupError)
server.on("error", onServerError)
// Port 0 asks the kernel for one; report the address it gave, as the Rust endpoint does.
const address = server.address()
const port = typeof address === "object" && address !== null ? address.port : Number(url.port)
resolve({
url: `ws://${url.hostname}:${port}`,
close: async () => {
const accepted = Array.from(sockets.entries())
accepted.forEach(([connection, record]) => {
record.socket.data.closed = true
connection.terminate()
})
await Promise.all([
new Promise<void>((resolveClose, rejectClose) => {
server.close((cause) => (cause ? rejectClose(cause) : resolveClose()))
// Bun releases the listener but does not invoke ws' close callback after an upgraded socket.
queueMicrotask(() => {
if (server.address() === null) resolveClose()
})
}),
Promise.all(accepted.map(([, record]) => record.cleanup())),
])
server.off("error", onServerError)
},
})
}
server.once("listening", onListening)
server.once("error", onStartupError)
server.on("connection", (connection) => {
let pendingBytes = 0
let outbound = Promise.resolve()
let cleanup: Promise<void> | undefined
const socket: Socket = {
data: options.data(),
send: (message) =>
Effect.tryPromise({
try: () => {
const bytes = Buffer.byteLength(message)
if (bytes > maxOutboundBytes || pendingBytes + bytes > maxOutboundBytes)
return Promise.reject(new Error(`Simulation outbound queue exceeds ${maxOutboundBytes} bytes`))
pendingBytes += bytes
const current = outbound.then(
() =>
new Promise<void>((resolveSend, rejectSend) => {
if (connection.readyState !== websocket.WebSocket.OPEN) {
rejectSend(new Error("Simulation control socket is not open"))
return
}
connection.send(message, (cause) => (cause ? rejectSend(cause) : resolveSend()))
}),
)
outbound = current.catch(() => undefined)
return current.finally(() => {
pendingBytes -= bytes
})
},
catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
}).pipe(
Effect.tapError(() =>
Effect.sync(() => {
connection.terminate()
}),
),
Effect.orDie,
),
}
const close = () => {
socket.data.closed = true
cleanup ??= runPromise(options.close?.(socket) ?? Effect.void).finally(() => sockets.delete(connection))
return cleanup
}
sockets.set(connection, { socket, cleanup: close })
connection.on("close", () => void close())
connection.on("error", (cause) => {
report("socket", cause)
connection.terminate()
})
connection.on("message", (message) => {
const input = Array.isArray(message)
? Buffer.concat(message).toString()
: message instanceof ArrayBuffer
? Buffer.from(message).toString()
: message.toString()
if (Queue.offerUnsafe(messages, { socket, input })) return
void runPromise(
socket
.send(
JSON.stringify(
SimulationProtocol.JsonRpc.failure(undefined, new Error("Simulation control queue is full")),
),
)
.pipe(
Effect.catchCause((cause) =>
Effect.logWarning(`${options.label}: queue rejection failed`, cause),
),
),
)
})
})
}),
),
({ close }) => Effect.promise(close),
)
return { url: endpoint.url } satisfies Server
})
}
function send(socket: Socket, response: SimulationProtocol.JsonRpc.Response | undefined) {
if (!response) return Effect.void
return socket.send(JSON.stringify(response))
}
export * as SimulationControlServer from "./control-server"