| 767 | * @since 4.0.0 |
| 768 | */ |
| 769 | export const makeWebSocket = <R = never>( |
| 770 | options: { |
| 771 | readonly url: string |
| 772 | readonly headers?: Headers.Input | undefined |
| 773 | readonly connectionParams?: Effect.Effect<Record<string, unknown> | undefined, unknown, R> | undefined |
| 774 | readonly connectionAckTimeout?: Duration.Input | undefined |
| 775 | readonly keepAlive?: Duration.Input | false | undefined |
| 776 | readonly idleTimeout?: Duration.Input | undefined |
| 777 | } |
| 778 | ): Effect.Effect<GraphQLProtocol["Service"], never, Socket.WebSocketConstructor | Scope.Scope | R> => |
| 779 | Effect.gen(function*() { |
| 780 | const socket = yield* Socket.makeWebSocket(options.url, { |
| 781 | protocols: "graphql-transport-ws", |
| 782 | headers: options.headers === undefined ? undefined : Headers.fromInput(options.headers) |
| 783 | }) |
| 784 | const writer = yield* socket.writer |
| 785 | const scope = yield* Effect.scope |
| 786 | const context = yield* Effect.context<R>() |
| 787 | const connectionParams = options.connectionParams === undefined |
| 788 | ? Effect.succeed(undefined) |
| 789 | : options.connectionParams.pipe( |
| 790 | Effect.provideContext(context), |
| 791 | Effect.mapError((cause) => |
| 792 | new TransportError({ description: `graphql-ws connectionParams failed: ${errorMessage(cause)}`, cause }) |
| 793 | ) |
| 794 | ) |
| 795 | const ackTimeout = options.connectionAckTimeout ?? Duration.seconds(10) |
| 796 | const keepAlive = options.keepAlive ?? Duration.seconds(10) |
| 797 | const idleTimeout = Duration.fromInputUnsafe(options.idleTimeout ?? 0) |
| 798 | |
| 799 | const operations = new Map<string, Operation>() |
| 800 | let connection: Connection | undefined |
| 801 | let nextId = 0 |
| 802 | let active = 0 |
| 803 | let idleGeneration = 0 |
| 804 | |
| 805 | const send = (message: WsMessage) => |
| 806 | writer.write(JSON.stringify(message)).pipe( |
| 807 | Effect.mapError((cause) => connectionError(Cause.fail(cause))) |
| 808 | ) |
| 809 | |
| 810 | const lose = (conn: Connection, error: TransportError) => { |
| 811 | if (conn.error !== undefined) return |
| 812 | conn.error = error |
| 813 | if (connection === conn) connection = undefined |
| 814 | Deferred.doneUnsafe(conn.ack, Effect.fail(error)) |
| 815 | for (const [id, operation] of operations) { |
| 816 | if (operation.connection !== conn) continue |
| 817 | operations.delete(id) |
| 818 | Queue.failCauseUnsafe(operation.queue, Cause.fail(error)) |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | // An invalid server message closes the connection with 4400, which is |
| 823 | // fatal for every operation on it. |
| 824 | const invalid = (reason: string, cause?: unknown) => |
| 825 | Effect.andThen( |
| 826 | Effect.ignore(writer.write(new Socket.CloseEvent(4400, "Invalid message"))), |