# Transport.subscriptionsOver

Builds the [`Subscriptions`](https://ethect.dev/reference/transport/#subscriptions) service of a transport of
your own, from a way to send calls and the items its connection pushes. It is what the socket
and EIP-1193 transports use.

## Usage

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

/** A transport from a `request` function and the items its connection pushes. */
const pushTransport = (
  request: Transport.Transport["Service"]["request"],
  items: PubSub.PubSub<Transport.PushedItem>,
) =>
  Layer.effectContext(
    Effect.gen(function* () {
      const scope = yield* Effect.scope;
      const subscriptions = Transport.subscriptionsOver({ request, items, scope });
      return Context.make(Transport.Transport, { request }).pipe(
        Context.add(Transport.Subscriptions, subscriptions),
      );
    }),
  );
// Layer<Transport | Subscriptions>
```

Publish every pushed item to `items`, and `Eth.subscribe.newHeads()` runs over the layer.
[Custom transports](https://ethect.dev/guides/custom-transports/#over-a-connection-that-pushes) has a complete
transport written this way.

## Returns

`Transport.Subscriptions["Service"]`

The service itself, not a layer: an object with `subscribe(params)` and `opened(params)`. Put
it in the context your layer builds, next to `Transport`.

Its [`opened`](https://ethect.dev/reference/transport/#opened) says each time the node took a subscription: when
it answers the `eth_subscribe` this sends through `request`, on each connection your
`connections` announces. Without `connections` there is one connection, and it says so once.

## Parameters

### connection

- **Type:** `Transport.PushConnection`

| Field | Type | Description |
| --- | --- | --- |
| `request` | `(method, params) => Effect<unknown, Transport.Error>` | Sends a call over the connection. `eth_subscribe` and `eth_unsubscribe` go through it. |
| `items` | `PubSub<Transport.PushedItem>` | Every item the connection receives, whatever its subscription. |
| `scope` | `Scope` | Where the calls that outlive a stream run: its late `eth_unsubscribe`. |
| `connections` (optional) | `Stream<number, Transport.Error>` | For a connection that is replaced when it drops: an identifier each time one is established. Left out, there is one connection. |
| `isLive` (optional) | `(connection: number) => boolean` | Whether the connection with this identifier is still the live one. Left out, it is. |

A `Transport.PushedItem` is what a node pushes in an `eth_subscription` notification.

| Field | Type | Holds |
| --- | --- | --- |
| `subscription` | `string` | the id the node answered `eth_subscribe` with |
| `result` | `unknown` | the item, as the node sent it |

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

/** Hands a notification the connection received to the streams. */
const onNotification = (items: PubSub.PubSub<Transport.PushedItem>, message: any) =>
  message.method === "eth_subscription"
    ? // message.params is { subscription, result }
      PubSub.publish(items, message.params)
    : Effect.succeed(false);
```

### A connection that is replaced

Give `connections` and `isLive` when your transport reconnects. Every open subscription is
issued again on each identifier `connections` emits.

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

/** `live` holds the number of the open connection, `undefined` while there is none. */
const subscriptionsOf = (
  request: Transport.Transport["Service"]["request"],
  items: PubSub.PubSub<Transport.PushedItem>,
  scope: Scope.Scope,
  live: SubscriptionRef.SubscriptionRef<number | undefined>,
) =>
  Transport.subscriptionsOver({
    request,
    items,
    scope,
    connections: SubscriptionRef.changes(live).pipe(
      Stream.filter((connection) => connection !== undefined),
    ),
    isLive: (connection) => SubscriptionRef.getUnsafe(live) === connection,
  });
```

## Behavior

- **It listens before it asks.** A stream starts reading `items` before `eth_subscribe` is
  sent, so an item pushed right behind the node's answer is not missed.
- **Items are routed by id.** A stream gets the items whose `subscription` is the id the node
  answered its `eth_subscribe` with, and no other.
- **It unsubscribes when the stream ends.** `eth_unsubscribe` is sent with the id, in `scope`,
  and its failure is ignored. A stream that ended before the node answered is unsubscribed
  when the answer arrives.
- **An id belongs to its connection.** No `eth_unsubscribe` is sent for a connection that
  `isLive` says is gone.
- **A new connection takes over.** When `connections` emits, the subscription is issued again
  there. What the node emitted in between is not replayed: `opened` says when the node took
  the subscription there, which is when a program reads what was missed.
- **`connections` failing fails every stream** with that error: use it when no connection
  will be made again.
- **The answer must be a string.** Any other answer to `eth_subscribe` fails the stream with
  `MalformedResponse`.

## Errors

What the stream does when the `eth_subscribe` request fails:

| The request fails with | The stream |
| --- | --- |
| an `RpcError` | fails with it |
| `TransportError`, reason `ConnectionLost` or `Unreachable`, with `connections` given | stays open and waits for the next connection |
| the same, without `connections` | fails with it: there is no next connection |
| any other `TransportError` | fails with it |
