# Transport.webSocket

A transport over one WebSocket connection, shared by every call and subscription. It reconnects
when the connection drops and keeps an idle connection alive.

## Usage

```ts
import { Effect, Layer, Stream } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const WebSocket = Transport.webSocket("ws://127.0.0.1:8545").pipe(
  Layer.provide(Socket.layerWebSocketConstructorGlobal),
);

const program = Effect.gen(function* () {
  const chainId = yield* Eth.chainId();
  // waits for the next block
  const head = yield* Eth.subscribe.newHeads().pipe(Stream.runHead);
  return { chainId, head };
});

const result = await program.pipe(Effect.provide(WebSocket), Effect.runPromise);
```

`Socket.layerWebSocketConstructorGlobal` uses the global `WebSocket`, which browsers, Node 22
and later, Bun and Deno have. The call and the subscription travel on the same connection.

### On Node, with the `ws` package

`@effect/platform-node` has a constructor backed by the `ws` package, for a runtime without
the global or when you need what `ws` adds.

```ts
import { NodeWS } from "@effect/platform-node";
import { Layer } from "effect";
import { Transport } from "@ethect/core";

const WebSocket = Transport.webSocket("ws://127.0.0.1:8545").pipe(
  Layer.provide(NodeWS.layerWebSocketConstructor),
);
```

### Give up instead of reconnecting forever

By default the transport tries to reconnect forever. Pass a schedule that ends to make calls
and subscriptions fail once it is spent.

```ts
import { Layer, Schedule } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";

const WebSocket = Transport.webSocket("ws://127.0.0.1:8545", {
  // five attempts, one second apart
  reconnect: Schedule.max([Schedule.spaced("1 second"), Schedule.recurs(5)]),
}).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
```

A subscription that must not miss an item needs this: see
[Connection lifecycle](https://ethect.dev/concepts/connection-lifecycle/#the-gap).

## Returns

`Layer<Transport | Subscriptions, never, WebSocketConstructor>`

A layer that provides [`Transport`](https://ethect.dev/reference/transport/#transport) and
[`Subscriptions`](https://ethect.dev/reference/transport/#subscriptions), and needs a WebSocket constructor.

## Parameters

### url

- **Type:** `Transport.Url`

The WebSocket endpoint, `ws://` or `wss://`: a `string`, or a `Redacted<string>` for a URL
that is a secret.

```ts
import { Layer } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";

const WebSocket = Transport.webSocket("wss://rpc.example.com/ws").pipe(
  Layer.provide(Socket.layerWebSocketConstructorGlobal),
);
```

A plain string says the URL is not a secret. A `Redacted` one, such as a URL with an API key
in it, is unwrapped only where the socket is opened, and nothing of it is written anywhere
else.

| | A `string` | A `Redacted<string>` |
| --- | --- | --- |
| the `cause` of a failure | the socket's error, which holds the socket and its URL | a plain error: the tag of the socket's error, and its message without the URL |
| the reason a node gave when it closed the connection | as it was sent | without the URL, where the node repeats it |
| the message of the node's own error | as it was sent | without the URL, where the node repeats it |

```ts
import { Config, Effect, Layer } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";

const WebSocket = Layer.unwrap(
  // a Redacted<string>, read from the environment
  Effect.map(Config.Redacted("RPC_WS_URL"), (url) =>
    Transport.webSocket(url, { keepAlive: "20 seconds" }),
  ),
).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
// Layer<Transport | Subscriptions, ConfigError>
```

This holds for the failures of calls and of subscriptions, read with `subscribe` or with
[`opened`](https://ethect.dev/reference/transport/#opened). The `message` of a socket failure never names the
URL, secret or not.

### options (optional)

- **Type:** `Transport.SocketOptions`

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `reconnect` | a `Schedule` | exponential backoff from 500 ms, capped at 5 s, forever | The pauses between attempts to connect, after one fails or a connection ends within 5 seconds of opening. When the schedule ends, the transport gives up. |
| `keepAlive` | a `Duration` input, or `false` | `"30 seconds"` | How often `net_version` is called to keep the connection open. `false` turns it off. |

```ts
import { Layer, Schedule } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";

const WebSocket = Transport.webSocket("ws://127.0.0.1:8545", {
  reconnect: Schedule.spaced("2 seconds"),
  keepAlive: "10 seconds",
}).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
```

## Behavior

- **One connection.** Every call and every subscription of the transport share it. Answers
  are matched to calls by id, compared as text: a node may echo `1` as `"1"`.
- **A dropped connection fails the calls in flight** with `ConnectionLost`. They are not sent
  again.
- **A connection that lasted 5 seconds or more is replaced at once.** New calls wait for the
  new connection, and the `reconnect` schedule starts over.
- **A failed attempt, or a connection that ended within 5 seconds of opening, is paced** by
  the `reconnect` schedule: the first pause is 500 ms by default. Until the next connection
  opens, calls fail at once with `Unreachable`.
- **A URL the socket cannot use fails calls too.** Every call over
  `Transport.webSocket("not a url")` fails with `Unreachable`.
- **Subscriptions survive a reconnection.** Each one is issued again on the new connection,
  one whose `eth_subscribe` was still unanswered included. What the node emitted in between
  is not replayed: [`opened`](https://ethect.dev/reference/transport/#opened) says when to read it.
- **A secret URL is never written.** With a `Redacted` URL, no failure of the transport holds
  it: see [`url`](#url).
- **Keep-alive.** A `net_version` call goes out every `keepAlive`. Any answer counts, an error
  included. No answer before the next one is due closes the connection and reconnects.
- **A message that is JSON but not JSON-RPC fails the call it names** with
  `MalformedResponse`, and is ignored when it names none. The connection stays open.
- **Text that is not JSON ends the connection.** The calls in flight fail with
  `MalformedResponse`.
- **An error with no id goes to the call in flight** when there is exactly one. With several
  waiting, it is ignored.
- **Closed with its scope.** The connection closes when the program the layer was provided to
  ends.

[Connection lifecycle](https://ethect.dev/concepts/connection-lifecycle/) walks through these cases in order.

## Errors

| Error | Reason | When |
| --- | --- | --- |
| `TransportError` | `Unreachable` | the connection cannot be opened, the last one ended within 5 seconds of opening and the next is not open yet, or the reconnect schedule has ended |
| `TransportError` | `ConnectionLost` | the connection closed while the call was in flight, or the keep-alive went unanswered |
| `TransportError` | `MalformedResponse` | the node answered the call with something that is not JSON-RPC, or sent text that is not JSON while the call was in flight |
| `TransportError` | `Unserializable` | the request cannot be written as JSON. Nothing was sent. |
