diff --git a/packages/effect/test/graphql/GraphQLProtocol.sse.test.ts b/packages/effect/test/graphql/GraphQLProtocol.sse.test.ts new file mode 100644 index 0000000000..3cf7dd20a0 --- /dev/null +++ b/packages/effect/test/graphql/GraphQLProtocol.sse.test.ts @@ -0,0 +1,114 @@ +import { assert, describe, it } from "@effect/vitest" +import { Deferred, Duration, Effect, Fiber, Layer, Stream } from "effect" +import { GraphQLClient, GraphQLProtocol } from "effect/graphql" +import { TransportError } from "effect/graphql/GraphQLClientError" +import * as HttpClient from "effect/http/HttpClient" +import * as HttpClientResponse from "effect/http/HttpClientResponse" +import { expectReason, graphqlResponse, httpClientLayer, IssuesGroup, IssueUpdated } from "./fixtures.ts" + +const url = "http://localhost/graphql" + +const event = (title: string) => ({ data: { issueUpdated: { title } } }) + +const subscription: GraphQLProtocol.GraphQLRequest = { + query: IssueUpdated.document, + operationName: "IssueUpdated", + variables: { id: "I_1" }, + headers: { authorization: "Bearer t" } +} + +/** + * A `text/event-stream` body that sends `chunks`, then ends, fails with + * `error`, or stays open. + */ +const eventStream = (chunks: ReadonlyArray, end: "close" | "open" | Error) => + new Response( + new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk)) + if (end === "close") controller.close() + else if (end instanceof Error) controller.error(end) + } + }), + { headers: { "content-type": "text/event-stream" } } + ) + +const next = (payload: unknown) => `event: next\ndata: ${JSON.stringify(payload)}\n\n` + +const subscribe = (layer: Layer.Layer) => + GraphQLProtocol.makeHttp({ url }).pipe( + Effect.map((protocol) => protocol.subscribe(subscription)), + Effect.provide(layer), + Stream.unwrap + ) + +describe("GraphQLProtocol.layerHttp subscriptions (graphql-sse distinct mode)", () => { + for (const ending of ["complete", "EOF"] as const) { + it.effect(`POSTs with Accept: text/event-stream and emits next events until ${ending}`, () => + Effect.gen(function*() { + let seen: { method: string; headers: Record; body: unknown } | undefined + const events = yield* subscribe(httpClientLayer((request, bodyText) => { + seen = { method: request.method, headers: request.headers, body: JSON.parse(bodyText!) } + return ending === "complete" + ? eventStream([next(event("a")), next(event("b")), "event: complete\ndata:\n\n"], "open") + : eventStream([next(event("a")), next(event("b"))], "close") + })).pipe(Stream.runCollect) + assert.deepStrictEqual(events, [event("a"), event("b")]) + assert.strictEqual(seen!.method, "POST") + assert.include(seen!.headers["accept"], "text/event-stream") + assert.strictEqual(seen!.headers["authorization"], "Bearer t") + assert.deepStrictEqual(seen!.body, { + query: IssueUpdated.document, + operationName: "IssueUpdated", + variables: { id: "I_1" } + }) + })) + } + + it.effect("a retry: line becomes retryAfter when the stream then fails", () => + Effect.gen(function*() { + const error = yield* subscribe( + httpClientLayer(() => eventStream([next(event("a")), "retry: 3000\n\n"], new Error("connection reset"))) + ).pipe(Stream.runDrain, Effect.flip) + assert.instanceOf(error, TransportError) + assert.isTrue(error.isRetryable) + assert.deepStrictEqual(error.retryAfter, Duration.seconds(3)) + })) + + it.effect("a GraphQL error response instead of a stream fails the client stream with ResponseError", () => + Effect.gen(function*() { + const layer = GraphQLProtocol.layerHttp({ url }).pipe( + Layer.provide(httpClientLayer(() => graphqlResponse({ errors: [{ message: "denied" }] }, { status: 400 }))) + ) + const reason = yield* GraphQLClient.make(IssuesGroup).pipe( + Effect.map((client) => client.IssueUpdated({ id: "I_1" })), + Effect.provide(layer), + Stream.unwrap, + Stream.runDrain, + expectReason("ResponseError") + ) + assert.deepStrictEqual(reason.errors, [{ message: "denied" }]) + })) + + it.effect("interrupting the stream aborts the request", () => + Effect.gen(function*() { + let signal: AbortSignal | undefined + const layer = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request, _url, abort) => { + signal = abort + return Effect.succeed(HttpClientResponse.fromWeb(request, eventStream([next(event("a"))], "open"))) + }) + ) + const received = yield* Deferred.make() + const fiber = yield* subscribe(layer).pipe( + Stream.runForEach(() => Deferred.succeed(received, void 0)), + Effect.forkChild + ) + // Join too, so a stream that fails before its first event fails the test. + yield* Deferred.await(received).pipe(Effect.raceFirst(Fiber.join(fiber))) + assert.isFalse(signal!.aborted) + yield* Fiber.interrupt(fiber) + assert.isTrue(signal!.aborted) + })) +}) diff --git a/packages/effect/test/graphql/GraphQLProtocol.webSocket.test.ts b/packages/effect/test/graphql/GraphQLProtocol.webSocket.test.ts new file mode 100644 index 0000000000..4a992ec022 --- /dev/null +++ b/packages/effect/test/graphql/GraphQLProtocol.webSocket.test.ts @@ -0,0 +1,218 @@ +import { assert, describe, it } from "@effect/vitest" +import { Deferred, Effect, Fiber, Layer, Queue, Ref, Stream } from "effect" +import { GraphQLClient, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql" +import { TransportError } from "effect/graphql/GraphQLClientError" +import { TestClock } from "effect/testing" +import { expectReason, IssuesGroup, IssueUpdated, Viewer, wsServer } from "./fixtures.ts" + +const url = "ws://localhost/graphql" + +const event = (title: string) => ({ data: { issueUpdated: { title } } }) + +const subscription = (id: string): GraphQLProtocol.GraphQLRequest => ({ + query: IssueUpdated.document, + operationName: "IssueUpdated", + variables: { id }, + headers: {} +}) + +const makeProtocol = ( + server: Effect.Success, + options?: Omit[0], "url"> +) => GraphQLProtocol.makeWebSocket({ url, ...options }).pipe(Effect.provide(server.layer)) + +describe("GraphQLProtocol.makeWebSocket", () => { + it.effect("subscribes only after connection_ack and routes events by operation id", () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server, { connectionParams: Effect.succeed({ token: "t1" }) }) + const a = yield* protocol.subscribe(subscription("A")).pipe(Stream.runCollect, Effect.forkChild) + const b = yield* protocol.subscribe(subscription("B")).pipe(Stream.runCollect, Effect.forkChild) + + const connection = yield* Queue.take(server.connections) + assert.strictEqual(connection.url, url) + assert.deepStrictEqual(connection.options, "graphql-transport-ws") + assert.deepStrictEqual(yield* Queue.take(connection.received), { + type: "connection_init", + payload: { token: "t1" } + }) + yield* TestClock.adjust("1 second") + assert.strictEqual(yield* Queue.size(connection.received), 0) + + yield* connection.send({ type: "connection_ack" }) + const subscribes = [yield* Queue.take(connection.received), yield* Queue.take(connection.received)] + const ids: Record = {} + for (const message of subscribes) { + assert.strictEqual(message.type, "subscribe") + const payload = message.payload as { variables: { id: string } } + ids[payload.variables.id] = message.id! + } + assert.deepStrictEqual(subscribes.find((message) => message.id === ids.A)!.payload, { + query: IssueUpdated.document, + operationName: "IssueUpdated", + variables: { id: "A" } + }) + assert.notStrictEqual(ids.A, ids.B) + + yield* connection.send({ id: "unknown", type: "next", payload: event("x") }) + yield* connection.send({ id: ids.B, type: "next", payload: event("b") }) + yield* connection.send({ id: ids.A, type: "next", payload: event("a") }) + yield* connection.send({ id: ids.A, type: "complete" }) + yield* connection.send({ id: ids.B, type: "complete" }) + assert.deepStrictEqual(yield* Fiber.join(a), [event("a")]) + assert.deepStrictEqual(yield* Fiber.join(b), [event("b")]) + })) + + it.effect("a missing connection_ack is a TransportError", () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server, { connectionAckTimeout: "5 seconds" }) + const fiber = yield* protocol.subscribe(subscription("A")).pipe(Stream.runDrain, Effect.flip, Effect.forkChild) + yield* Queue.take(server.connections) + yield* TestClock.adjust("5 seconds") + assert.instanceOf(yield* Fiber.join(fiber), TransportError) + })) + + it.effect("answers ping with pong, pings every keepAlive and treats a missed frame as a retryable close", () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server, { keepAlive: "10 seconds" }) + const fiber = yield* protocol.subscribe(subscription("A")).pipe(Stream.runDrain, Effect.flip, Effect.forkChild) + const { connection } = yield* server.accept + assert.strictEqual((yield* Queue.take(connection.received)).type, "subscribe") + + yield* connection.send({ type: "ping" }) + assert.deepStrictEqual(yield* Queue.take(connection.received), { type: "pong" }) + + yield* TestClock.adjust("10 seconds") + assert.deepStrictEqual(yield* Queue.take(connection.received), { type: "ping" }) + yield* TestClock.adjust("10 seconds") + const error = yield* Fiber.join(fiber) + assert.instanceOf(error, TransportError) + assert.isTrue(error.isRetryable) + })) + + for (const [code, retryable] of [[4401, false], [4406, false], [1006, true], [4500, true]] as const) { + it.effect(`close code ${code} is a ${retryable ? "retryable" : "fatal"} TransportError`, () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server) + const fiber = yield* protocol.subscribe(subscription("A")).pipe( + Stream.runDrain, + Effect.flip, + Effect.forkChild + ) + const { connection } = yield* server.accept + yield* Queue.take(connection.received) + yield* connection.close(code) + const error = yield* Fiber.join(fiber) + assert.strictEqual(error.closeCode, code) + assert.strictEqual(error.isRetryable, retryable) + })) + } + + it.effect("interrupting a subscription sends a client complete", () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server) + const fiber = yield* protocol.subscribe(subscription("A")).pipe(Stream.runDrain, Effect.forkChild) + const { connection } = yield* server.accept + const subscribe = yield* Queue.take(connection.received) + yield* Fiber.interrupt(fiber) + assert.deepStrictEqual(yield* Queue.take(connection.received), { id: subscribe.id, type: "complete" }) + })) + + it.effect("a lost connection fails in-flight queries, and the next operation reconnects with fresh connectionParams", () => + Effect.gen(function*() { + const server = yield* wsServer + const tokens = yield* Ref.make(0) + const protocol = yield* makeProtocol(server, { + connectionParams: Effect.map(Ref.updateAndGet(tokens, (n) => n + 1), (n) => ({ token: n })) + }) + const query: GraphQLProtocol.GraphQLRequest = { + query: Viewer.document, + operationName: "Viewer", + variables: {}, + headers: {} + } + + const inFlight = yield* protocol.execute(query).pipe(Effect.flip, Effect.forkChild) + const first = yield* server.accept + assert.deepStrictEqual(first.init.payload, { token: 1 }) + yield* Queue.take(first.connection.received) + yield* first.connection.close(1006) + const error = yield* Fiber.join(inFlight) + assert.isTrue(error.isRetryable) + + const retried = yield* protocol.execute(query).pipe(Effect.forkChild) + const second = yield* server.accept + assert.deepStrictEqual(second.init.payload, { token: 2 }) + const subscribe = yield* Queue.take(second.connection.received) + yield* second.connection.send({ id: subscribe.id, type: "next", payload: { data: { viewer: { login: "tim" } } } }) + yield* second.connection.send({ id: subscribe.id, type: "complete" }) + assert.deepStrictEqual(yield* Fiber.join(retried), { data: { viewer: { login: "tim" } } }) + })) + + it.effect("connects on the first operation, ignores per-call headers and closes idleTimeout after the last one", () => + Effect.gen(function*() { + const server = yield* wsServer + const protocol = yield* makeProtocol(server, { idleTimeout: "30 seconds" }) + yield* TestClock.adjust("1 minute") + assert.strictEqual(yield* Queue.size(server.connections), 0) + + const fiber = yield* protocol.subscribe({ ...subscription("A"), headers: { authorization: "Bearer t" } }).pipe( + Stream.runCollect, + Effect.forkChild + ) + const { connection } = yield* server.accept + const subscribe = yield* Queue.take(connection.received) + assert.deepStrictEqual(subscribe.payload, { + query: IssueUpdated.document, + operationName: "IssueUpdated", + variables: { id: "A" } + }) + yield* connection.send({ id: subscribe.id, type: "complete" }) + assert.deepStrictEqual(yield* Fiber.join(fiber), []) + + yield* TestClock.adjust("29 seconds") + assert.isFalse(yield* Deferred.isDone(connection.closed)) + yield* TestClock.adjust("1 second") + assert.strictEqual(yield* Deferred.await(connection.closed), 1000) + })) +}) + +describe("GraphQLProtocol.layerWebSocket with GraphQLClient", () => { + it.effect("a retryable close resubscribes through the middleware chain; a server error is a ResponseError", () => + Effect.gen(function*() { + class Count extends GraphQLMiddleware.Service()("test/Count") {} + const subscribes = yield* Ref.make(0) + const CountLive = Layer.succeed(Count, { + execute: ({ next, request }) => next(request), + subscribe: ({ next, request }) => Stream.unwrap(Effect.as(Ref.update(subscribes, (n) => n + 1), next(request))) + }) + const server = yield* wsServer + const context = yield* Layer.build( + Layer.merge(GraphQLProtocol.layerWebSocket({ url }).pipe(Layer.provide(server.layer)), CountLive) + ) + const client = yield* GraphQLClient.make(IssuesGroup.middleware(Count)).pipe(Effect.provide(context)) + const fiber = yield* client.IssueUpdated({ id: "I_1" }).pipe( + Stream.runCollect, + expectReason("ResponseError"), + Effect.forkChild + ) + + const first = yield* server.accept + yield* Queue.take(first.connection.received) + yield* first.connection.close(4500) + // The client's default schedule waits 500ms before resubscribing. + yield* TestClock.adjust("500 millis") + + const second = yield* server.accept + const subscribe = yield* Queue.take(second.connection.received) + yield* second.connection.send({ id: subscribe.id, type: "error", payload: [{ message: "denied" }] }) + const reason = yield* Fiber.join(fiber) + assert.deepStrictEqual(reason.errors, [{ message: "denied" }]) + assert.isUndefined(reason.data) + assert.strictEqual(yield* Ref.get(subscribes), 2) + })) +}) diff --git a/packages/effect/test/graphql/fixtures.ts b/packages/effect/test/graphql/fixtures.ts index 89a5cc5400..0af87e23d0 100644 --- a/packages/effect/test/graphql/fixtures.ts +++ b/packages/effect/test/graphql/fixtures.ts @@ -7,7 +7,7 @@ * codec (`DateTime`) that applies to inputs and results alike. */ import { assert } from "@effect/vitest" -import { Effect, Layer, Ref, Schema, Stream } from "effect" +import { Deferred, Effect, Layer, Queue, Ref, Schema, Stream } from "effect" import { GraphQL, GraphQLGroup } from "effect/graphql" import { GraphQLClientError } from "effect/graphql/GraphQLClientError" import type { TransportError } from "effect/graphql/GraphQLClientError" @@ -16,6 +16,7 @@ import * as HttpBody from "effect/http/HttpBody" import * as HttpClient from "effect/http/HttpClient" import type * as HttpClientRequest from "effect/http/HttpClientRequest" import * as HttpClientResponse from "effect/http/HttpClientResponse" +import * as Socket from "effect/socket/Socket" // ----------------------------------------------------------------------------- // Stand-in for generated output @@ -141,6 +142,99 @@ export const layerHttp = ( handler: (request: HttpClientRequest.HttpClientRequest, bodyText: string | undefined) => Response ) => GraphQLProtocol.layerHttp({ url: "http://localhost/graphql" }).pipe(Layer.provide(httpClientLayer(handler))) +/** + * A graphql-ws message as it goes over the wire. + */ +export interface WsMessage { + readonly type: string + readonly id?: string | undefined + readonly payload?: unknown +} + +/** + * The server end of one in-memory WebSocket opened by the transport. + */ +export interface WsConnection { + readonly url: string + readonly options: Socket.WebSocketConstructorOptions | undefined + /** Every frame the client sent, parsed. */ + readonly received: Queue.Queue + /** The code the client closed with, once it does. */ + readonly closed: Deferred.Deferred + readonly send: (message: WsMessage) => Effect.Effect + readonly close: (code: number, reason?: string) => Effect.Effect +} + +/** + * A `Socket.WebSocketConstructor` whose sockets are in-memory queue pairs. + * Each socket the transport opens shows up on `connections`, already open, + * for the test to script the server side. + */ +export const wsServer = Effect.gen(function*() { + const connections = yield* Queue.unbounded() + const layer = Layer.succeed( + Socket.WebSocketConstructor, + (url, options) => { + const inbox = Effect.runSync(Queue.unbounded()) + const closedWith = Effect.runSync(Deferred.make()) + let listeners: Array<{ + readonly type: string + readonly listener: (event: Socket.WebSocketEvent) => void + readonly once: boolean + }> = [] + const dispatch = (type: string, event: Socket.WebSocketEvent) => { + for (const entry of listeners.filter((entry) => entry.type === type)) { + if (entry.once) listeners = listeners.filter((other) => other !== entry) + entry.listener(event) + } + } + const ws = { + readyState: 1, + addEventListener(type, listener, options) { + listeners.push({ type, listener, once: options?.once === true }) + }, + removeEventListener(type, listener) { + listeners = listeners.filter((entry) => entry.type !== type || entry.listener !== listener) + }, + send(data) { + Queue.offerUnsafe(inbox, JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data))) + }, + close(code = 1005, reason) { + if (ws.readyState >= 2) return + ws.readyState = 3 + Deferred.doneUnsafe(closedWith, Effect.succeed(code)) + dispatch("close", { code, reason: reason ?? "" }) + } + } satisfies Socket.WebSocketLike & { readyState: number } + Queue.offerUnsafe(connections, { + url, + options, + received: inbox, + closed: closedWith, + send: (message) => Effect.sync(() => dispatch("message", { data: JSON.stringify(message) })), + close: (code, reason) => + Effect.sync(() => { + if (ws.readyState >= 2) return + ws.readyState = 3 + dispatch("close", { code, reason: reason ?? "" }) + }) + }) + return ws + } + ) + /** + * Takes the next connection, reads its `connection_init` and acknowledges it. + */ + const accept = Effect.gen(function*() { + const connection = yield* Queue.take(connections) + const init = yield* Queue.take(connection.received) + assert.strictEqual(init.type, "connection_init") + yield* connection.send({ type: "connection_ack" }) + return { connection, init } + }) + return { layer, connections, accept } +}) + // ----------------------------------------------------------------------------- // Assertions // ----------------------------------------------------------------------------- diff --git a/packages/platform/node/test/GraphQLProtocol.test.ts b/packages/platform/node/test/GraphQLProtocol.test.ts new file mode 100644 index 0000000000..35854054b3 --- /dev/null +++ b/packages/platform/node/test/GraphQLProtocol.test.ts @@ -0,0 +1,119 @@ +import { NodeHttpServer, NodeSocket } from "@effect/platform-node" +import { assert, describe, it } from "@effect/vitest" +import { Effect, Layer, Schema, Stream } from "effect" +import { GraphQL, GraphQLClient, GraphQLGroup, GraphQLProtocol } from "effect/graphql" +import { FetchHttpClient, HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http" +import type * as NetAddress from "effect/net/NetAddress" + +const Viewer = GraphQL.query("Viewer", { + document: "query Viewer{viewer{login}}", + result: Schema.Struct({ viewer: Schema.Struct({ login: Schema.String }) }) +}) + +const IssueUpdated = GraphQL.subscription("IssueUpdated", { + document: "subscription IssueUpdated($id:ID!){issueUpdated(id:$id){title}}", + variables: { id: Schema.String }, + result: Schema.Struct({ issueUpdated: Schema.Struct({ title: Schema.String }) }) +}) + +const Group = GraphQLGroup.make(Viewer, IssueUpdated) + +const encoder = new TextEncoder() +const decoder = new TextDecoder() + +const viewer = { data: { viewer: { login: "tim" } } } +const issue = (title: string) => ({ data: { issueUpdated: { title } } }) + +/** + * POST answers queries with JSON and subscriptions with a graphql-sse stream. + */ +const post = Effect.gen(function*() { + const request = yield* HttpServerRequest.HttpServerRequest + if (!(request.headers["accept"] ?? "").includes("text/event-stream")) { + return yield* HttpServerResponse.json(viewer) + } + return HttpServerResponse.stream( + Stream.make( + `event: next\ndata: ${JSON.stringify(issue("over sse"))}\n\n`, + "event: complete\ndata:\n\n" + ).pipe(Stream.map((chunk) => encoder.encode(chunk))), + { contentType: "text/event-stream" } + ) +}) + +/** + * A hand-rolled graphql-transport-ws server that requires an Authorization + * header on the handshake. + */ +const webSocket = Effect.gen(function*() { + const request = yield* HttpServerRequest.HttpServerRequest + if (request.headers["authorization"] !== "Bearer secret") { + return HttpServerResponse.empty({ status: 401 }) + } + const socket = yield* request.upgrade + const { write } = yield* socket.writer + const { pull } = yield* socket.reader + const send = (message: unknown) => write(JSON.stringify(message)) + while (true) { + for (const frame of yield* pull) { + const message = JSON.parse(typeof frame === "string" ? frame : decoder.decode(frame)) + switch (message.type) { + case "connection_init": + yield* send({ type: "connection_ack" }) + break + case "ping": + yield* send({ type: "pong" }) + break + case "subscribe": + yield* send({ id: message.id, type: "next", payload: issue("over ws") }) + yield* send({ id: message.id, type: "complete" }) + break + } + } + } +}).pipe( + Effect.scoped, + Effect.catchTag("SocketError", () => Effect.succeed(HttpServerResponse.empty())) +) + +describe("GraphQLProtocol over a real server", () => { + it.effect( + "serves a query over POST, a subscription over graphql-ws and one over graphql-sse", + () => + Effect.gen(function*() { + yield* HttpRouter.add("POST", "/graphql", post).pipe( + Layer.merge(HttpRouter.add("GET", "/graphql", webSocket)), + (layer) => HttpRouter.serve(layer, { disableListenLog: true }), + Layer.build + ) + const server = yield* HttpServer.HttpServer + const port = (server.address as NetAddress.InetAddress).port + const url = `http://127.0.0.1:${port}/graphql` + + const splitProtocol = yield* Layer.build(GraphQLProtocol.layerHttp({ + url, + subscriptions: { + webSocket: { url: `ws://127.0.0.1:${port}/graphql`, headers: { authorization: "Bearer secret" } } + } + })) + const split = yield* GraphQLClient.make(Group).pipe(Effect.provide(splitProtocol)) + assert.deepStrictEqual(yield* split.Viewer(), viewer.data) + assert.deepStrictEqual( + yield* Stream.runCollect(split.IssueUpdated({ id: "I_1" })), + [issue("over ws").data] + ) + + const sseProtocol = yield* Layer.build(GraphQLProtocol.layerHttp({ url })) + const sse = yield* GraphQLClient.make(Group).pipe(Effect.provide(sseProtocol)) + assert.deepStrictEqual( + yield* Stream.runCollect(sse.IssueUpdated({ id: "I_1" })), + [issue("over sse").data] + ) + }).pipe( + Effect.provide([FetchHttpClient.layer, NodeSocket.layerWebSocketConstructor]), + Effect.provide(NodeHttpServer.layerTest), + Effect.timeout("5 seconds") + ), + 10000 + ) +})