The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { describe, expect } from "@alchemy.run/test"; |
| 3 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 4 | import * as Alchemy from "alchemy"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Deferred from "effect/Deferred"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Exit from "effect/Exit"; |
| 9 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 10 | import * as Queue from "effect/Queue"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Schema from "effect/Schema"; |
| 13 | import { requestWorker, waitUntilStable } from "../Utils/WorkerRequest.ts"; |
| 14 | import AttachmentWorker from "./fixtures/hibernating-websocket/worker.ts"; |
| 15 | |
| 16 | class HandshakeFailed extends Data.TaggedError("HandshakeFailed")<{ readonly message: string }> {} |
| 17 | |
| 18 | const connect = Effect.fn( |
| 19 | function* (url: string) { |
| 20 | const opened = yield* Deferred.make<void, HandshakeFailed>(); |
| 21 | const closed = yield* Deferred.make<{ code: number; reason: string }>(); |
| 22 | const messages = yield* Queue.unbounded<string>(); |
| 23 | const socket = yield* Effect.acquireRelease( |
| 24 | Effect.sync(() => { |
| 25 | const socket = new WebSocket(url.replace(/^http/, "ws")); |
| 26 | socket.addEventListener("open", () => Deferred.doneUnsafe(opened, Exit.void)); |
| 27 | socket.addEventListener("error", (event) => |
| 28 | Deferred.doneUnsafe( |
| 29 | opened, |
| 30 | Exit.fail( |
| 31 | new HandshakeFailed({ message: `WebSocket handshake failed: ${event.type}` }), |
| 32 | ), |
| 33 | ), |
| 34 | ); |
| 35 | socket.addEventListener("message", (event) => |
| 36 | Queue.offerUnsafe(messages, String(event.data)), |
| 37 | ); |
| 38 | socket.addEventListener("close", (event) => |
| 39 | Deferred.doneUnsafe(closed, Exit.succeed({ code: event.code, reason: event.reason })), |
| 40 | ); |
| 41 | return socket; |
| 42 | }), |
| 43 | (socket) => Effect.sync(() => socket.close()), |
| 44 | ); |
| 45 | yield* Deferred.await(opened).pipe( |
| 46 | Effect.timeout("10 seconds"), |
| 47 | Effect.onError(() => Effect.sync(() => socket.close())), |
| 48 | ); |
| 49 | return { |
| 50 | socket, |
| 51 | send: (message: string) => Effect.sync(() => socket.send(message)), |
| 52 | receive: Queue.take(messages).pipe( |
| 53 | Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))), |
| 54 | Effect.timeout("10 seconds"), |
| 55 | ), |
| 56 | closed: Deferred.await(closed).pipe(Effect.timeout("10 seconds")), |
| 57 | }; |
| 58 | }, |
| 59 | Effect.retry({ |
| 60 | while: (error) => error._tag === "HandshakeFailed", |
| 61 | schedule: Schedule.spaced("1 second"), |
| 62 | times: 8, |
| 63 | }), |
| 64 | ); |
| 65 | |
| 66 | const Stats = Schema.Struct({ |
| 67 | boots: Schema.Number, |
| 68 | restored: Schema.Array(Schema.Number), |
| 69 | rejected: Schema.Array(Schema.String), |
| 70 | count: Schema.Number, |
| 71 | joined: Schema.String, |
| 72 | isDate: Schema.Boolean, |
| 73 | }); |
| 74 | const timestamp = "2026-01-02T03:04:05.000Z"; |
| 75 | |
| 76 | describe.concurrent.each([ |
| 77 | { dev: true, stage: `${Test.defaultStage()}-native-websocket-local` }, |
| 78 | { dev: false, stage: `${Test.defaultStage()}-native-websocket-live` }, |
| 79 | ])( |
| 80 | "Native WebSocket attachments (dev: $dev)", |
| 81 | ({ dev, stage }) => { |
| 82 | const state = dev ? Alchemy.inMemoryState() : Cloudflare.state(); |
| 83 | const Stack = Alchemy.Stack( |
| 84 | "HibernatingWebSocketStack", |
| 85 | { providers: Cloudflare.providers(), state }, |
| 86 | Effect.gen(function* () { |
| 87 | const worker = yield* AttachmentWorker; |
| 88 | return { url: worker.url.as<string>() }; |
| 89 | }), |
| 90 | ); |
| 91 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 92 | providers: Cloudflare.providers(), |
| 93 | state, |
| 94 | dev, |
| 95 | stage, |
| 96 | }); |
| 97 | const stack = beforeAll( |
| 98 | Effect.gen(function* () { |
| 99 | yield* destroy(Stack); |
| 100 | const output = yield* deploy(Stack); |
| 101 | // A new version reaches Cloudflare's hosts one at a time: require the |
| 102 | // HTTP route and a WebSocket handshake to succeed several times in a |
| 103 | // row before the tests open sockets that may land on any host. |
| 104 | yield* waitUntilStable( |
| 105 | `WebSocket worker at ${output.url}`, |
| 106 | Effect.gen(function* () { |
| 107 | const response = yield* requestWorker(HttpClientRequest.get(`${output.url}/ready`)); |
| 108 | expect(response.status).toBe(200); |
| 109 | expect(yield* response.text).toBe("ready"); |
| 110 | yield* connect(`${output.url}/socket/ready`).pipe(Effect.scoped); |
| 111 | return true; |
| 112 | }).pipe( |
| 113 | Effect.catchTag(["WorkerNotPropagated", "HandshakeFailed"], () => |
| 114 | Effect.succeed(false), |
| 115 | ), |
| 116 | ), |
| 117 | ); |
| 118 | return output; |
| 119 | }), |
| 120 | { timeout: 180_000 }, |
| 121 | ); |
| 122 | afterAll(destroy(Stack), { timeout: 30_000 }); |
| 123 | |
| 124 | const request = Effect.fn(function* (command: string) { |
| 125 | const { url } = yield* stack; |
| 126 | const connection = yield* connect(`${url}/socket/${command}`); |
| 127 | yield* connection.send(command); |
| 128 | const response = yield* connection.receive; |
| 129 | expect(connection.socket.readyState).toBe(WebSocket.OPEN); |
| 130 | yield* connection.send("codec"); |
| 131 | expect(yield* connection.receive).toEqual({ |
| 132 | encoded: { version: 1, count: "42", joined: timestamp }, |
| 133 | count: 42, |
| 134 | joined: timestamp, |
| 135 | isDate: true, |
| 136 | }); |
| 137 | return response; |
| 138 | }); |
| 139 | |
| 140 | test( |
| 141 | "encodes number and Date codecs and exposes the encoded value unchecked", |
| 142 | Effect.gen(function* () { |
| 143 | expect(yield* request("codec")).toEqual({ |
| 144 | encoded: { version: 1, count: "42", joined: timestamp }, |
| 145 | count: 42, |
| 146 | joined: timestamp, |
| 147 | isDate: true, |
| 148 | }); |
| 149 | }).pipe(Effect.scoped), |
| 150 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 151 | ); |
| 152 | |
| 153 | test( |
| 154 | "uses distinct encoding and decoding services in the caller's context", |
| 155 | Effect.gen(function* () { |
| 156 | expect(yield* request("services")).toEqual({ encoded: "37", decoded: 42 }); |
| 157 | }).pipe(Effect.scoped), |
| 158 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 159 | ); |
| 160 | |
| 161 | test( |
| 162 | "decodes existing unchecked attachments without an envelope", |
| 163 | Effect.gen(function* () { |
| 164 | expect(yield* request("unchecked")).toEqual({ count: 17, joined: timestamp, isDate: true }); |
| 165 | }).pipe(Effect.scoped), |
| 166 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 167 | ); |
| 168 | |
| 169 | test( |
| 170 | "reports native absence even for Schema.Unknown", |
| 171 | Effect.gen(function* () { |
| 172 | const response = yield* request("missing"); |
| 173 | yield* Effect.sync(() => console.log("Native attachment absence", { dev, response })); |
| 174 | expect(response).toMatchObject({ |
| 175 | _tag: "WebSocketAttachmentError", |
| 176 | reason: "missing", |
| 177 | absence: "null", |
| 178 | }); |
| 179 | }).pipe(Effect.scoped), |
| 180 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 181 | ); |
| 182 | |
| 183 | test( |
| 184 | "returns malformed encoded values as recoverable decode errors", |
| 185 | Effect.gen(function* () { |
| 186 | expect(yield* request("malformed")).toMatchObject({ |
| 187 | _tag: "WebSocketAttachmentError", |
| 188 | reason: "decode", |
| 189 | causeIsError: true, |
| 190 | }); |
| 191 | }).pipe(Effect.scoped), |
| 192 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 193 | ); |
| 194 | |
| 195 | test( |
| 196 | "encode failure preserves the previously written attachment", |
| 197 | Effect.gen(function* () { |
| 198 | expect(yield* request("encode")).toMatchObject({ |
| 199 | _tag: "WebSocketAttachmentError", |
| 200 | reason: "encode", |
| 201 | previous: "7", |
| 202 | causeIsError: true, |
| 203 | }); |
| 204 | }).pipe(Effect.scoped), |
| 205 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 206 | ); |
| 207 | |
| 208 | test( |
| 209 | "native oversize serialization is a recoverable write failure", |
| 210 | Effect.gen(function* () { |
| 211 | const response = yield* request("oversize"); |
| 212 | yield* Effect.sync(() => console.log("Native attachment size limit", { dev, response })); |
| 213 | expect(response).toMatchObject({ |
| 214 | _tag: "WebSocketAttachmentError", |
| 215 | reason: "write", |
| 216 | acceptedLength: 16_000, |
| 217 | previous: "small", |
| 218 | cause: |
| 219 | "A WebSocket 'attachment' cannot be larger than 16384 bytes.'attachment' was 32774 bytes.", |
| 220 | causeIsError: true, |
| 221 | }); |
| 222 | }).pipe(Effect.scoped), |
| 223 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 224 | ); |
| 225 | |
| 226 | test( |
| 227 | "native structured clone preserves Dates, Maps, and bytes without aliasing", |
| 228 | Effect.gen(function* () { |
| 229 | expect(yield* request("clone")).toEqual({ date: timestamp, count: 42, bytes: [1, 2, 3] }); |
| 230 | }).pipe(Effect.scoped), |
| 231 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 232 | ); |
| 233 | |
| 234 | test( |
| 235 | "a schema-valid uncloneable value reports the genuine native error", |
| 236 | Effect.gen(function* () { |
| 237 | expect(yield* request("uncloneable")).toMatchObject({ |
| 238 | _tag: "WebSocketAttachmentError", |
| 239 | reason: "write", |
| 240 | causeIsError: true, |
| 241 | }); |
| 242 | }).pipe(Effect.scoped), |
| 243 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 244 | ); |
| 245 | |
| 246 | test( |
| 247 | "upgrade tags sockets for getWebSockets(tag) and getTags", |
| 248 | Effect.gen(function* () { |
| 249 | const { url } = yield* stack; |
| 250 | // A fresh object per attempt so sockets from a retried attempt are not counted. |
| 251 | const name = `tags-${crypto.randomUUID()}`; |
| 252 | const a = yield* connect(`${url}/socket/${name}?tags=user:a,room:all`); |
| 253 | const b = yield* connect(`${url}/socket/${name}?tags=user:b,room:all`); |
| 254 | const untagged = yield* connect(`${url}/socket/${name}`); |
| 255 | const members = { "user:a": 1, "user:b": 1, "room:all": 2 }; |
| 256 | yield* a.send("tags"); |
| 257 | expect(yield* a.receive).toEqual({ tags: ["user:a", "room:all"], members, all: 3 }); |
| 258 | yield* b.send("tags"); |
| 259 | expect(yield* b.receive).toEqual({ tags: ["user:b", "room:all"], members, all: 3 }); |
| 260 | yield* untagged.send("tags"); |
| 261 | expect(yield* untagged.receive).toEqual({ tags: [], members, all: 3 }); |
| 262 | }).pipe(Effect.scoped), |
| 263 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 264 | ); |
| 265 | |
| 266 | test( |
| 267 | "real hibernation restores typed attachments and closes an obsolete schema by application policy", |
| 268 | Effect.gen(function* () { |
| 269 | const { url } = yield* stack; |
| 270 | const valid = yield* connect(`${url}/socket/idle`); |
| 271 | yield* valid.send("codec"); |
| 272 | yield* valid.receive; |
| 273 | yield* valid.send("stats"); |
| 274 | const before = yield* valid.receive.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Stats))); |
| 275 | const obsolete = yield* connect(`${url}/socket/idle`); |
| 276 | yield* obsolete.send("obsolete"); |
| 277 | expect(yield* obsolete.receive).toEqual({ boots: before.boots, obsolete: true }); |
| 278 | const sameSocket = valid.socket; |
| 279 | const after = yield* Effect.gen(function* () { |
| 280 | yield* Effect.sleep("15 seconds"); |
| 281 | yield* valid.send("stats"); |
| 282 | return yield* valid.receive.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Stats))); |
| 283 | }).pipe(Effect.repeat({ times: 2, until: (value) => value.boots > before.boots })); |
| 284 | expect(after.boots).toBeGreaterThan(before.boots); |
| 285 | expect(after.restored).toEqual([42]); |
| 286 | expect(after.rejected).toEqual(["decode"]); |
| 287 | expect(after.count).toBe(42); |
| 288 | expect(after.joined).toBe(timestamp); |
| 289 | expect(after.isDate).toBe(true); |
| 290 | expect(valid.socket).toBe(sameSocket); |
| 291 | expect(valid.socket.readyState).toBe(WebSocket.OPEN); |
| 292 | expect(yield* obsolete.receive).toMatchObject({ |
| 293 | _tag: "WebSocketAttachmentError", |
| 294 | reason: "decode", |
| 295 | boots: after.boots, |
| 296 | }); |
| 297 | expect(yield* obsolete.closed).toEqual({ code: 1008, reason: "Invalid attachment" }); |
| 298 | expect(obsolete.socket.readyState).toBe(WebSocket.CLOSED); |
| 299 | yield* valid.send("stats"); |
| 300 | expect(yield* valid.receive).toEqual(after); |
| 301 | }).pipe(Effect.scoped), |
| 302 | { tags: [...(dev ? ["local"] : ["live"])], timeout: 110_000 }, |
| 303 | ); |
| 304 | }, |
| 305 | { tags: ["provider:cloudflare", "provider:cloudflare:worker"] }, |
| 306 | ); |