# Connection lifecycle

A socket transport holds one connection for every call and subscription. What happens to each when the connection drops, how it comes back, and what a subscription misses in between.

A socket transport, WebSocket or IPC, holds one connection for every call and subscription.
This page says what happens to each of them when that connection drops, and how to deal with
what a subscription misses in between.

HTTP has no connection to lose: each call is a request of its own. An EIP-1193 provider owns
its connection, and the transport does not manage it.

## One connection

```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* () {
  // both travel on the same socket, at the same time
  const watcher = yield* Eth.subscribe.newHeads().pipe(
    Stream.runDrain,
    Effect.forkScoped,
  );
  return yield* Eth.chainId();
}).pipe(Effect.scoped, Effect.provide(WebSocket));
```

The connection opens when the layer is built and closes when the program it was provided to
ends. Each request carries an id, so answers can come back in any order.

## What happens when

| Situation | A call in flight | A new call | A subscription |
| --- | --- | --- | --- |
| the connection is open | is answered | is sent | streams |
| a connection that lasted 5 seconds or more drops | fails with `ConnectionLost` | waits for the new connection, opened at once | waits, then is issued again |
| a connection drops within 5 seconds of opening | fails with `ConnectionLost` | fails at once with `Unreachable` | waits, then is issued again |
| an attempt to connect fails | | fails at once with `Unreachable` | waits |
| the reconnect schedule has ended | | fails with `Unreachable` | fails with `Unreachable` |

- **A call is never sent twice.** One that was in flight when the connection dropped fails.
  The transport cannot know whether the node executed it, so repeating it is your decision.
- **Calls do not queue while the node is away.** They fail at once, so a program finds out
  instead of hanging. A URL the socket cannot use counts as a node that is away.
- **Subscriptions do wait.** A stream stays open across the outage and carries on when the
  connection is back. One whose `eth_subscribe` was not answered yet is issued again too.

## Reconnecting

A connection that worked is replaced at once. One that did not is retried on the `reconnect`
schedule.

| The connection | The next attempt |
| --- | --- |
| lasted 5 seconds or more | at once, and the schedule starts over |
| ended within 5 seconds of opening | after the schedule's next pause |
| could not be opened | after the schedule's next pause |

The default schedule is an exponential backoff that starts at 500 ms, is capped at 5 s, and
never ends. A node that accepts connections and closes them is therefore dialled at that pace,
not in a loop.

```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", {
  // one attempt per second, ten times, then give up
  reconnect: Schedule.max([Schedule.spaced("1 second"), Schedule.recurs(10)]),
}).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
```

When the schedule ends, the transport gives up for good: every call and every subscription
fails with `Unreachable` from then on. Build a new transport to try again.

## What the node sends

| The node sends | The transport |
| --- | --- |
| an answer whose id is a call's, as a number or as text | completes that call |
| JSON that is not JSON-RPC, with the id of a call | fails that call with `MalformedResponse` |
| JSON that is not JSON-RPC, with no id of a call | ignores it |
| an error with no id, while exactly one call is in flight | fails that call with the error |
| text that is not JSON | ends the connection: the calls in flight fail with `MalformedResponse` |

## Keep-alive

A WebSocket transport calls `net_version` every 30 seconds. An idle connection behind a proxy
stays open, and a node that stopped answering is noticed.

| The node | The transport |
| --- | --- |
| answers, with a result or an error | keeps the connection |
| does not answer before the next keep-alive is due | closes the connection and reconnects |

`keepAlive: false` turns it off, and a duration changes the interval. IPC has no keep-alive
unless you set one.

## The gap

When a subscription is issued again on a new connection, the node starts pushing from that
moment. What it emitted while the connection was down is not replayed, and the stream does not
mark the place.

The transport marks it. [`opened`](https://ethect.dev/reference/transport/#opened), on the `Subscriptions`
service, says each time the node takes a subscription: when it answers `eth_subscribe` on the
connection that is open, then on each one that replaces it.

| You watch | To miss nothing |
| --- | --- |
| new blocks | use [`Block.watch`](https://ethect.dev/reference/block/): on each connection it reads the latest block once the node has the subscription, and gives the blocks mined in between, in order, up to 256 of them |
| events | use [`Ev.watch`](https://ethect.dev/reference/ev/watch/): on each connection it takes back the events a reorg replaced meanwhile, then reads the ones it missed |
| anything else | read what you missed each time `opened` says the node took the subscription, as below |

```ts
import { Effect, Stream } from "effect";
import { Transport } from "@ethect/core";

/** What a subscription pushes, with `catchUp` read first each time the node takes it. */
const withCatchUp = <A, E, R>(params: ReadonlyArray<unknown>, catchUp: Effect.Effect<A, E, R>) =>
  Stream.unwrap(
    Effect.map(Transport.Subscriptions, ({ opened }) =>
      opened(params).pipe(
        // the node has the subscription: nothing happens between this read and what it pushes
        Stream.switchMap(({ items }) => Stream.concat(Stream.fromEffect(catchUp), items)),
      ),
    ),
  );
// Stream<unknown, E | Transport.Error, R | Subscriptions>
```

The order is what matters. A connection is established before any subscription is taken on
it, and a read made then can be followed by a block that is neither read nor pushed. The
answer of the node to `eth_subscribe` is when it starts pushing: read after it.

With a raw `newHeads` subscription, the stream itself shows the gap: block numbers stop being
consecutive.

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

const headsWithGaps = Eth.subscribe.newHeads().pipe(
  Stream.mapAccum(
    () => undefined as bigint | undefined,
    (last, head) => {
      const missed =
        last === undefined || head.number === null ? 0n : head.number - last - 1n;
      return [head.number ?? last, [{ head, missed }]] as const;
    },
  ),
  Stream.runForEach(({ head, missed }) =>
    missed > 0n
      ? Effect.log(`missed ${missed} block(s) before ${head.number}`)
      : Effect.void,
  ),
);
```

For logs, nothing in the stream tells you. Three ways to not miss any:

| Approach | How |
| --- | --- |
| drive everything from blocks | watch the blocks, and for each new one read its logs with [`Eth.getLogs`](https://ethect.dev/rpc/eth/get-logs/) over the blocks since the last one you handled |
| read the gap when the node takes the subscription again | each time `opened` emits, read with `Eth.getLogs` from the last block you handled. It is what [`Ev.subscription`](https://ethect.dev/reference/ev/source/#subscription) does. |
| make the stream fail instead | give the transport a `reconnect` schedule that ends, catch the failure, read what you missed with `Eth.getLogs`, and start again |

```ts
import { Effect, Stream } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

/** Every log of a contract from block `from` on, whatever the connection does. */
const logsSince = (contract: Address.Address, from: bigint) =>
  Eth.subscribe.newHeads().pipe(
    Stream.mapAccumEffect(
      () => from,
      (next, head) =>
        head.number === null || head.number < next
          ? Effect.succeed([next, []] as const)
          : Effect.map(
              Eth.getLogs({ address: contract, fromBlock: next, toBlock: head.number }),
              (logs) => [head.number! + 1n, logs] as const,
            ),
    ),
  );
// Stream<Log, Method.Error, Subscriptions | Transport>
```

The headers only say when to look. The logs come from `eth_getLogs` over an explicit range of
blocks, so a missed header delays logs and never loses them.

## EIP-1193

`Transport.eip1193` does not reconnect and does not resubscribe: the wallet's provider owns the
connection. Follow [`Eip1193.disconnect`](https://ethect.dev/reference/eip1193/#disconnect) and
[`Eip1193.connect`](https://ethect.dev/reference/eip1193/#connect) to know when it is away, and open your
subscriptions again when it comes back.

## Next steps

- [`Transport.webSocket`](https://ethect.dev/reference/transport/web-socket/) and
  [`Transport.ipc`](https://ethect.dev/reference/transport/ipc/): the `reconnect` and `keepAlive` options.
- [Subscriptions](https://ethect.dev/rpc/guides/subscriptions/), in the JSON-RPC layer: opening, consuming and
  stopping a stream.
- [`TransportError`](https://ethect.dev/reference/errors/transport-error/): `ConnectionLost`, `Unreachable` and
  when a call may have been executed.
