@zyro-sec/server 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/package.json +8 -8
  2. package/script/build.ts +28 -28
  3. package/script/pack.ts +5 -5
  4. package/script/workerd-probe.ts +59 -59
  5. package/src/api.ts +12 -12
  6. package/src/auth.ts +70 -70
  7. package/src/content-headers.ts +32 -32
  8. package/src/cors.ts +34 -34
  9. package/src/event-feed.ts +93 -93
  10. package/src/fetch.ts +67 -67
  11. package/src/handlers/agent.ts +23 -23
  12. package/src/handlers/artifact.ts +242 -242
  13. package/src/handlers/automation.ts +63 -63
  14. package/src/handlers/blob.ts +55 -55
  15. package/src/handlers/command.ts +8 -8
  16. package/src/handlers/config.ts +26 -26
  17. package/src/handlers/credential.ts +87 -87
  18. package/src/handlers/debug.ts +57 -57
  19. package/src/handlers/event.ts +38 -38
  20. package/src/handlers/form.ts +15 -15
  21. package/src/handlers/fs.ts +180 -180
  22. package/src/handlers/generate.ts +117 -117
  23. package/src/handlers/integration.ts +310 -310
  24. package/src/handlers/job.ts +29 -29
  25. package/src/handlers/location.ts +33 -33
  26. package/src/handlers/machine.ts +336 -336
  27. package/src/handlers/mcp.ts +160 -160
  28. package/src/handlers/media.ts +44 -44
  29. package/src/handlers/message.ts +82 -82
  30. package/src/handlers/migration.ts +13 -13
  31. package/src/handlers/model.ts +25 -25
  32. package/src/handlers/permission.ts +131 -131
  33. package/src/handlers/persistent-pty.ts +285 -285
  34. package/src/handlers/plugin.ts +97 -97
  35. package/src/handlers/project.ts +23 -23
  36. package/src/handlers/provider.ts +32 -32
  37. package/src/handlers/pty-socket.ts +47 -47
  38. package/src/handlers/pty.ts +181 -181
  39. package/src/handlers/push.ts +67 -67
  40. package/src/handlers/reference.ts +8 -8
  41. package/src/handlers/rpc.ts +31 -31
  42. package/src/handlers/server.ts +58 -58
  43. package/src/handlers/session-error.ts +47 -47
  44. package/src/handlers/session.ts +722 -722
  45. package/src/handlers/shell.ts +72 -72
  46. package/src/handlers/skill.ts +34 -34
  47. package/src/handlers/usage.ts +23 -23
  48. package/src/handlers/vcs.ts +104 -104
  49. package/src/handlers/voice.ts +50 -50
  50. package/src/handlers/websearch.ts +50 -50
  51. package/src/handlers/worktree.ts +60 -60
  52. package/src/handlers.ts +69 -69
  53. package/src/location.ts +86 -86
  54. package/src/media-uri.ts +13 -13
  55. package/src/middleware/authorization.ts +111 -111
  56. package/src/middleware/defect-response.ts +39 -39
  57. package/src/middleware/form-location.ts +44 -44
  58. package/src/middleware/schema-error.ts +49 -49
  59. package/src/middleware/session-location.ts +30 -30
  60. package/src/options.ts +61 -61
  61. package/src/pairing.ts +36 -36
  62. package/src/process.ts +274 -274
  63. package/src/range.ts +16 -16
  64. package/src/request-site.ts +36 -36
  65. package/src/request-tracing.ts +9 -9
  66. package/src/routes.ts +261 -261
  67. package/src/server-info.ts +41 -41
  68. package/src/service-status.ts +30 -30
  69. package/src/workerd.ts +184 -184
  70. package/test/fixture/mcp-starts.cjs +20 -20
  71. package/test/fixture/routes.ts +37 -37
  72. package/test/fixture/server.ts +20 -20
  73. package/test/fixture/worktree-delegate/index.ts +13 -13
  74. package/test/fixture/worktree-plugin/index.ts +47 -47
  75. package/tsconfig.build.json +15 -15
  76. package/tsconfig.json +11 -11
  77. package/test/artifact.test.ts +0 -224
  78. package/test/auth.test.ts +0 -24
  79. package/test/automation.test.ts +0 -315
  80. package/test/client-mcp.test.ts +0 -369
  81. package/test/codemode-api.test.ts +0 -88
  82. package/test/config.test.ts +0 -104
  83. package/test/cors.test.ts +0 -24
  84. package/test/defect-response.test.ts +0 -83
  85. package/test/event-feed.test.ts +0 -201
  86. package/test/fetch-option.test.ts +0 -104
  87. package/test/fetch.test.ts +0 -698
  88. package/test/flag-channel.test.ts +0 -126
  89. package/test/fs.test.ts +0 -439
  90. package/test/generate.test.ts +0 -132
  91. package/test/handler-policy.test.ts +0 -43
  92. package/test/heap-dump.test.ts +0 -137
  93. package/test/integration-policy.test.ts +0 -93
  94. package/test/job.test.ts +0 -186
  95. package/test/machine-iroh.test.ts +0 -259
  96. package/test/machine-link.test.ts +0 -1234
  97. package/test/machine-routes.test.ts +0 -198
  98. package/test/media.test.ts +0 -343
  99. package/test/message.test.ts +0 -105
  100. package/test/model.test.ts +0 -62
  101. package/test/options.test.ts +0 -42
  102. package/test/permission-saved.test.ts +0 -73
  103. package/test/persistent-pty.test.ts +0 -1007
  104. package/test/process.test.ts +0 -261
  105. package/test/provider.test.ts +0 -88
  106. package/test/pty-socket.property.test.ts +0 -240
  107. package/test/pty-socket.test.ts +0 -89
  108. package/test/pty-transport.test.ts +0 -200
  109. package/test/push-routes.test.ts +0 -157
  110. package/test/request-site.test.ts +0 -71
  111. package/test/request-tracing.test.ts +0 -87
  112. package/test/rpc-handler-errors.test.ts +0 -76
  113. package/test/schema-error.test.ts +0 -68
  114. package/test/service-status.test.ts +0 -34
  115. package/test/session-admit-location.test.ts +0 -92
  116. package/test/session-create.test.ts +0 -65
  117. package/test/session-diff.test.ts +0 -100
  118. package/test/session-form.test.ts +0 -50
  119. package/test/session-import.test.ts +0 -152
  120. package/test/session-instances.test.ts +0 -335
  121. package/test/session-unarchive.test.ts +0 -73
  122. package/test/session-update.test.ts +0 -66
  123. package/test/skill.test.ts +0 -57
  124. package/test/sse-failure.test.ts +0 -71
  125. package/test/usage.test.ts +0 -88
  126. package/test/vcs.test.ts +0 -356
  127. package/test/video-generate.test.ts +0 -131
  128. package/test/voice.test.ts +0 -170
  129. package/test/workerd.test.ts +0 -227
  130. package/test/worktree.test.ts +0 -333
@@ -1,1234 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { NodeHttpServer } from "@effect/platform-node"
3
- import { NodeWS } from "@effect/platform-node-shared"
4
- import { Environment } from "@zyro-sec/core/environment/index"
5
- import { Frames } from "@zyro-sec/core/machine/frames"
6
- import { Identity } from "@zyro-sec/core/machine/identity"
7
- import { Join } from "@zyro-sec/core/machine/join"
8
- import { Link } from "@zyro-sec/core/machine/link"
9
- import { Machines } from "@zyro-sec/core/machine/machines"
10
- import { MACHINE_LINK_PATH } from "@zyro-sec/protocol/groups/machine"
11
- import { Global } from "@zyro-sec/util/global"
12
- import {
13
- Cause,
14
- Clock,
15
- Context,
16
- Deferred,
17
- Duration,
18
- Effect,
19
- Exit,
20
- Fiber,
21
- Layer,
22
- Logger,
23
- Option,
24
- Queue,
25
- References,
26
- Scope,
27
- Stream,
28
- } from "effect"
29
- import type { NonEmptyReadonlyArray } from "effect/Array"
30
- import { HttpRouter, HttpServer, type HttpServerRequest, type HttpServerResponse } from "effect/http"
31
- import { ChildProcess, ChildProcessSpawner } from "effect/process"
32
- import { Socket } from "effect/socket"
33
- import { TestClock } from "effect/testing"
34
- import { randomBytes } from "node:crypto"
35
- import { once } from "node:events"
36
- import { createServer, type IncomingMessage } from "node:http"
37
- import { connect } from "node:net"
38
- import { makeWorker } from "../../core/test/fixture/machine-worker"
39
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
40
- import { it } from "../../core/test/lib/effect"
41
- import { carrier, keepalive, type Transport, upgrade, Watch } from "../src/handlers/machine"
42
- import { ServerProcess } from "../src/process"
43
- import { createEmbeddedRoutes, createRoutes } from "../src/routes"
44
-
45
- // The endpoint a machine's link lands on, over real sockets: the fake worker from core's tests dials it with
46
- // `Link.connect` over a WebSocket, and the home is the server's own routes with the real Machines, Identity and
47
- // database layers.
48
- //
49
- // A test that moves time (`it.effect`) runs the server on the test clock, where a wait of the endpoint ends only when
50
- // the test moves the clock past it. A wait begins some turns after what set it off, and one the clock was moved before
51
- // would be left behind, never to end. So a test moves the clock only once it has what the home sent or did on its way
52
- // into the wait, in the same run of the same fiber: the ping before each interval, the close before the time to answer
53
- // it. Where the home does nothing a test can see, `waits` counts the wait itself. Every other wait a test can reach is
54
- // a limit on something real that the test waits for instead, and never has to end.
55
- //
56
- // A test that moves no time runs on the real clock (`it.live`).
57
-
58
- const authorization = `Basic ${btoa("opencode:secret")}`
59
- /** The close every connection the home ends carries. */
60
- const CLOSED = { code: 1008, reason: "" }
61
- /** The close the WebSocket layer gives a message over 65,535 bytes, which it takes none of. */
62
- const TOO_BIG = { code: 1009, reason: "" }
63
- const MAX_HANDSHAKES = 32
64
- /** A path no route has, next to the link's. */
65
- const OTHER = "/api/experimental/machine/other"
66
- /** A path that is another route's, though a URL parser reads it as the link's: that route's to guard. */
67
- const BORROWED = `/api/fs/read/../..${MACHINE_LINK_PATH.slice("/api".length)}`
68
-
69
- const options = (directory: string, machines: boolean) => ({
70
- password: "secret",
71
- app: { version: "test-version" },
72
- database: { path: ":memory:" },
73
- models: { fetch: false },
74
- config: { directory, project: false, content: JSON.stringify({ experimental: { machines } }) },
75
- fs: { filewatcher: false },
76
- })
77
-
78
- /**
79
- * The server's routes on a port of their own, with the home's key and everything else it writes in a fresh directory.
80
- * As in ServerProcess, the routes are built once the server is serving, so they stop before it does. `sockets` is the
81
- * endpoint's own `ws` server once it has made one, whose clients are the connections it holds. Without `password` the
82
- * routes are the ones an embedding host serves, which ask for none, and without `upgrades` the server hands every
83
- * request over as HTTP.
84
- *
85
- * The routes run on the test's clock, through one that also counts the waits begun on it: `waits` is how many of a
86
- * length have begun in a span of a name, which is how a wait of the link is told from the server's own.
87
- */
88
- const home = Effect.fnUntraced(function* (
89
- input: { readonly machines?: boolean; readonly password?: boolean; readonly upgrades?: boolean } = {},
90
- ) {
91
- const directory = (yield* tmpdirScoped("opencode-machine-link-")).path
92
- const server = createServer()
93
- const http = yield* NodeHttpServer.make(() => server, { port: 0, host: "127.0.0.1" })
94
- yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
95
- const routes =
96
- yield* Deferred.make<
97
- Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, HttpServerRequest.HttpServerRequest | Scope.Scope>
98
- >()
99
- yield* http.serve(Effect.flatten(Deferred.await(routes))).pipe(Effect.provide(NodeHttpServer.layerHttpServices))
100
- if (input.upgrades === false) server.removeAllListeners("upgrade")
101
- const overrides = [
102
- Global.node.replace(
103
- Global.layerWith({
104
- data: directory,
105
- cache: directory,
106
- config: directory,
107
- state: directory,
108
- tmp: directory,
109
- bin: directory,
110
- log: directory,
111
- repos: directory,
112
- }),
113
- ),
114
- ]
115
- const begun: Array<{ readonly span: string | undefined; readonly millis: number }> = []
116
- const real = yield* Clock.Clock
117
- const clock: Clock.Clock = Object.assign(Object.create(real), {
118
- sleep: (duration: Duration.Duration) =>
119
- Effect.flatMap(Effect.option(Effect.currentSpan), (span) => {
120
- begun.push({ span: Option.getOrUndefined(span)?.name, millis: Duration.toMillis(duration) })
121
- return real.sleep(duration)
122
- }),
123
- })
124
- const watched: Array<NodeWS.WebSocketServer> = []
125
- const most = { sockets: 0 }
126
- const context = yield* Layer.build(
127
- (input.password === false
128
- ? createEmbeddedRoutes(options(directory, input.machines ?? true), overrides)
129
- : createRoutes(options(directory, input.machines ?? true), () => [], overrides)
130
- ).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
131
- ).pipe(
132
- Effect.provideService(Clock.Clock, clock),
133
- Effect.provideService(Watch, (sockets) => {
134
- watched.push(sockets)
135
- sockets.on("headers", () => {
136
- most.sockets = Math.max(most.sockets, sockets.clients.size + 1)
137
- })
138
- }),
139
- )
140
- yield* Deferred.succeed(routes, Context.get(context, HttpRouter.HttpRouter).asHttpEffect())
141
- const base = HttpServer.formatAddress(http.address)
142
- return {
143
- base,
144
- url: link(base),
145
- machines: Context.get(context, Machines.Service),
146
- /** How many `ws` servers the endpoint has made: none until its first link, and one from then on. */
147
- made: () => watched.length,
148
- get sockets() {
149
- return watched[0]
150
- },
151
- /** The most sockets the endpoint has held, counted each time one is about to be added. */
152
- most: () => most.sockets,
153
- waits: (span: string, length: Duration.Input) =>
154
- begun.filter((wait) => wait.span === span && wait.millis === Duration.toMillis(Duration.fromInputUnsafe(length)))
155
- .length,
156
- }
157
- })
158
-
159
- const link = (base: string) => {
160
- const url = new URL(MACHINE_LINK_PATH, base)
161
- url.protocol = "ws:"
162
- return url
163
- }
164
-
165
- /**
166
- * A WebSocket to the endpoint, as the carrier a worker dials with: Bun's own unless `open` makes another. `receive`
167
- * takes what arrived, in order, and `closed` is how the socket ended.
168
- */
169
- const dial = Effect.fnUntraced(function* (url: URL, open: () => Socket.WebSocketLike = () => new WebSocket(url)) {
170
- const messages = yield* Queue.unbounded<Uint8Array, Cause.Done>()
171
- const closed = Promise.withResolvers<{ readonly code?: number; readonly reason?: string }>()
172
- const opened = Promise.withResolvers<boolean>()
173
- const socket = yield* Effect.acquireRelease(
174
- Effect.sync(() => {
175
- const socket = Object.assign(open(), { binaryType: "arraybuffer" })
176
- socket.addEventListener("open", () => opened.resolve(true))
177
- socket.addEventListener("message", (event) => {
178
- if (event.data instanceof ArrayBuffer) Queue.offerUnsafe(messages, new Uint8Array(event.data))
179
- })
180
- socket.addEventListener("close", (event) => {
181
- Queue.endUnsafe(messages)
182
- opened.resolve(false)
183
- closed.resolve({ code: event.code, reason: event.reason })
184
- })
185
- return socket
186
- }),
187
- (socket) => Effect.sync(() => socket.close()),
188
- )
189
- return {
190
- opened: yield* Effect.promise(() => opened.promise),
191
- closed: Effect.promise(() => closed.promise),
192
- receive: Queue.take(messages).pipe(Effect.mapError(() => new Link.Closed())),
193
- send: (message: Uint8Array | string) =>
194
- Effect.sync(() => socket.send(typeof message === "string" ? message : new Uint8Array(message))),
195
- }
196
- })
197
-
198
- /** Lets the sockets move: one turn of the event loop, which no clock counts. */
199
- const turn = Effect.promise(() => new Promise((resolve) => setImmediate(resolve)))
200
-
201
- /**
202
- * Waits for the home to act on what a socket brought it, since nothing it does then is sent back. The bound is only
203
- * there to end a loop whose test has already failed, and is far more than a loaded machine needs.
204
- */
205
- const until = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
206
- const deadline = performance.now() + 30_000
207
- while (!(yield* condition)) {
208
- if (performance.now() > deadline) return yield* Effect.die(new Error("the home never got there"))
209
- yield* turn
210
- }
211
- })
212
-
213
- const online = (machines: Machines.Interface) =>
214
- Effect.map(machines.list(), (list) => list.filter((machine) => machine.online).map((machine) => machine.id))
215
-
216
- const invite = (machines: Machines.Interface, id: Environment.ID) =>
217
- machines.invite(id, { reach: [] }).pipe(Effect.map((printed) => Option.getOrThrow(Join.decode(printed))))
218
-
219
- /**
220
- * The fake worker from core's tests (test/fixture/machine-worker.ts), each of its connections a WebSocket to the
221
- * endpoint that `Link.connect` dials. `sockets` are those WebSockets, newest last.
222
- */
223
- const worker = Effect.fnUntraced(function* (
224
- url: URL,
225
- machines: Machines.Interface,
226
- dialing: Link.DialOptions,
227
- open?: () => Socket.WebSocketLike,
228
- ) {
229
- const sockets: Array<Effect.Success<ReturnType<typeof dial>>> = []
230
- const fake = yield* makeWorker({
231
- connect: (connection) =>
232
- Effect.scoped(
233
- Effect.gen(function* () {
234
- const socket = yield* dial(url, open)
235
- sockets.push(socket)
236
- const linked = yield* Link.connect(socket, dialing)
237
- linked.send(connection.hello)
238
- yield* Effect.raceFirst(
239
- Stream.runForEach(linked.messages, (message) => Effect.sync(() => connection.send(message))),
240
- Stream.runForEach(connection.messages, (message) => Effect.sync(() => linked.send(message))),
241
- )
242
- }),
243
- ),
244
- })
245
- const connected = Effect.andThen(fake.restore, until(Effect.map(online(machines), (ids) => ids.length > 0)))
246
- yield* connected
247
- return { fake, files: Environment.makeFiles(fake.files), sockets, reconnect: connected }
248
- })
249
-
250
- /**
251
- * Starts handshakes, one socket after another, until the home turns one away, which it does before the socket is a
252
- * WebSocket. Each one admitted sends a first message, has the home's second, and is left waiting on its third.
253
- */
254
- const handshakes = Effect.fnUntraced(function* (url: URL) {
255
- const admitted: Array<Effect.Success<ReturnType<typeof dial>>> = []
256
- while (admitted.length <= MAX_HANDSHAKES) {
257
- const peer = yield* dial(url)
258
- if (!peer.opened) return admitted
259
- yield* peer.send(randomBytes(32))
260
- yield* peer.receive
261
- admitted.push(peer)
262
- }
263
- return admitted
264
- })
265
-
266
- /**
267
- * How many handshakes the home has room for, found by filling it with peers that only connect. Each is then refused,
268
- * which frees its place before the peer can see that it was.
269
- */
270
- const room = Effect.fnUntraced(function* (url: URL) {
271
- const admitted: Array<Effect.Success<ReturnType<typeof dial>>> = []
272
- while (admitted.length <= MAX_HANDSHAKES) {
273
- const peer = yield* dial(url)
274
- if (!peer.opened) break
275
- admitted.push(peer)
276
- }
277
- yield* Effect.forEach(admitted, (peer) => Effect.andThen(peer.send(randomBytes(100)), peer.closed), {
278
- concurrency: "unbounded",
279
- })
280
- return admitted.length
281
- })
282
-
283
- /**
284
- * Nothing is left of the connections that ended: the endpoint holds only the `left` sockets still in use, and every
285
- * place for a handshake is free.
286
- */
287
- const idle = Effect.fnUntraced(function* (server: Effect.Success<ReturnType<typeof home>>, left = 0) {
288
- yield* until(Effect.sync(() => server.sockets.clients.size === left))
289
- expect(yield* room(server.url)).toBe(MAX_HANDSHAKES)
290
- yield* until(Effect.sync(() => server.sockets.clients.size === left))
291
- })
292
-
293
- /** One HTTP/1.1 request on a connection of its own, and the response as the server wrote it, less its date. */
294
- const exchange = (base: string, path: string, headers: Record<string, string>, method = "GET") =>
295
- Effect.promise(async () => {
296
- const url = new URL(base)
297
- const socket = connect(Number(url.port), url.hostname)
298
- const chunks: Buffer[] = []
299
- socket.on("data", (chunk) => {
300
- chunks.push(chunk)
301
- // An upgraded connection stays open, so its response ends with its head.
302
- if (Buffer.concat(chunks).toString("latin1").startsWith("HTTP/1.1 101")) socket.destroy()
303
- })
304
- socket.write(
305
- [
306
- `${method} ${path} HTTP/1.1`,
307
- `Host: ${url.host}`,
308
- ...Object.entries({ Connection: "close", ...headers }).map(([name, value]) => `${name}: ${value}`),
309
- "",
310
- "",
311
- ].join("\r\n"),
312
- )
313
- await once(socket, "close")
314
- return Buffer.concat(chunks)
315
- .toString("latin1")
316
- .replace(/^date: .*\r\n/im, "")
317
- })
318
-
319
- const websocket = {
320
- Connection: "Upgrade",
321
- Upgrade: "websocket",
322
- "Sec-WebSocket-Version": "13",
323
- "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
324
- }
325
-
326
- /** A peer that asks for the WebSocket and then says nothing more, not even in answer to a close. */
327
- const mute = Effect.fnUntraced(function* (url: URL) {
328
- const socket = yield* Effect.acquireRelease(
329
- Effect.sync(() => connect(Number(url.port), url.hostname)),
330
- (socket) => Effect.sync(() => socket.destroy()),
331
- )
332
- const switched = once(socket, "data")
333
- socket.write(
334
- [
335
- `GET ${url.pathname} HTTP/1.1`,
336
- `Host: ${url.host}`,
337
- ...Object.entries(websocket).map(([name, value]) => `${name}: ${value}`),
338
- "",
339
- "",
340
- ].join("\r\n"),
341
- )
342
- yield* Effect.promise(() => switched)
343
- return socket
344
- })
345
-
346
- /** Resolves once the socket has been pinged `count` times. */
347
- const pinged = (socket: NodeWS.WebSocket, count: number) => {
348
- const seen = { pings: 0 }
349
- const reached = Promise.withResolvers<void>()
350
- socket.on("ping", () => {
351
- if (++seen.pings === count) reached.resolve()
352
- })
353
- return reached.promise
354
- }
355
-
356
- /** A `ws` socket as the endpoint upgrades one, on a server that does nothing else, and the `ws` client at its other end. */
357
- const pair = Effect.fnUntraced(function* () {
358
- const server = createServer()
359
- const request = Promise.withResolvers<IncomingMessage>()
360
- server.once("upgrade", request.resolve)
361
- yield* Effect.acquireRelease(
362
- Effect.promise(() => once(server.listen(0, "127.0.0.1"), "listening")),
363
- () => Effect.sync(() => server.close()),
364
- )
365
- const address = server.address()
366
- if (address === null || typeof address === "string") return yield* Effect.die(new Error("the server has no port"))
367
- const client = new NodeWS.WebSocket(`ws://127.0.0.1:${address.port}`)
368
- const opened = once(client, "open")
369
- const transport = yield* upgrade(
370
- new NodeWS.WebSocketServer({ noServer: true }),
371
- yield* Effect.promise(() => request.promise),
372
- )
373
- // Dropped before the endpoint's socket is closed, whose close would wait on a client the test left paused.
374
- yield* Effect.addFinalizer(() => Effect.sync(() => client.terminate()))
375
- yield* Effect.promise(() => opened)
376
- return { client, transport }
377
- })
378
-
379
- it.live("runs a command and reads a file on a machine that joined over a WebSocket", () =>
380
- Effect.gen(function* () {
381
- const server = yield* home()
382
- const id = yield* server.machines.add("gpu")
383
- const printed = yield* invite(server.machines, id)
384
- const gpu = yield* worker(server.url, server.machines, {
385
- home: printed.home,
386
- identity: Identity.fromSeed(randomBytes(32)),
387
- secret: printed.secret,
388
- })
389
- const environment = yield* server.machines.get(id)
390
- const handle = yield* environment.spawner.spawn(ChildProcess.make("/bin/echo", ["over the link"], { cwd: "/work" }))
391
- const run = gpu.fake.runs[0]
392
- expect([run.argv, run.cwd]).toEqual([["/bin/echo", "over the link"], "/work"])
393
- yield* run.print("over the link\n")
394
- yield* run.exit(0)
395
- expect(yield* Stream.mkString(Stream.decodeText(handle.all))).toBe("over the link\n")
396
- expect(yield* handle.exitCode).toBe(ChildProcessSpawner.ExitCode(0))
397
-
398
- // 1 MiB is some twenty frames each way, more than the socket takes at once.
399
- const large = new Uint8Array(randomBytes(1024 * 1024))
400
- yield* environment.files.write("/big", large)
401
- expect((yield* gpu.files.read("/big")).bytes).toEqual(large)
402
- expect((yield* environment.files.read("/big")).bytes).toEqual(large)
403
- expect((yield* server.machines.list()).map((machine) => [machine.id, machine.online, machine.paired])).toEqual([
404
- [id, true, true],
405
- ])
406
- }),
407
- )
408
-
409
- it.live("serves a key that reconnects as the same machine, with no secret", () =>
410
- Effect.gen(function* () {
411
- const server = yield* home()
412
- const id = yield* server.machines.add("gpu")
413
- const printed = yield* invite(server.machines, id)
414
- const identity = Identity.fromSeed(randomBytes(32))
415
- const first = yield* worker(server.url, server.machines, { home: printed.home, identity, secret: printed.secret })
416
- yield* first.fake.cut
417
- yield* until(Effect.map(online(server.machines), (ids) => ids.length === 0))
418
-
419
- const second = yield* worker(server.url, server.machines, { home: printed.home, identity })
420
- expect(yield* online(server.machines)).toEqual([id])
421
- const files = (yield* server.machines.get(id)).files
422
- yield* files.write("/note", new TextEncoder().encode("after the reconnect"))
423
- expect(new TextDecoder().decode((yield* second.files.read("/note")).bytes)).toBe("after the reconnect")
424
-
425
- // The spent secret pairs no second key.
426
- const other = yield* dial(server.url)
427
- const refused = yield* Link.connect(other, {
428
- home: printed.home,
429
- identity: Identity.fromSeed(randomBytes(32)),
430
- secret: printed.secret,
431
- }).pipe(Effect.flip)
432
- expect(refused).toEqual(new Link.Refused())
433
- expect(yield* other.closed).toEqual(CLOSED)
434
- }),
435
- )
436
-
437
- it.live("closes a stranger's handshake the same way whatever it lacks, and connects no machine", () =>
438
- Effect.gen(function* () {
439
- const server = yield* home()
440
- const id = yield* server.machines.add("gpu")
441
- const printed = yield* invite(server.machines, id)
442
- const strangers: ReadonlyArray<Link.DialOptions> = [
443
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)) },
444
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)), secret: randomBytes(32) },
445
- ]
446
- for (const stranger of strangers) {
447
- const peer = yield* dial(server.url)
448
- expect(peer.opened).toBe(true)
449
- expect(yield* Link.connect(peer, stranger).pipe(Effect.flip)).toEqual(new Link.Refused())
450
- expect(yield* peer.closed).toEqual(CLOSED)
451
- }
452
- expect((yield* server.machines.list()).map((machine) => [machine.online, machine.paired])).toEqual([[false, false]])
453
- yield* idle(server)
454
- }),
455
- )
456
-
457
- /**
458
- * Requests that are not the link's upgrade though something about each says so. `path` puts the route in the request's
459
- * path, so the same request can be made of a path no route has.
460
- */
461
- const impostors: ReadonlyArray<{
462
- readonly method?: string
463
- readonly path: (route: string) => string
464
- readonly headers: Record<string, string>
465
- }> = [
466
- // The protocol is named, on a connection that does not ask to change to it.
467
- { path: (route) => route, headers: { ...websocket, Connection: "close" } },
468
- { method: "POST", path: (route) => route, headers: websocket },
469
- { method: "HEAD", path: (route) => route, headers: websocket },
470
- // Paths a URL parser reads as the route's, and the router does not.
471
- { path: (route) => `//evil.example${route}`, headers: websocket },
472
- { path: (route) => route.replace(/\/([^/]+)$/, "/x/../$1"), headers: websocket },
473
- ]
474
-
475
- it.live("takes no server password for a GET WebSocket upgrade to exactly its path, and for nothing else", () =>
476
- Effect.gen(function* () {
477
- const directory = (yield* tmpdirScoped("opencode-machine-link-")).path
478
- const started = yield* ServerProcess.start<never, never>({
479
- ...options(directory, true),
480
- hostname: "127.0.0.1",
481
- port: 0,
482
- })
483
- const base = HttpServer.formatAddress(started.address)
484
-
485
- // Not a first message of the handshake, so the home refuses it before it reads its key.
486
- const peer = yield* dial(link(base))
487
- expect(peer.opened).toBe(true)
488
- yield* peer.send(randomBytes(64))
489
- expect(yield* peer.closed).toEqual(CLOSED)
490
-
491
- const status = (path: string, headers: Record<string, string>) =>
492
- Effect.map(exchange(base, path, headers), (response) => response.split("\r\n")[0])
493
- expect(yield* status(MACHINE_LINK_PATH, websocket)).toBe("HTTP/1.1 101 Switching Protocols")
494
- // `upgrade` is one of the connection's tokens, in any case, and a query is no part of the path.
495
- expect(yield* status(MACHINE_LINK_PATH, { ...websocket, Connection: "keep-alive, UPGRADE" })).toBe(
496
- "HTTP/1.1 101 Switching Protocols",
497
- )
498
- expect(yield* status(`${MACHINE_LINK_PATH}?from=worker`, websocket)).toBe("HTTP/1.1 101 Switching Protocols")
499
- // The same request to its neighbours, and the path without the upgrade.
500
- expect(yield* status("/api/experimental/job", websocket)).toBe("HTTP/1.1 401 Unauthorized")
501
- expect(yield* status("/api/experimental/persistent-pty/pty_1/connect", websocket)).toBe("HTTP/1.1 401 Unauthorized")
502
- expect(yield* status(MACHINE_LINK_PATH, {})).toBe("HTTP/1.1 401 Unauthorized")
503
- expect(yield* status(`${MACHINE_LINK_PATH}/`, websocket)).toBe("HTTP/1.1 401 Unauthorized")
504
- expect(yield* status(MACHINE_LINK_PATH, { authorization })).toBe("HTTP/1.1 404 Not Found")
505
- expect(yield* status(BORROWED, websocket)).toBe("HTTP/1.1 401 Unauthorized")
506
- // Turned away where an unknown route is, before the routes see it: the status, the challenge and the body.
507
- expect(yield* exchange(base, MACHINE_LINK_PATH, {})).toBe(yield* exchange(base, OTHER, {}))
508
- for (const request of impostors) {
509
- const unknown = yield* exchange(base, request.path(OTHER), request.headers, request.method)
510
- expect(unknown.split("\r\n").slice(0, 2)).toEqual([
511
- "HTTP/1.1 401 Unauthorized",
512
- 'www-authenticate: Basic realm="Secure Area"',
513
- ])
514
- expect(yield* exchange(base, request.path(MACHINE_LINK_PATH), request.headers, request.method)).toBe(unknown)
515
- }
516
- }),
517
- )
518
-
519
- it.live("makes the same exception, and no wider one, where the routes are served alone", () =>
520
- Effect.gen(function* () {
521
- // As an embedding host serves them, with the server's password.
522
- const routes = yield* home()
523
- const routed = (headers: Record<string, string>) =>
524
- Effect.map(exchange(routes.base, MACHINE_LINK_PATH, headers), (response) => response.split("\r\n")[0])
525
- expect(yield* routed(websocket)).toBe("HTTP/1.1 101 Switching Protocols")
526
- expect(yield* routed({})).toBe("HTTP/1.1 401 Unauthorized")
527
- // The header alone asks for nothing, and is let past nothing.
528
- expect(yield* routed({ Upgrade: "websocket" })).toBe("HTTP/1.1 401 Unauthorized")
529
- // An upgrade that is no WebSocket handshake is answered by the WebSocket layer.
530
- expect(yield* routed({ Connection: "Upgrade", Upgrade: "websocket" })).toBe("HTTP/1.1 400 Bad Request")
531
- expect(yield* routed({ authorization })).toBe("HTTP/1.1 404 Not Found")
532
- // With the password, a request that is not the upgrade finds no route here.
533
- expect(yield* routed({ Upgrade: "websocket", authorization })).toBe("HTTP/1.1 404 Not Found")
534
- expect(new URL(BORROWED, routes.base).pathname).toBe(MACHINE_LINK_PATH)
535
- expect((yield* exchange(routes.base, BORROWED, websocket)).split("\r\n")[0]).toBe("HTTP/1.1 401 Unauthorized")
536
-
537
- // A server that upgrades nothing hands the upgrade over as any other request, and the endpoint leaves it one.
538
- const plain = yield* home({ upgrades: false })
539
- const kept = yield* exchange(plain.base, MACHINE_LINK_PATH, { ...websocket, Connection: "Upgrade, close" })
540
- expect([kept.split("\r\n")[0], plain.made()]).toEqual(["HTTP/1.1 404 Not Found", 0])
541
-
542
- // Routes that ask for no password answer everything but the upgrade as they answer a path with no route.
543
- const open = yield* home({ password: false })
544
- expect((yield* exchange(open.base, MACHINE_LINK_PATH, websocket)).split("\r\n")[0]).toBe(
545
- "HTTP/1.1 101 Switching Protocols",
546
- )
547
- for (const request of [{ path: (route: string) => route, headers: {} }, ...impostors]) {
548
- const unknown = yield* exchange(open.base, request.path(OTHER), request.headers, request.method)
549
- expect(unknown.split("\r\n")[0]).toBe("HTTP/1.1 404 Not Found")
550
- expect(yield* exchange(open.base, request.path(MACHINE_LINK_PATH), request.headers, request.method)).toBe(unknown)
551
- }
552
- }),
553
- )
554
-
555
- it.live("logs no response for a request that became a WebSocket, and still logs one it turned away", () =>
556
- Effect.gen(function* () {
557
- // The status of each line the server's own response log writes for the link's path.
558
- const logged: Array<unknown> = []
559
- const directory = (yield* tmpdirScoped("opencode-machine-link-")).path
560
- const started = yield* ServerProcess.start<never, never>({
561
- ...options(directory, true),
562
- hostname: "127.0.0.1",
563
- port: 0,
564
- }).pipe(
565
- Effect.provide(
566
- Logger.layer([
567
- Logger.make((line) => {
568
- const annotations = line.fiber.getRef(References.CurrentLogAnnotations)
569
- if (annotations["http.url"] === MACHINE_LINK_PATH) logged.push(annotations["http.status"])
570
- }),
571
- ]),
572
- ),
573
- )
574
- const base = HttpServer.formatAddress(started.address)
575
-
576
- // A link the home ends: the server sees its connection close with no response written.
577
- const refused = yield* dial(link(base))
578
- yield* refused.send(randomBytes(64))
579
- expect(yield* refused.closed).toEqual(CLOSED)
580
-
581
- // Every place held by a peer that has only connected, and the request turned away for want of one.
582
- const holding = yield* Effect.forEach(Array.from({ length: MAX_HANDSHAKES }), () => dial(link(base)))
583
- expect(holding.every((peer) => peer.opened)).toBe(true)
584
- expect((yield* exchange(base, MACHINE_LINK_PATH, websocket)).split("\r\n")[0]).toBe(
585
- "HTTP/1.1 503 Service Unavailable",
586
- )
587
- yield* until(Effect.sync(() => logged.length > 0))
588
- expect(logged).toEqual([503])
589
- }),
590
- )
591
-
592
- it.live("makes its WebSocket server for the first link, not with the routes", () =>
593
- Effect.gen(function* () {
594
- // The routes are also built where there is no Node and no such server to make, and where nothing is a link.
595
- const server = yield* home()
596
- expect(server.made()).toBe(0)
597
- yield* exchange(server.base, MACHINE_LINK_PATH, { authorization })
598
- yield* exchange(server.base, MACHINE_LINK_PATH, { Upgrade: "websocket", authorization })
599
- expect(server.made()).toBe(0)
600
- const peers = yield* Effect.forEach([1, 2, 3], () => dial(server.url), { concurrency: "unbounded" })
601
- expect([peers.every((peer) => peer.opened), server.made(), server.sockets.clients.size]).toEqual([true, 1, 3])
602
- }),
603
- )
604
-
605
- it.live("answers as an unknown route does while machines are off", () =>
606
- Effect.gen(function* () {
607
- const directory = (yield* tmpdirScoped("opencode-machine-link-")).path
608
- const started = yield* ServerProcess.start<never, never>({
609
- ...options(directory, false),
610
- hostname: "127.0.0.1",
611
- port: 0,
612
- })
613
- const base = HttpServer.formatAddress(started.address)
614
- const requests: ReadonlyArray<Record<string, string>> = [
615
- websocket,
616
- { ...websocket, authorization },
617
- {},
618
- { authorization },
619
- ]
620
- for (const headers of requests) {
621
- const unknown = yield* exchange(base, OTHER, headers)
622
- expect(unknown.split("\r\n")[0]).toBe(
623
- "authorization" in headers ? "HTTP/1.1 404 Not Found" : "HTTP/1.1 401 Unauthorized",
624
- )
625
- expect(yield* exchange(base, MACHINE_LINK_PATH, headers)).toBe(unknown)
626
- }
627
- }),
628
- )
629
-
630
- it.live("answers as an unknown route does while machines are off, where the routes are served alone", () =>
631
- Effect.gen(function* () {
632
- // As an embedding host serves them, with a password and without one.
633
- const server = yield* home({ machines: false })
634
- expect(yield* exchange(server.base, MACHINE_LINK_PATH, { ...websocket, authorization })).toBe(
635
- yield* exchange(server.base, OTHER, { ...websocket, authorization }),
636
- )
637
- const open = yield* home({ machines: false, password: false })
638
- expect(yield* exchange(open.base, MACHINE_LINK_PATH, websocket)).toBe(yield* exchange(open.base, OTHER, websocket))
639
- expect([server.made(), open.made()]).toEqual([0, 0])
640
- }),
641
- )
642
-
643
- it.live("closes a peer that sends what no link sends, leaving no handshake behind", () =>
644
- Effect.gen(function* () {
645
- const server = yield* home()
646
- const bad: ReadonlyArray<ReadonlyArray<Uint8Array | string>> = [
647
- ["a text message, not a binary one"],
648
- // The largest message the WebSocket layer lets in, which is no first message.
649
- [new Uint8Array(65_535)],
650
- [randomBytes(100)],
651
- // Shorter than any frame of a link is, and the shortest that is not.
652
- [new Uint8Array(0)],
653
- [randomBytes(15)],
654
- [randomBytes(16)],
655
- // A first message the home answers, then bytes that are no third message.
656
- [randomBytes(32), randomBytes(193)],
657
- ]
658
- for (const messages of bad) {
659
- const socket = yield* dial(server.url)
660
- yield* Effect.forEach(messages, socket.send, { discard: true })
661
- expect(yield* socket.closed).toEqual(CLOSED)
662
- }
663
- // One byte more than the WebSocket layer lets in: it closes the socket itself, and the home drops a stranger
664
- // without waiting for what it was still sending, so the close may not be what the stranger sees last.
665
- const oversized = yield* dial(server.url)
666
- yield* oversized.send(new Uint8Array(65_536))
667
- const seen = (yield* oversized.closed).code
668
- expect(seen === TOO_BIG.code || seen === 1006).toBe(true)
669
- // A place any of them had kept would be missing here.
670
- yield* idle(server)
671
-
672
- // The same after the handshake: a paired worker whose link carries garbage is cut off and its machine goes offline.
673
- const id = yield* server.machines.add("gpu")
674
- const printed = yield* invite(server.machines, id)
675
- const gpu = yield* worker(server.url, server.machines, {
676
- home: printed.home,
677
- identity: Identity.fromSeed(randomBytes(32)),
678
- secret: printed.secret,
679
- })
680
- const garbage = [
681
- { message: "a text message, not a binary one", closed: CLOSED },
682
- { message: new Uint8Array(65_536), closed: TOO_BIG },
683
- { message: randomBytes(100), closed: CLOSED },
684
- { message: randomBytes(15), closed: CLOSED },
685
- ]
686
- for (const sent of garbage) {
687
- const socket = gpu.sockets[gpu.sockets.length - 1]
688
- yield* socket.send(sent.message)
689
- expect(yield* socket.closed).toEqual(sent.closed)
690
- yield* until(Effect.map(online(server.machines), (ids) => ids.length === 0))
691
- yield* until(Effect.sync(() => server.sockets.clients.size === 0))
692
- yield* gpu.reconnect
693
- }
694
- yield* idle(server, 1)
695
- }),
696
- )
697
-
698
- it.effect("closes a peer that says nothing ten seconds after it connected", () =>
699
- Effect.gen(function* () {
700
- const server = yield* home()
701
- const silent = yield* dial(server.url)
702
- expect(silent.opened).toBe(true)
703
- // Nothing tells a peer that its ten seconds have begun.
704
- yield* until(Effect.sync(() => server.waits("Link.serve", "10 seconds") === 1))
705
- const [held] = [...server.sockets.clients]
706
- yield* TestClock.adjust("9999 millis")
707
- // It still holds one of the places.
708
- expect(held.readyState).toBe(held.OPEN)
709
- expect(yield* room(server.url)).toBe(MAX_HANDSHAKES - 1)
710
- yield* TestClock.adjust("1 millis")
711
- expect(yield* silent.closed).toEqual(CLOSED)
712
- yield* idle(server)
713
- }),
714
- )
715
-
716
- it.effect("makes no more strangers WebSockets than it has places for, and answers the rest as HTTP", () =>
717
- Effect.gen(function* () {
718
- const server = yield* home()
719
- const strangers = yield* Effect.forEach(Array.from({ length: 50 }), () => dial(server.url), {
720
- concurrency: "unbounded",
721
- })
722
- const admitted = strangers.filter((stranger) => stranger.opened)
723
- expect([admitted.length, server.sockets.clients.size]).toEqual([MAX_HANDSHAKES, MAX_HANDSHAKES])
724
- // One more is answered, with nothing in the body, and is never a WebSocket.
725
- expect(yield* exchange(server.base, MACHINE_LINK_PATH, websocket)).toBe(
726
- "HTTP/1.1 503 Service Unavailable\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n",
727
- )
728
- expect(server.sockets.clients.size).toBe(MAX_HANDSHAKES)
729
-
730
- // Places change hands: the ones holding them are refused while twice as many ask for one.
731
- const asking = yield* Effect.forkChild(
732
- Effect.forEach(
733
- Array.from({ length: 2 * MAX_HANDSHAKES }),
734
- () =>
735
- Effect.scoped(
736
- Effect.gen(function* () {
737
- const stranger = yield* dial(server.url)
738
- if (!stranger.opened) return false
739
- yield* stranger.send(randomBytes(100))
740
- yield* stranger.closed
741
- return true
742
- }),
743
- ),
744
- { concurrency: 2 * MAX_HANDSHAKES },
745
- ),
746
- { startImmediately: true },
747
- )
748
- yield* Effect.forEach(admitted, (stranger) => Effect.andThen(stranger.send(randomBytes(100)), stranger.closed), {
749
- concurrency: "unbounded",
750
- })
751
- expect((yield* Fiber.join(asking)).filter((opened) => opened).length).toBeGreaterThan(0)
752
- // Counted as each was about to be added, when the endpoint's sockets were the most they had been.
753
- expect(server.most()).toBe(MAX_HANDSHAKES)
754
-
755
- // The same for handshakes begun, which find every place free again: the one past the last is turned away with the
756
- // clock where it was, and the ones that never finish give their places back when their time is up. Each has the
757
- // home's answer to its first message, which the home sends with that time already running.
758
- const begun = yield* handshakes(server.url)
759
- expect(begun.length).toBe(MAX_HANDSHAKES)
760
- yield* TestClock.adjust("10 seconds")
761
- expect(yield* Effect.forEach(begun, (peer) => peer.closed)).toEqual(begun.map(() => CLOSED))
762
- yield* idle(server)
763
- }),
764
- )
765
-
766
- it.live("closes the socket of a machine removed while it is connected", () =>
767
- Effect.gen(function* () {
768
- const server = yield* home()
769
- const id = yield* server.machines.add("gpu")
770
- const printed = yield* invite(server.machines, id)
771
- const identity = Identity.fromSeed(randomBytes(32))
772
- const gpu = yield* worker(server.url, server.machines, { home: printed.home, identity, secret: printed.secret })
773
- yield* server.machines.remove(id)
774
- expect(yield* gpu.sockets[0].closed).toEqual(CLOSED)
775
- expect(yield* server.machines.list()).toEqual([])
776
-
777
- // Its key is gone with it.
778
- const again = yield* dial(server.url)
779
- expect(yield* Link.connect(again, { home: printed.home, identity }).pipe(Effect.flip)).toEqual(new Link.Refused())
780
- expect(yield* again.closed).toEqual(CLOSED)
781
- yield* idle(server)
782
- }),
783
- )
784
-
785
- it.live("serves a machine's second connection in place of its first", () =>
786
- Effect.gen(function* () {
787
- const server = yield* home()
788
- const id = yield* server.machines.add("gpu")
789
- const printed = yield* invite(server.machines, id)
790
- const identity = Identity.fromSeed(randomBytes(32))
791
- const first = yield* worker(server.url, server.machines, { home: printed.home, identity, secret: printed.secret })
792
- const offline = { seen: false }
793
- const watching = yield* Effect.forkChild(
794
- Effect.forever(
795
- Effect.andThen(
796
- Effect.map(online(server.machines), (ids) => {
797
- if (ids.length === 0) offline.seen = true
798
- }),
799
- turn,
800
- ),
801
- ),
802
- { startImmediately: true },
803
- )
804
- // The same worker dialing again while the home still holds its first connection, which nothing has ended.
805
- const second = yield* worker(server.url, server.machines, { home: printed.home, identity })
806
- expect(yield* first.sockets[0].closed).toEqual(CLOSED)
807
- yield* idle(server, 1)
808
- yield* Fiber.interrupt(watching)
809
- expect([offline.seen, yield* online(server.machines)]).toEqual([false, [id]])
810
-
811
- const environment = yield* server.machines.get(id)
812
- const handle = yield* environment.spawner.spawn(ChildProcess.make("/bin/echo", ["on the second"], { cwd: "/work" }))
813
- expect(first.fake.runs).toEqual([])
814
- const run = second.fake.runs[0]
815
- yield* run.print("on the second\n")
816
- yield* run.exit(0)
817
- expect(yield* Stream.mkString(Stream.decodeText(handle.all))).toBe("on the second\n")
818
- expect(yield* handle.exitCode).toBe(ChildProcessSpawner.ExitCode(0))
819
- }),
820
- )
821
-
822
- it.live("leaves no socket and no handshake behind, whichever side ends a connection and when", () =>
823
- Effect.gen(function* () {
824
- const server = yield* home()
825
- const gone = until(Effect.sync(() => server.sockets.clients.size === 0))
826
- // Before the handshake: a stranger that closes, one that vanishes, and one whose WebSocket handshake is refused.
827
- yield* Effect.scoped(Effect.asVoid(dial(server.url)))
828
- yield* gone
829
- yield* Effect.scoped(Effect.map(mute(server.url), (stranger) => stranger.destroy()))
830
- yield* gone
831
- const refused = yield* exchange(server.base, MACHINE_LINK_PATH, { Connection: "Upgrade", Upgrade: "websocket" })
832
- expect(refused.split("\r\n")[0]).toBe("HTTP/1.1 400 Bad Request")
833
- // A place any of the three had kept would be missing here.
834
- yield* idle(server)
835
-
836
- // After it: a machine that closes, and one that vanishes.
837
- const id = yield* server.machines.add("gpu")
838
- const printed = yield* invite(server.machines, id)
839
- const identity = Identity.fromSeed(randomBytes(32))
840
- const offline = until(Effect.map(online(server.machines), (ids) => ids.length === 0))
841
- const closing = yield* worker(server.url, server.machines, { home: printed.home, identity, secret: printed.secret })
842
- yield* closing.fake.cut
843
- yield* offline
844
- yield* gone
845
- const vanishing = new NodeWS.WebSocket(server.url)
846
- yield* worker(server.url, server.machines, { home: printed.home, identity }, () => vanishing)
847
- vanishing.terminate()
848
- yield* offline
849
- yield* idle(server)
850
- }),
851
- )
852
-
853
- it.effect("gives a machine five seconds to answer the close, and a stranger none", () =>
854
- Effect.gen(function* () {
855
- const server = yield* home()
856
- const stranger = yield* mute(server.url)
857
- yield* until(Effect.sync(() => server.waits("Link.serve", "10 seconds") === 1))
858
- const received: Array<Buffer> = []
859
- stranger.on("data", (chunk) => received.push(chunk))
860
- const dropped = once(stranger, "close")
861
- yield* TestClock.adjust("10 seconds")
862
- // The clock stays where the deadline was: the connection ends with the close, not after a wait for its answer.
863
- yield* Effect.promise(() => dropped)
864
- // The close frame, 1008 with no reason, and nothing after it: the route's HTTP response found no connection to
865
- // be written to.
866
- expect([...Buffer.concat(received)]).toEqual([0x88, 0x02, 0x03, 0xf0])
867
- yield* idle(server)
868
-
869
- // A machine that stops reading, so the close the home sends it when it is removed goes unanswered.
870
- const id = yield* server.machines.add("gpu")
871
- const printed = yield* invite(server.machines, id)
872
- const client = new NodeWS.WebSocket(server.url)
873
- const gpu = yield* worker(
874
- server.url,
875
- server.machines,
876
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)), secret: printed.secret },
877
- () => client,
878
- )
879
- const [linked] = [...server.sockets.clients]
880
- client.pause()
881
- yield* server.machines.remove(id)
882
- // Closing, which the home's socket is from the moment the home sends the close and begins to wait for the answer.
883
- yield* until(Effect.sync(() => linked.readyState === linked.CLOSING))
884
- yield* TestClock.adjust("4999 millis")
885
- expect([linked.readyState, server.sockets.clients.size]).toEqual([linked.CLOSING, 1])
886
- yield* TestClock.adjust("1 millis")
887
- yield* idle(server)
888
- // What the machine finds when it reads again is the close, and the end of the connection.
889
- client.resume()
890
- expect(yield* gpu.sockets[0].closed).toEqual(CLOSED)
891
- }),
892
- )
893
-
894
- it.effect("closes every link as the server begins to stop, without waiting out what it gives open connections", () =>
895
- Effect.gen(function* () {
896
- // The whole server, with a peer that has only connected. Nothing here moves the clock, so neither its ten seconds
897
- // nor the server's twenty can pass.
898
- const process = yield* Scope.fork(yield* Effect.scope)
899
- const directory = (yield* tmpdirScoped("opencode-machine-link-")).path
900
- const started = yield* ServerProcess.start<never, never>({
901
- ...options(directory, true),
902
- hostname: "127.0.0.1",
903
- port: 0,
904
- }).pipe(Scope.provide(process))
905
- const peer = yield* dial(link(HttpServer.formatAddress(started.address)))
906
- expect(peer.opened).toBe(true)
907
- yield* Scope.close(process, Exit.void)
908
- expect(yield* peer.closed).toEqual(CLOSED)
909
-
910
- // The routes, with a machine connected.
911
- const routes = yield* Scope.fork(yield* Effect.scope)
912
- const server = yield* home().pipe(Scope.provide(routes))
913
- const id = yield* server.machines.add("gpu")
914
- const printed = yield* invite(server.machines, id)
915
- const gpu = yield* worker(server.url, server.machines, {
916
- home: printed.home,
917
- identity: Identity.fromSeed(randomBytes(32)),
918
- secret: printed.secret,
919
- })
920
- yield* Scope.close(routes, Exit.void)
921
- expect(yield* gpu.sockets[0].closed).toEqual(CLOSED)
922
- expect(server.sockets.clients.size).toBe(0)
923
- }),
924
- )
925
-
926
- it.effect("stops a second after it begins to, however many peers leave the close unanswered", () =>
927
- Effect.gen(function* () {
928
- const routes = yield* Scope.fork(yield* Effect.scope)
929
- const server = yield* home().pipe(Scope.provide(routes))
930
- // A machine that has stopped reading, and strangers that never read: none of them answers a close.
931
- const id = yield* server.machines.add("gpu")
932
- const printed = yield* invite(server.machines, id)
933
- const client = new NodeWS.WebSocket(server.url)
934
- yield* worker(
935
- server.url,
936
- server.machines,
937
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)), secret: printed.secret },
938
- () => client,
939
- )
940
- client.pause()
941
- const strangers = yield* Effect.forEach(Array.from({ length: 5 }), () => mute(server.url))
942
- const closes = strangers.map((stranger) => once(stranger, "data"))
943
- const dropped = strangers.map((stranger) => once(stranger, "close"))
944
- expect(server.sockets.clients.size).toBe(6)
945
-
946
- const stopping = yield* Effect.forkChild(Scope.close(routes, Exit.void), { startImmediately: true })
947
- // Each is sent the close as the routes begin to stop, and has the one second from then.
948
- expect((yield* Effect.promise(() => Promise.all(closes))).map(([frame]) => [...frame])).toEqual(
949
- strangers.map(() => [0x88, 0x02, 0x03, 0xf0]),
950
- )
951
- yield* TestClock.adjust("999 millis")
952
- expect([stopping.pollUnsafe(), server.sockets.clients.size]).toEqual([undefined, 6])
953
- yield* TestClock.adjust("1 millis")
954
- yield* Fiber.join(stopping)
955
- yield* Effect.promise(() => Promise.all(dropped))
956
- expect(server.sockets.clients.size).toBe(0)
957
- }),
958
- )
959
-
960
- it.effect("keeps a quiet link while its pings are answered, and drops it when they are not", () =>
961
- Effect.gen(function* () {
962
- const server = yield* home()
963
- const id = yield* server.machines.add("gpu")
964
- const printed = yield* invite(server.machines, id)
965
- // This peer answers a ping when the test says so, and the test waits for the home to have the answer.
966
- const client = new NodeWS.WebSocket(server.url, { autoPong: false })
967
- const first = pinged(client, 1)
968
- const gpu = yield* worker(
969
- server.url,
970
- server.machines,
971
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)), secret: printed.secret },
972
- () => client,
973
- )
974
- yield* Effect.promise(() => first)
975
- const [linked] = [...server.sockets.clients]
976
- // Nothing else is sent on this link once it is up, so the home pings again only because the last ping was answered.
977
- for (const _ of ["second", "third", "fourth"]) {
978
- const answered = once(linked, "pong")
979
- client.pong()
980
- yield* Effect.promise(() => answered)
981
- const next = pinged(client, 1)
982
- yield* TestClock.adjust("30 seconds")
983
- yield* Effect.promise(() => next)
984
- }
985
- // The fourth goes unanswered, as every ping to a peer that is gone does.
986
- yield* TestClock.adjust("29999 millis")
987
- expect([yield* online(server.machines), server.sockets.clients.size]).toEqual([[id], 1])
988
- yield* TestClock.adjust("1 millis")
989
- // Dropped, not closed: no close frame reaches a peer that is gone.
990
- expect((yield* gpu.sockets[0].closed).code).toBe(1006)
991
- yield* until(Effect.map(online(server.machines), (ids) => ids.length === 0))
992
- yield* idle(server)
993
- }),
994
- )
995
-
996
- it.effect("keeps a link whose peer keeps sending though it answers no ping, and drops it once it is silent", () =>
997
- Effect.gen(function* () {
998
- const server = yield* home()
999
- const id = yield* server.machines.add("gpu")
1000
- const printed = yield* invite(server.machines, id)
1001
- const unanswering = new NodeWS.WebSocket(server.url, { autoPong: false })
1002
- const first = pinged(unanswering, 1)
1003
- const gpu = yield* worker(
1004
- server.url,
1005
- server.machines,
1006
- { home: printed.home, identity: Identity.fromSeed(randomBytes(32)), secret: printed.secret },
1007
- () => unanswering,
1008
- )
1009
- yield* Effect.promise(() => first)
1010
- const files = (yield* server.machines.get(id)).files
1011
- for (const minute of ["first", "second", "third"]) {
1012
- // The worker's reply is something from the peer since the last ping.
1013
- yield* files.write("/note", new TextEncoder().encode(minute))
1014
- const next = pinged(unanswering, 1)
1015
- yield* TestClock.adjust("30 seconds")
1016
- yield* Effect.promise(() => next)
1017
- }
1018
- yield* TestClock.adjust("29999 millis")
1019
- expect(yield* online(server.machines)).toEqual([id])
1020
- yield* TestClock.adjust("1 millis")
1021
- expect((yield* gpu.sockets[0].closed).code).toBe(1006)
1022
- yield* until(Effect.map(online(server.machines), (ids) => ids.length === 0))
1023
- yield* idle(server)
1024
- }),
1025
- )
1026
-
1027
- it.effect("on a real socket, returns from a send when the peer has taken it and drops a peer that takes nothing", () =>
1028
- Effect.gen(function* () {
1029
- const { client, transport } = yield* pair()
1030
- const socket = yield* Socket.fromWebSocket(Effect.succeed(transport))
1031
- const link = carrier(yield* socket.reader, transport)
1032
- const received = { bytes: 0 }
1033
- client.on("message", (data: Buffer) => {
1034
- received.bytes += data.length
1035
- })
1036
- // 64 MiB, more than the connection holds between the two: while the client reads nothing, not all of it is taken.
1037
- const frame = new Uint8Array(65_535)
1038
- const frames = Array.from({ length: 1024 }, () => frame)
1039
- const send = Effect.forkChild(Effect.forEach(frames, link.send, { discard: true }), { startImmediately: true })
1040
-
1041
- client.pause()
1042
- const held = yield* send
1043
- yield* until(Effect.sync(() => transport.bufferedAmount > 0))
1044
- expect(held.pollUnsafe()).toBeUndefined()
1045
- client.resume()
1046
- yield* Fiber.join(held)
1047
- expect(transport.bufferedAmount).toBe(0)
1048
- yield* until(Effect.sync(() => received.bytes === frames.length * frame.length))
1049
-
1050
- // A minute passes only once bytes wait in the socket behind a client that reads nothing: a send still on its way
1051
- // there is not one the peer is failing to take. A minute in which the connection took some more is not the last.
1052
- client.pause()
1053
- const stalled = yield* send
1054
- const minutes: Array<number> = []
1055
- while (transport.readyState === transport.OPEN) {
1056
- yield* until(Effect.sync(() => transport.bufferedAmount > 0))
1057
- expect(stalled.pollUnsafe()).toBeUndefined()
1058
- minutes.push(transport.bufferedAmount)
1059
- yield* TestClock.adjust("60 seconds")
1060
- }
1061
- expect(minutes.every((waiting) => waiting > 0)).toBe(true)
1062
- yield* Fiber.join(stalled)
1063
- expect(yield* link.receive.pipe(Effect.flip)).toEqual(new Link.Closed())
1064
- }),
1065
- )
1066
-
1067
- it.live("on a real socket, drops a peer on the first frame shorter than a frame can be", () =>
1068
- Effect.gen(function* () {
1069
- // What the reader would be handed, heard after the endpoint's own listener as the reader hears it.
1070
- const flooded = yield* pair()
1071
- const handed = { frames: 0 }
1072
- flooded.transport.on("message", () => {
1073
- handed.frames++
1074
- })
1075
- const closed = once(flooded.client, "close")
1076
- // Frames of no bytes never stop the reader, which counts the bytes that wait.
1077
- Array.from({ length: 2_000 }).forEach(() => flooded.client.send(new Uint8Array(0)))
1078
- yield* Effect.promise(() => closed)
1079
- yield* until(Effect.sync(() => flooded.transport.readyState === flooded.transport.CLOSED))
1080
- expect(handed.frames).toBe(1)
1081
-
1082
- // A frame of sixteen bytes is let through, and one of fifteen is the last.
1083
- const exact = yield* pair()
1084
- const lengths: Array<number> = []
1085
- exact.transport.on("message", (data: Buffer) => lengths.push(data.length))
1086
- const ended = once(exact.client, "close")
1087
- for (const length of [16, 16, 15, 16]) exact.client.send(new Uint8Array(length))
1088
- yield* Effect.promise(() => ended)
1089
- yield* until(Effect.sync(() => exact.transport.readyState === exact.transport.CLOSED))
1090
- expect(lengths).toEqual([16, 16, 15])
1091
- }),
1092
- )
1093
-
1094
- // The carrier and the keepalive on their own, over a socket the test controls: a real socket cannot be told how much to
1095
- // take or when its reading is paused. `transport` stands for the `ws` socket and takes what was sent only when the test
1096
- // says so.
1097
- const controlled = Effect.fnUntraced(function* () {
1098
- const inbox = yield* Queue.unbounded<NonEmptyReadonlyArray<Uint8Array | string>>()
1099
- const unsent: Array<{ bytes: number; readonly taken: () => void }> = []
1100
- const listeners = new Map<string, Set<() => void>>()
1101
- const state = { pings: 0, terminated: false, paused: false }
1102
- const transport: Transport = {
1103
- get bufferedAmount() {
1104
- return unsent.reduce((bytes, message) => bytes + message.bytes, 0)
1105
- },
1106
- get isPaused() {
1107
- return state.paused
1108
- },
1109
- send: (message, taken) => {
1110
- unsent.push({ bytes: message.length, taken })
1111
- },
1112
- ping: () => {
1113
- state.pings++
1114
- },
1115
- on: (event, listener) => listeners.set(event, new Set([...(listeners.get(event) ?? []), listener])),
1116
- off: (event, listener) => listeners.get(event)?.delete(listener),
1117
- terminate: () => {
1118
- state.terminated = true
1119
- },
1120
- }
1121
- return {
1122
- inbox,
1123
- transport,
1124
- state,
1125
- /** Something of this kind arrives from the peer. */
1126
- hear: (event: string) => listeners.get(event)?.forEach((listener) => listener()),
1127
- listening: () => [...listeners.values()].reduce((count, heard) => count + heard.size, 0),
1128
- /** The peer takes `bytes` of the oldest message still unsent. */
1129
- take: (bytes: number) => {
1130
- unsent[0].bytes -= bytes
1131
- if (unsent[0].bytes === 0) unsent.shift()?.taken()
1132
- },
1133
- carrier: carrier({ pull: Queue.take(inbox), upgrade: Socket.SocketUpgradeError.unsupported }, transport),
1134
- }
1135
- })
1136
-
1137
- it.live("hands over binary messages in order and ends on a text message or a flood", () =>
1138
- Effect.gen(function* () {
1139
- const socket = yield* controlled()
1140
- const largest = new Uint8Array(65_535).fill(7)
1141
- Queue.offerUnsafe(socket.inbox, [Uint8Array.of(1), largest])
1142
- Queue.offerUnsafe(socket.inbox, [Uint8Array.of(3)])
1143
- expect(yield* socket.carrier.receive).toEqual(Uint8Array.of(1))
1144
- expect(yield* socket.carrier.receive).toBe(largest)
1145
- expect(yield* socket.carrier.receive).toEqual(Uint8Array.of(3))
1146
-
1147
- const ended = yield* controlled()
1148
- Queue.offerUnsafe(ended.inbox, ["text"])
1149
- expect(yield* ended.carrier.receive.pipe(Effect.flip)).toEqual(new Link.Closed())
1150
-
1151
- // More waiting than a whole message is more than the socket should ever have let in.
1152
- const flooded = yield* controlled()
1153
- const frames = Array.from({ length: Math.ceil(Frames.MAX_MESSAGE / largest.length) }, () => largest)
1154
- Queue.offerUnsafe(flooded.inbox, [largest, ...frames])
1155
- expect(yield* flooded.carrier.receive.pipe(Effect.flip)).toEqual(new Link.Closed())
1156
- const full = yield* controlled()
1157
- Queue.offerUnsafe(full.inbox, [largest, ...frames.slice(2)])
1158
- expect(yield* full.carrier.receive).toBe(largest)
1159
-
1160
- // A read with nothing to take can be interrupted.
1161
- const reading = yield* Effect.forkChild(socket.carrier.receive, { startImmediately: true })
1162
- yield* Fiber.interrupt(reading)
1163
- }),
1164
- )
1165
-
1166
- it.effect("holds a send until the socket has taken it, and drops a socket that takes nothing for a minute", () =>
1167
- Effect.gen(function* () {
1168
- const socket = yield* controlled()
1169
- const frame = new Uint8Array(2_000)
1170
- const send = () => Effect.forkChild(socket.carrier.send(frame), { startImmediately: true })
1171
-
1172
- // Nothing more is sent while the socket still holds this one, however long a peer that is reading takes.
1173
- const first = yield* send()
1174
- yield* TestClock.adjust("59 seconds")
1175
- socket.take(1_000)
1176
- yield* TestClock.adjust("59 seconds")
1177
- expect([first.pollUnsafe(), socket.transport.bufferedAmount]).toEqual([undefined, 1_000])
1178
- socket.take(1_000)
1179
- yield* Fiber.join(first)
1180
-
1181
- // A minute in which the peer took something starts another; one in which it took nothing is the last.
1182
- const stalled = yield* send()
1183
- yield* TestClock.adjust("59 seconds")
1184
- socket.take(1)
1185
- yield* TestClock.adjust("1 seconds")
1186
- yield* TestClock.adjust("59999 millis")
1187
- expect([stalled.pollUnsafe(), socket.state.terminated]).toEqual([undefined, false])
1188
- yield* TestClock.adjust("1 millis")
1189
- yield* Fiber.join(stalled)
1190
- expect(socket.state.terminated).toBe(true)
1191
-
1192
- // A send that is waiting can be interrupted.
1193
- const waiting = yield* send()
1194
- yield* Fiber.interrupt(waiting)
1195
- }),
1196
- )
1197
-
1198
- it.effect("pings every interval and drops the socket once one passes with nothing from the peer", () =>
1199
- Effect.gen(function* () {
1200
- const socket = yield* controlled()
1201
- const fiber = yield* Effect.forkChild(keepalive(socket.transport), { startImmediately: true })
1202
- expect(socket.state.pings).toBe(1)
1203
- socket.hear("pong")
1204
- yield* TestClock.adjust("29999 millis")
1205
- expect(socket.state.pings).toBe(1)
1206
- yield* TestClock.adjust("1 millis")
1207
- expect(socket.state.pings).toBe(2)
1208
-
1209
- // Anything else from the peer counts as its answer does.
1210
- for (const event of ["message", "ping"]) {
1211
- socket.hear(event)
1212
- yield* TestClock.adjust("30 seconds")
1213
- }
1214
- expect([socket.state.pings, socket.state.terminated]).toEqual([4, false])
1215
-
1216
- // Nothing the peer sends can be seen while reading is paused, so an interval that ends paused is not held against
1217
- // it, nor is one that began paused: here reading resumes a millisecond before the interval is up, too late for
1218
- // the answer to its ping to have been read.
1219
- socket.state.paused = true
1220
- yield* TestClock.adjust("30 seconds")
1221
- expect([socket.state.pings, socket.state.terminated]).toEqual([5, false])
1222
- yield* TestClock.adjust("29999 millis")
1223
- socket.state.paused = false
1224
- yield* TestClock.adjust("1 millis")
1225
- expect([socket.state.pings, socket.state.terminated]).toEqual([6, false])
1226
-
1227
- // The interval after it was read from start to end, and is the peer's to answer.
1228
- yield* TestClock.adjust("29999 millis")
1229
- expect([socket.state.pings, socket.state.terminated]).toEqual([6, false])
1230
- yield* TestClock.adjust("1 millis")
1231
- yield* Fiber.join(fiber)
1232
- expect([socket.state.pings, socket.state.terminated, socket.listening()]).toEqual([6, true, 0])
1233
- }),
1234
- )