# Custom transports

A transport is a Layer that provides one function, request. Wrap an existing transport to log or fall back, or write one from scratch.

A transport is a `Layer` that provides the [`Transport`](https://ethect.dev/reference/transport/#transport)
service, which is one function: `request(method, params)`. Anything that can answer that
function is a transport.

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

/** Answers from a table, without a network. */
const Canned = Layer.succeed(Transport.Transport)({
  request: (method) =>
    method === "eth_chainId"
      ? Effect.succeed("0x1")
      : Effect.fail(
          RpcError.fromWire({ code: -32601, message: `Method ${method} not found` }),
        ),
});

const chainId = Eth.chainId().pipe(Effect.provide(Canned)); // 1
```

## The contract

`request` receives the wire name and the encoded params, and returns the `result` of the
JSON-RPC response as the node sent it. Methods encode before and decode after: a transport
never sees a `bigint`.

| `request` must | How |
| --- | --- |
| return the raw `result` | `Effect.succeed(result)` |
| fail with the node's error | `Effect.fail(RpcError.fromWire({ code, message, data }))` |
| fail when no answer came back | `Effect.fail(new TransportError.TransportError({ reason, message }))` |
| never throw | wrap what can throw in `Effect.try` or `Effect.tryPromise` |

`RpcError.fromWire` classifies the error into a [reason](https://ethect.dev/reference/errors/rpc-error/#reasons),
so `Effect.catchReason` works over your transport as over the built-in ones.

## Wrap a transport

Most custom transports add something to an existing one. Take the inner `Transport` from the
context and provide a new one.

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

/** Logs every call of the transport it wraps. */
const logged = <E, R>(inner: Layer.Layer<Transport.Transport, E, R>) =>
  Layer.effect(Transport.Transport)(
    Effect.map(Transport.Transport, (transport) => ({
      request: (method: string, params: Transport.Params) =>
        transport.request(method, params).pipe(
          Effect.tap(() => Effect.log(`${method} ok`)),
          Effect.tapError((error) => Effect.log(`${method} failed: ${error._tag}`)),
        ),
    })),
  ).pipe(Layer.provide(inner));

const Http = Transport.http("http://127.0.0.1:8545").pipe(
  Layer.provide(FetchHttpClient.layer),
);

const LoggedHttp = logged(Http);
```

`logged(Http)` is a transport like any other. The same shape adds a rate limit, a cache for
immutable results, or metrics.

## Fall back to a second endpoint

The library has no fallback transport. It is a wrapper around two.

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

/** Sends to `primary`, and to `secondary` when `primary` gives no answer. */
const fallback = <E1, R1, E2, R2>(
  primary: Layer.Layer<Transport.Transport, E1, R1>,
  secondary: Layer.Layer<Transport.Transport, E2, R2>,
) =>
  Layer.effect(Transport.Transport)(
    Effect.gen(function* () {
      const first = Context.get(yield* Layer.build(primary), Transport.Transport);
      const second = Context.get(yield* Layer.build(secondary), Transport.Transport);
      return {
        request: (method: string, params: Transport.Params) =>
          first.request(method, params).pipe(
            Effect.catchTag("TransportError", () => second.request(method, params)),
          ),
      };
    }),
  );

const http = (url: string) =>
  Transport.http(url).pipe(Layer.provide(FetchHttpClient.layer));

const Resilient = fallback(
  http("https://rpc.example.com"),
  http("https://rpc.example.org"),
);
```

Only a `TransportError` falls back. An `RpcError` is an answer: the second node would say the
same.

> **Caution: A fallback can send twice**
>
> After a `TransportError` other than `Unreachable`, the first node may have executed the call.
> Falling back on `eth_sendTransaction` can then send a second transaction. Filter on `method`,
> or on the reason, if the transport carries calls that send.

## Serve subscriptions

A transport that can push also provides
[`Subscriptions`](https://ethect.dev/reference/transport/#subscriptions): one function, `subscribe(params)`, that
returns a `Stream` of raw items. `params` are those of `eth_subscribe`, the kind first.

### Over a connection that pushes

[`Transport.subscriptionsOver`](https://ethect.dev/reference/transport/subscriptions-over/) builds the service
from three things: a way to send calls, the items the connection pushes, and a scope.

This transport runs over anything that carries JSON messages both ways, such as a
`MessagePort` or a tunnel.

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

/** Carries JSON messages both ways. */
interface Channel {
  readonly send: (message: unknown) => void;
  /** Calls `listener` with each message received. Returns how to stop. */
  readonly listen: (listener: (message: any) => void) => () => void;
}

type Call = Deferred.Deferred<unknown, Transport.Error>;

/** A transport over a channel that can push. */
const overChannel = (channel: Channel) =>
  Layer.effectContext(
    Effect.gen(function* () {
      const scope = yield* Effect.scope;
      const items = yield* PubSub.unbounded<Transport.PushedItem>();
      const pending = new Map<unknown, Call>();
      let nextId = 0;

      // An answer completes the call with its id. A notification is an item.
      yield* Effect.acquireRelease(
        Effect.sync(() =>
          channel.listen((message) => {
            const call = pending.get(message.id);
            if (call !== undefined) {
              Deferred.doneUnsafe(call, outcomeOf(message));
            } else if (message.method === "eth_subscription") {
              PubSub.publishUnsafe(items, message.params);
            }
          }),
        ),
        (stop) => Effect.sync(stop),
      );

      const request = (method: string, params: Transport.Params) =>
        Effect.suspend(() => {
          const id = nextId++;
          const call: Call = Deferred.makeUnsafe();
          pending.set(id, call);
          return Effect.try({
            try: () => channel.send({ jsonrpc: "2.0", id, method, params }),
            catch: (cause) =>
              new TransportError.TransportError({
                reason: { _tag: "Unserializable" },
                message: "The channel refused the message",
                cause,
              }),
          }).pipe(
            Effect.andThen(Deferred.await(call)),
            Effect.ensuring(Effect.sync(() => pending.delete(id))),
          );
        });

      return Context.make(Transport.Transport, { request }).pipe(
        Context.add(
          Transport.Subscriptions,
          Transport.subscriptionsOver({ request, items, scope }),
        ),
      );
    }),
  );

const outcomeOf = (message: any): Exit.Exit<unknown, Transport.Error> =>
  "error" in message
    ? Exit.fail(RpcError.fromWire(message.error))
    : Exit.succeed(message.result);
```

`Eth.subscribe.newHeads()` now runs over `overChannel(channel)`, like every other
subscription kind.

| You write | `subscriptionsOver` does |
| --- | --- |
| `request`: send a call, match its answer by id | sends `eth_subscribe`, and `eth_unsubscribe` when a stream ends |
| `items`: publish every notification you receive | gives each stream the items of its own subscription id |
| `scope`: the scope of your layer | runs there the `eth_unsubscribe` that outlives a stream |

A transport that reconnects also passes `connections` and `isLive`, and its subscriptions are
issued again on each new connection. See
[`Transport.subscriptionsOver`](https://ethect.dev/reference/transport/subscriptions-over/#a-connection-that-is-replaced).

### By polling

A transport that cannot push can still provide the service. This layer gives
`Eth.subscribe.newHeads()` to HTTP by polling the block number.

```ts
import { Effect, Layer, Schedule, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { RpcError, Transport } from "@ethect/core";

/** `newHeads` for a transport that cannot push: polls the block number. */
const PolledHeads = Layer.effect(Transport.Subscriptions)(
  Effect.map(Transport.Transport, (transport) => {
    const heads = Stream.fromEffectSchedule(
      transport.request("eth_blockNumber", []),
      Schedule.spaced("2 seconds"),
    ).pipe(
      Stream.changes,
      Stream.drop(1), // the block that was already there
      Stream.mapEffect((number) => transport.request("eth_getBlockByNumber", [number, false])),
    );
    /** One kind is served. Any other is refused, as a node refuses a kind it does not have. */
    const served = <A>(
      [kind]: ReadonlyArray<unknown>,
      stream: Stream.Stream<A, Transport.Error>,
    ): Stream.Stream<A, Transport.Error> =>
      kind === "newHeads"
        ? stream
        : Stream.fail(RpcError.fromWire({ code: -32601, message: `Cannot poll ${String(kind)}` }));
    return {
      subscribe: (params) => served(params, heads),
      // no node takes anything here: a subscription is in place as soon as it is asked for
      opened: (params) => served(params, Stream.make({ id: "polled", items: heads })),
    };
  }),
);

const Http = Transport.http("http://127.0.0.1:8545").pipe(
  Layer.provide(FetchHttpClient.layer),
);

// Provides `Transport` and `Subscriptions`: programs that subscribe now run over HTTP.
const HttpWithHeads = Layer.provideMerge(PolledHeads, Http);
```

A `Subscriptions` you write by hand has two members.

| Member | What to write |
| --- | --- |
| `subscribe` | the items, as a stream |
| [`opened`](https://ethect.dev/reference/transport/#opened) | one `{ id, items }` each time the subscription is in place. Where a node answers `eth_subscribe`, emit it when it has answered, and again on each connection. Where nothing is taken by a node, as here, emit it once, at once. |

`Block.watch` and `Ev.watch` read `opened`: they read the node when it emits, then take its
`items`. [`Transport.subscriptionsOver`](https://ethect.dev/reference/transport/subscriptions-over/) writes both
for a connection that pushes.

The typed kinds decode what `subscribe` emits, so the items must have the wire shape of the
kind: here a block, whose header fields `newHeads` keeps.

For new blocks you do not need this: [`Block.watch`](https://ethect.dev/reference/block/) polls a transport that
cannot push by itself.

## Behavior

- **A transport is a value.** Wrappers compose: `logged(fallback(a, b))` is a transport.
- **One instance per build.** State you keep in the layer, such as a counter or a cache, lives
  as long as the layer: see [Provide it once](https://ethect.dev/guides/transports/#provide-it-once).
- **`params` is an array or an object.** A method defined with `Method.makeByName` passes an
  object: forward `params` as you received it.

## Next steps

- [`Transport`](https://ethect.dev/reference/transport/): the two services and their types.
- [`Transport.subscriptionsOver`](https://ethect.dev/reference/transport/subscriptions-over/): the fields of a
  push connection and what the streams do when it drops.
- [`RpcError`](https://ethect.dev/reference/errors/rpc-error/#fromwire) and
  [`TransportError`](https://ethect.dev/reference/errors/transport-error/): what a transport fails with.
- [Custom methods](https://ethect.dev/rpc/guides/custom-methods/), in the JSON-RPC layer: the other half, what
  is sent.
- [`MockProvider`](https://ethect.dev/reference/testing/mock-provider/): often the transport a test needs.
