The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { NeonAuth } from "@alchemy.run/neon/AuthProvider"; |
| 2 | import { fromAuthProvider } from "@alchemy.run/neon/Credentials"; |
| 3 | import { Function } from "@alchemy.run/neon/Function"; |
| 4 | import { FunctionLogs } from "@alchemy.run/neon/FunctionProvider"; |
| 5 | import { providers } from "@alchemy.run/neon/Providers"; |
| 6 | import { expect } from "@alchemy.run/test"; |
| 7 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 8 | import * as NeonApi from "@distilled.cloud/neon"; |
| 9 | import * as Alchemy from "alchemy"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Exit from "effect/Exit"; |
| 12 | import * as HttpClient from "effect/http/HttpClient"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Option from "effect/Option"; |
| 15 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 16 | import * as Schedule from "effect/Schedule"; |
| 17 | import * as Stream from "effect/Stream"; |
| 18 | import RuntimeFunction from "./fixtures/function-effect.ts"; |
| 19 | |
| 20 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 21 | providers: providers(), |
| 22 | }); |
| 23 | const Stack = Alchemy.Stack( |
| 24 | "NeonFunctionRuntime", |
| 25 | { providers: providers(), state: Alchemy.localState() }, |
| 26 | Effect.gen(function* () { |
| 27 | const api = yield* RuntimeFunction; |
| 28 | const main = yield* Effect.sync( |
| 29 | () => new URL("./fixtures/function-native-lifecycle.ts", import.meta.url).href, |
| 30 | ); |
| 31 | const native = yield* Function("NativeLifecycle", { |
| 32 | branch: { projectId: api.projectId, branchId: api.branchId }, |
| 33 | main, |
| 34 | }); |
| 35 | return { url: api.url, api, native }; |
| 36 | }), |
| 37 | ); |
| 38 | const stack = beforeAll(destroy(Stack).pipe(Effect.andThen(deploy(Stack)))); |
| 39 | afterAll( |
| 40 | Effect.gen(function* () { |
| 41 | const outputs = yield* Effect.exit(stack); |
| 42 | yield* destroy(Stack); |
| 43 | if (Exit.isFailure(outputs) || !outputs.value) return; |
| 44 | const { api, native } = outputs.value; |
| 45 | for (const resource of [api, native]) { |
| 46 | expect( |
| 47 | yield* NeonApi.getProjectBranchFunction({ |
| 48 | project_id: resource.projectId, |
| 49 | branch_id: resource.branchId, |
| 50 | slug: resource.slug, |
| 51 | }).pipe( |
| 52 | Effect.as(false), |
| 53 | Effect.catchTag("NotFound", () => Effect.succeed(true)), |
| 54 | ), |
| 55 | ).toBe(true); |
| 56 | } |
| 57 | expect( |
| 58 | yield* NeonApi.getProject({ project_id: api.projectId }).pipe( |
| 59 | Effect.as(false), |
| 60 | Effect.catchTag("NotFound", () => Effect.succeed(true)), |
| 61 | ), |
| 62 | ).toBe(true); |
| 63 | yield* Effect.logInfo( |
| 64 | "Neon lifecycle cleanup: both functions and project independently absent", |
| 65 | ); |
| 66 | }).pipe(Effect.provide(fromAuthProvider().pipe(Layer.provide(NeonAuth)))), |
| 67 | ); |
| 68 | const reportRuntimeLogs = Effect.gen(function* () { |
| 69 | const { api, native } = yield* stack; |
| 70 | const client = yield* HttpClient.HttpClient; |
| 71 | for (const resource of [api, native]) { |
| 72 | const lifecycle = yield* client |
| 73 | .get(`${resource.url}diagnostics`) |
| 74 | .pipe(Effect.flatMap((response) => response.json)); |
| 75 | yield* Effect.logInfo(JSON.stringify({ native: resource === native, lifecycle })); |
| 76 | const lines = yield* FunctionLogs(resource, { limit: 1000 }); |
| 77 | yield* Effect.logInfo( |
| 78 | JSON.stringify({ |
| 79 | native: resource === native, |
| 80 | functionRuntimeLogs: lines, |
| 81 | }), |
| 82 | ); |
| 83 | } |
| 84 | }); |
| 85 | |
| 86 | test( |
| 87 | "Effect class preserves request isolation, streams and bodyless finalizers", |
| 88 | Effect.gen(function* () { |
| 89 | const { url } = yield* stack; |
| 90 | const client = yield* HttpClient.HttpClient; |
| 91 | expect(yield* (yield* client.get(url)).text).toBe("effect"); |
| 92 | const stream = yield* client.get(`${url}stream?id=stream`); |
| 93 | expect(yield* stream.text).toBe("data: first\n\ndata: second\n\n"); |
| 94 | expect((yield* client.head(`${url}?id=head`)).status).toBe(200); |
| 95 | expect((yield* client.get(`${url}empty?id=empty`)).status).toBe(204); |
| 96 | const parallel = yield* Effect.all( |
| 97 | Array.from({ length: 4 }, (_, i) => |
| 98 | client.get(`${url}slow?id=parallel${i}`).pipe(Effect.flatMap((response) => response.text)), |
| 99 | ), |
| 100 | { concurrency: 4 }, |
| 101 | ); |
| 102 | expect(parallel).toEqual(["effect", "effect", "effect", "effect"]); |
| 103 | const finalized = yield* client |
| 104 | .get(`${url}finalized`) |
| 105 | .pipe(Effect.flatMap((response) => response.json)); |
| 106 | expect(finalized).toMatchObject({ active: 0 }); |
| 107 | expect(finalized).toMatchObject({ |
| 108 | finalized: expect.arrayContaining([ |
| 109 | "stream", |
| 110 | "head", |
| 111 | "empty", |
| 112 | "parallel0", |
| 113 | "parallel1", |
| 114 | "parallel2", |
| 115 | "parallel3", |
| 116 | ]), |
| 117 | }); |
| 118 | }), |
| 119 | { |
| 120 | tags: ["provider:neon", "provider:neon:function", "provider:neon:project", "live"], |
| 121 | timeout: 120_000, |
| 122 | }, |
| 123 | ); |
| 124 | |
| 125 | test( |
| 126 | "waitUntil outlives the response with an independent request scope", |
| 127 | Effect.gen(function* () { |
| 128 | const { url } = yield* stack; |
| 129 | const client = yield* HttpClient.HttpClient; |
| 130 | expect(yield* (yield* client.get(`${url}background?id=background-request`)).text).toBe( |
| 131 | "scheduled", |
| 132 | ); |
| 133 | const completed = yield* client.get(`${url}finalized`).pipe( |
| 134 | Effect.flatMap((response) => response.json), |
| 135 | Effect.repeat({ |
| 136 | schedule: Schedule.spaced("500 millis"), |
| 137 | times: 8, |
| 138 | until: (body) => JSON.stringify(body).includes("background-work"), |
| 139 | }), |
| 140 | ); |
| 141 | expect(completed).toMatchObject({ |
| 142 | finalized: expect.arrayContaining(["background-request", "background-work"]), |
| 143 | }); |
| 144 | }), |
| 145 | { |
| 146 | tags: ["provider:neon", "provider:neon:function", "provider:neon:project", "live"], |
| 147 | timeout: 120_000, |
| 148 | }, |
| 149 | ); |
| 150 | |
| 151 | // Waits up to two minutes for durable finalizer evidence; skip under --fast. |
| 152 | test.provider.skipIf(!!process.env.FAST)( |
| 153 | "WebSocket upgrade preserves native metadata and closes the request scope", |
| 154 | () => |
| 155 | Effect.gen(function* () { |
| 156 | const { url, native } = yield* stack; |
| 157 | for (const [target, id] of [ |
| 158 | [native.url, "native-websocket"], |
| 159 | [url, "websocket"], |
| 160 | ]) { |
| 161 | const echoed = yield* Effect.callback<string, Error>((resume) => { |
| 162 | const socket = new WebSocket(`${target.replace(/^http/, "ws")}websocket?id=${id}`); |
| 163 | let message: string | undefined; |
| 164 | socket.addEventListener("open", () => socket.send("native-upgrade")); |
| 165 | socket.addEventListener( |
| 166 | "message", |
| 167 | (event) => { |
| 168 | message = String(event.data); |
| 169 | socket.close(1000); |
| 170 | }, |
| 171 | { once: true }, |
| 172 | ); |
| 173 | socket.addEventListener( |
| 174 | "close", |
| 175 | (event) => |
| 176 | resume( |
| 177 | message !== undefined && event.wasClean |
| 178 | ? Effect.succeed(message) |
| 179 | : Effect.fail(new Error(`Neon WebSocket closed unexpectedly (${event.code})`)), |
| 180 | ), |
| 181 | { once: true }, |
| 182 | ); |
| 183 | socket.addEventListener( |
| 184 | "error", |
| 185 | () => resume(Effect.fail(new Error("Neon WebSocket handshake failed"))), |
| 186 | { once: true }, |
| 187 | ); |
| 188 | return Effect.sync(() => socket.close()); |
| 189 | }).pipe(Effect.timeout("15 seconds")); |
| 190 | expect(echoed).toBe("native-upgrade"); |
| 191 | } |
| 192 | const client = yield* HttpClient.HttpClient; |
| 193 | const completed = yield* client.get(`${url}finalized`).pipe( |
| 194 | Effect.flatMap((response) => response.json), |
| 195 | Effect.repeat({ |
| 196 | schedule: Schedule.spaced("1 second"), |
| 197 | until: (body) => JSON.stringify(body).includes("websocket"), |
| 198 | }), |
| 199 | Effect.timeout("2 minutes"), |
| 200 | ); |
| 201 | const lifecycle = yield* (yield* client.get(`${native.url}diagnostics`)).json; |
| 202 | yield* Effect.logInfo(JSON.stringify({ lifecycle })); |
| 203 | expect(lifecycle).toEqual( |
| 204 | expect.arrayContaining([{ id: "native-websocket", phase: "close" }]), |
| 205 | ); |
| 206 | expect(completed).toMatchObject({ |
| 207 | finalized: expect.arrayContaining(["websocket"]), |
| 208 | }); |
| 209 | }).pipe(Effect.ensuring(reportRuntimeLogs.pipe(Effect.orDie))), |
| 210 | { |
| 211 | tags: ["provider:neon", "provider:neon:function", "provider:neon:project", "live"], |
| 212 | timeout: 180_000, |
| 213 | }, |
| 214 | ); |
| 215 | |
| 216 | // Neon's host never cancels a response stream when the client disconnects, so |
| 217 | // even the native handler never sees abort/cancel: |
| 218 | // https://github.com/neondatabase/neon-pkgs/issues/636. Opt in with |
| 219 | // NEON_TEST_STREAM_CANCEL=1 once that is fixed. Waits up to two minutes for |
| 220 | // durable finalizer evidence; skip under --fast. |
| 221 | test.provider.skipIf(!!process.env.FAST || !process.env.NEON_TEST_STREAM_CANCEL)( |
| 222 | "cancelling a streamed response releases its request scope", |
| 223 | () => |
| 224 | Effect.gen(function* () { |
| 225 | const { url, native } = yield* stack; |
| 226 | for (const [target, id, suffix] of [ |
| 227 | [native.url, "native-stream", ""], |
| 228 | [url, "cancelled-stream", ""], |
| 229 | [native.url, "native-sse", "&sse"], |
| 230 | [url, "cancelled-sse", "&sse"], |
| 231 | ]) { |
| 232 | yield* Effect.gen(function* () { |
| 233 | const child = yield* ChildProcess.make("curl", [ |
| 234 | "--silent", |
| 235 | "--show-error", |
| 236 | "--fail", |
| 237 | "--no-buffer", |
| 238 | "--http1.1", |
| 239 | "--noproxy", |
| 240 | "*", |
| 241 | "--max-time", |
| 242 | "15", |
| 243 | "-H", |
| 244 | "Connection: close", |
| 245 | `${target}stream-cancel?id=${id}${suffix}`, |
| 246 | ]); |
| 247 | const first = yield* child.stdout.pipe( |
| 248 | Stream.decodeText, |
| 249 | Stream.filter((chunk) => chunk.includes("tick")), |
| 250 | Stream.runHead, |
| 251 | Effect.timeout("10 seconds"), |
| 252 | ); |
| 253 | expect(Option.isSome(first)).toBe(true); |
| 254 | // Terminating the client proves the transport closed, not just its reader. |
| 255 | if (yield* child.isRunning) yield* child.kill(); |
| 256 | expect(yield* child.isRunning).toBe(false); |
| 257 | }).pipe(Effect.scoped); |
| 258 | } |
| 259 | const client = yield* HttpClient.HttpClient; |
| 260 | const completed = yield* client.get(`${url}finalized`).pipe( |
| 261 | Effect.flatMap((response) => response.json), |
| 262 | Effect.repeat({ |
| 263 | schedule: Schedule.spaced("1 second"), |
| 264 | until: (body) => |
| 265 | ["cancelled-stream", "cancelled-sse"].every((id) => JSON.stringify(body).includes(id)), |
| 266 | }), |
| 267 | Effect.timeout("2 minutes"), |
| 268 | ); |
| 269 | const lifecycle = (yield* (yield* client.get(`${native.url}diagnostics`)).json) as { |
| 270 | id: string; |
| 271 | phase: string; |
| 272 | }[]; |
| 273 | yield* Effect.logInfo(JSON.stringify({ lifecycle })); |
| 274 | for (const id of ["native-stream", "native-sse"]) { |
| 275 | expect(lifecycle).toEqual(expect.arrayContaining([{ id, phase: "entered" }])); |
| 276 | expect( |
| 277 | lifecycle.some( |
| 278 | (row) => row.id === id && (row.phase === "abort" || row.phase === "cancel"), |
| 279 | ), |
| 280 | ).toBe(true); |
| 281 | } |
| 282 | expect(completed).toMatchObject({ |
| 283 | finalized: expect.arrayContaining(["cancelled-stream", "cancelled-sse"]), |
| 284 | }); |
| 285 | }).pipe(Effect.ensuring(reportRuntimeLogs.pipe(Effect.orDie))), |
| 286 | { |
| 287 | tags: ["provider:neon", "provider:neon:function", "provider:neon:project", "live"], |
| 288 | timeout: 180_000, |
| 289 | }, |
| 290 | ); |
| 291 | |
| 292 | test( |
| 293 | "Effect defects produce non-success responses without leaking errors", |
| 294 | Effect.gen(function* () { |
| 295 | const { url } = yield* stack; |
| 296 | const client = yield* HttpClient.HttpClient; |
| 297 | const response = yield* client.get(`${url}error`); |
| 298 | expect(response.status).toBe(500); |
| 299 | expect(yield* response.text).not.toContain("intentional"); |
| 300 | }), |
| 301 | { |
| 302 | tags: ["provider:neon", "provider:neon:function", "provider:neon:project", "live"], |
| 303 | timeout: 120_000, |
| 304 | }, |
| 305 | ); |