# `Julep`
[🔗](https://github.com/RiverFinancial/julep/blob/v0.1.0-rc.1/lib/julep.ex#L1)

A behaviour for WebSocket clients built on [Mint](https://hexdocs.pm/mint) and
`Mint.WebSocket`.

`use Julep` to build a WebSocket client as a `GenServer`.

Your module keeps the usual `c:handle_call/3`, `c:handle_cast/2` and
`c:handle_info/2`, and gains `c:handle_frame/2` for frames from the server and
`c:handle_disconnect/2` to decide whether to reconnect. Julep handles the
protocol, dialing the server, proxying if you ask, upgrading the connection,
answering pings and completing the closing handshake.

    defmodule MyApp.Ticker do
      use Julep

      def start_link(url), do: Julep.start_link(__MODULE__, url: url)

      @impl Julep
      def init(_arg), do: {:ok, %{}}

      @impl Julep
      def handle_connect(state),
        do: {:noreply, state, {:send, {:text, ~s({"subscribe":"ticker"})}}}

      @impl Julep
      def handle_frame({:text, json}, state) do
        IO.puts(json)
        {:noreply, state}
      end

      @impl Julep
      def handle_disconnect(_reason, state), do: {:reconnect, state}
    end

## Lifecycle

### Opening a WebSocket

Use `start_link/2` to start a client and connect in the background. To wait
for the connection, call `connect/2` instead. Both take the options listed
under `start_link/2`. To wait on a client that is already running, call
`wait_until_connected/2`.

To run a client under a supervisor, define `start_link/1` as `MyApp.Ticker`
does. `use Julep` defines a `child_spec/1` that calls it:

    children = [{MyApp.Ticker, "wss://example.com/ws"}]

If you need to authenticate or subscribe, send the frames from
`c:handle_connect/1`, which runs every time the WebSocket opens, including
after a reconnect. To add headers to the upgrade request, such as a signature
that must be fresh on every attempt, define `c:prepare/3`.

### Sending and receiving frames

`c:handle_frame/2` receives each text and binary frame from the server. Julep
handles pings, pongs and close frames itself.

To send from a callback, return `{:send, frame_or_frames}` as the last element
of its result. To send from another process, call `send/3`, or `cast/2` to
not wait for the write.

Send only while connected. At any other time, including between reconnect
attempts and after the client has sent a close, `send/3` returns an error and
`cast/2` drops the frames. A callback that sends then raises
`Julep.NotConnectedError` and crashes the client.

### Closing a WebSocket

To close the WebSocket, return `{:send, :close}` from a callback.
`c:handle_disconnect/2` then receives `:local_close` once the server answers,
or `:close_timeout` if it does not answer within `:close_timeout`. When the
server closes first, Julep answers and calls `c:handle_disconnect/2` with
`:remote_close`.

Closing does not stop the client. To stop it, return `{:stop, reason, state}`
from `c:handle_disconnect/2`. Returning a stop from any other callback stops
the client without the closing handshake.

### Staying connected

Julep never reconnects on its own. To reconnect after a failed attempt or a
dropped connection, return `{:reconnect, state}` from `c:handle_disconnect/2`.
The next attempt starts after the `:backoff` delay.

To automatically drop a connection that has gone quiet, set `:idle_timeout`.
Set `:keepalive` to a shorter interval, so the heartbeats keep a healthy
connection open.

## Callbacks

`c:init/1`, `c:handle_frame/2` and `c:handle_disconnect/2` are required.
`use Julep` defines the others to do nothing, except `c:handle_call/3`, which
stops the client with `{:bad_call, request}` as a GenServer does.

`c:handle_connect/1`, `c:handle_frame/2`, `c:handle_cast/2` and
`c:handle_info/2` return a `t:result/0`.

## Proxies

To connect through an HTTP or HTTPS proxy, build one with `Julep.Proxy.new/2`
and pass it as the `:proxy` option. Julep never reads the environment itself,
so to respect `https_proxy`, `no_proxy` and the like, call
`Julep.Proxy.resolve!/2` and pass on the result.

> #### Warning {: .warning}
>
> Only `wss://` URLs can be tunnelled. A client given a proxy and a `ws://`
> URL fails every attempt to connect, with
> `{:tunnel_error, :plaintext_not_supported}`.

## Telemetry

Julep emits events for connection attempts, disconnects and frames. See
`Julep.Telemetry`.

# `action`

```elixir
@type action() :: {:send, frame() | [frame()]}
```

What a callback can ask Julep to do once it returns: send one frame, or a
list of frames in order.

# `disconnect_reason`

```elixir
@type disconnect_reason() ::
  :connect_timeout
  | :idle_timeout
  | :remote_close
  | :local_close
  | :close_timeout
  | {:open_error, reason :: term()}
  | {:tunnel_failed, status :: pos_integer()}
  | {:tunnel_error, reason :: term()}
  | {:upgrade_failed, status :: pos_integer()}
  | {:upgrade_error, reason :: term()}
  | {:transport_error, reason :: term()}
  | {:ws_error, reason :: term()}
```

Why a connection attempt failed or a connection ended.

  * `:connect_timeout` - the attempt took longer than `:connect_timeout`.
  * `:idle_timeout` - nothing arrived from the server for `:idle_timeout`.
  * `:remote_close` - the server closed the WebSocket.
  * `:local_close` - the client sent a close frame and the server answered it.
  * `:close_timeout` - the client sent a close frame and the server did not
    answer within `:close_timeout`.
  * `{:open_error, reason}` - the dial failed, for example with
    `:econnrefused` or a TLS alert.
  * `{:tunnel_failed, status}` - the proxy answered the `CONNECT` request
    with an HTTP status other than 2xx.
  * `{:tunnel_error, reason}` - the tunnel through the proxy failed for
    another reason. A `ws://` URL fails with `:plaintext_not_supported`,
    since only `wss://` URLs can be tunnelled.
  * `{:upgrade_failed, status}` - the server answered the upgrade with an
    HTTP status other than 101.
  * `{:upgrade_error, reason}` - the upgrade failed for another reason.
  * `{:transport_error, reason}` - the socket failed or closed, or a write
    blocked for longer than `:send_timeout`.
  * `{:ws_error, reason}` - the server sent a frame a client must reject.

# `frame`

```elixir
@type frame() ::
  {:text, iodata()}
  | {:binary, iodata()}
  | :ping
  | {:ping, iodata()}
  | :pong
  | {:pong, iodata()}
  | :close
  | {:close, iodata()}
  | {:close, code :: non_neg_integer(), reason :: iodata()}
```

A frame a client can send.

  * `{:text, data}` and `{:binary, data}` carry the application's messages.
  * `:ping` and `{:ping, data}` ask the server for a pong. The `:keepalive`
    option sends them on a timer.
  * `:pong` and `{:pong, data}` answer a ping. Julep answers the server's
    pings itself, so a client rarely needs to.
  * `:close` and `{:close, reason}` start the closing handshake with status
    1000 (normal closure), and `{:close, code, reason}` picks the status
    code.

# `option`

```elixir
@type option() ::
  {:url, String.t()}
  | {:arg, term()}
  | {:name, GenServer.name()}
  | {:tls_opts, keyword()}
  | {:proxy, Julep.Proxy.t() | nil}
  | {:subprotocols, [String.t()]}
  | {:connect_timeout, pos_integer()}
  | {:send_timeout, pos_integer()}
  | {:keepalive, pos_integer() | nil}
  | {:idle_timeout, pos_integer() | nil}
  | {:close_timeout, pos_integer()}
  | {:backoff, (failures :: pos_integer() -&gt; non_neg_integer())}
```

# `phase`

```elixir
@type phase() ::
  :initial
  | :connecting
  | :upgrading
  | :connected
  | :closing
  | :reconnecting
  | :closed
```

Where a client is in its lifecycle.

  * `:initial` - started, not yet connecting.
  * `:connecting` - dialing the server, or the proxy.
  * `:upgrading` - waiting for the server to accept the upgrade.
  * `:connected` - the WebSocket is open.
  * `:closing` - the client sent a close and is waiting for the server's.
  * `:reconnecting` - waiting out the backoff delay.
  * `:closed` - stopping.

# `result`

```elixir
@type result() ::
  {:noreply, state :: term()}
  | {:noreply, state :: term(), action()}
  | {:stop, reason :: term(), state :: term()}
```

What `c:handle_connect/1`, `c:handle_frame/2`, `c:handle_cast/2` and
`c:handle_info/2` return.

  * `{:noreply, state}` - carries on.
  * `{:noreply, state, {:send, frame_or_frames}}` - sends them, then carries
    on.
  * `{:stop, reason, state}` - stops the client.

# `stage`

```elixir
@type stage() :: :upgrade | :connect
```

The request `c:prepare/3` shapes.

  * `:upgrade` - the WebSocket upgrade request.
  * `:connect` - the `CONNECT` request that opens a tunnel through a proxy.

# `handle_call`
*optional* 

```elixir
@callback handle_call(request :: term(), GenServer.from(), state :: term()) ::
  {:reply, reply :: term(), state :: term()}
  | {:reply, reply :: term(), state :: term(), action()}
  | {:noreply, state :: term()}
  | {:noreply, state :: term(), action()}
  | {:stop, reason :: term(), reply :: term(), state :: term()}
  | {:stop, reason :: term(), state :: term()}
```

Handles a call to the client process, as in `c:GenServer.handle_call/3`.

# `handle_cast`
*optional* 

```elixir
@callback handle_cast(request :: term(), state :: term()) :: result()
```

Handles a cast to the client process, as in `c:GenServer.handle_cast/2`.

# `handle_connect`
*optional* 

```elixir
@callback handle_connect(state :: term()) :: result()
```

Runs when the WebSocket upgrade succeeds, before any frame from the server is
handled.

This is the place to send a subscription or an authentication frame, since it
runs again after every reconnect.

# `handle_disconnect`

```elixir
@callback handle_disconnect(disconnect_reason(), state :: term()) ::
  {:reconnect, state :: term()} | {:stop, reason :: term(), state :: term()}
```

Runs when a connection attempt fails or an established connection drops.

Return `{:reconnect, state}` to try again after the backoff delay, or
`{:stop, reason, state}` to stop the client.

# `handle_frame`

```elixir
@callback handle_frame({:text | :binary, binary()}, state :: term()) :: result()
```

Handles a text or binary frame from the server.

Julep answers pings and handles close frames itself, so control frames never
reach this callback. Frames that arrive after the client has sent a close are
dropped.

# `handle_info`
*optional* 

```elixir
@callback handle_info(msg :: term(), state :: term()) :: result()
```

Handles any other message to the client process.

Julep's own messages, including socket traffic and timers, never reach this
callback.

# `init`

```elixir
@callback init(arg :: term()) :: {:ok, state :: term()}
```

Builds the initial state from the `:arg` option.

Runs in the client process before the first connection attempt.

# `prepare`
*optional* 

```elixir
@callback prepare(stage(), Julep.Request.t(), state :: term()) :: Julep.Request.t()
```

Shapes the request for `stage` before every connection attempt.

Defining this callback replaces the default for every stage, so return the
request unchanged for any stage you don't shape. See `Julep.Request`.

# `terminate`
*optional* 

```elixir
@callback terminate(reason :: term(), state :: term()) :: term()
```

Runs when the client stops, before the connection is closed.

# `cast`

```elixir
@spec cast(GenServer.server(), frame() | [frame()]) :: :ok
```

Sends a frame, or a list of frames in order, without waiting.

The frames are written if the WebSocket is open and dropped otherwise.

Returns `:ok` immediately.

# `connect`

```elixir
@spec connect(module(), [option() | {:timeout, timeout()}]) ::
  {:ok, pid()} | {:error, term()}
```

Starts a client process linked to the caller and waits for its first
connection attempt.

Returns `{:ok, pid}` once the WebSocket is connected. If the first attempt
fails, returns `{:error, reason}` with the reason `c:handle_disconnect/2`
received, and stops the client process normally, even if
`c:handle_disconnect/2` asked to reconnect.

Takes the options of `start_link/2`, plus `:timeout`, how long to wait in
milliseconds. It defaults to five seconds beyond `:connect_timeout`, so the
attempt gives up first.

# `send`

```elixir
@spec send(GenServer.server(), frame() | [frame()], timeout()) ::
  :ok | {:error, {:not_connected, phase()} | disconnect_reason()}
```

Sends a frame, or a list of frames in order, and waits until they are written.

Returns `:ok` once the frames are written to the socket. Returns
`{:error, {:not_connected, phase}}` if the WebSocket is not open, where
`phase` is a `t:phase/0`. If a write fails, returns `{:error, reason}` with a
`t:disconnect_reason/0`, and the client disconnects. Frames are written until
one fails, so the start of a list may already have been sent.

This is for other processes. A callback sends by returning
`{:send, frame_or_frames}`.

# `start_link`

```elixir
@spec start_link(module(), [option()]) :: GenServer.on_start()
```

Starts a client process linked to the caller.

Returns as soon as the process has started. The first connection attempt runs
in the background, and `c:handle_connect/1` runs when it succeeds.

## Options

  * `:url` - the `ws://` or `wss://` URL to connect to. Required.
  * `:arg` - passed to `c:init/1`. Defaults to `nil`.
  * `:name` - registers the process, as for `GenServer.start_link/3`.
  * `:tls_opts` - TLS options for a `wss://` server, merged over Mint's
    defaults, which verify the server against the system trust store.
  * `:proxy` - a `Julep.Proxy` to tunnel through. Only `wss://` URLs can be
    proxied. Defaults to `nil`, which connects directly.
  * `:subprotocols` - WebSocket subprotocols to request, most preferred first.
  * `:connect_timeout` - how long a connection attempt may take, from the
    dial to the end of the upgrade, in milliseconds. Defaults to 30 seconds.
  * `:send_timeout` - how long a single socket write may block before the
    connection is treated as broken, in milliseconds. Defaults to 10 seconds.
  * `:keepalive` - how often to ping the server while connected, in
    milliseconds. Defaults to `nil`, which sends no pings.
  * `:idle_timeout` - how long the connection may go without a frame from the
    server before it is dropped with `:idle_timeout`, in milliseconds. Any
    frame counts, including the pong that answers a keepalive ping. Defaults
    to `nil`, which never drops an idle connection.
  * `:close_timeout` - how long to wait for the server to answer a close frame
    the client sent, in milliseconds. Defaults to 5 seconds.
  * `:backoff` - a function from the number of consecutive failures, starting
    at 1, to the delay before the next attempt in milliseconds. A dropped
    connection counts as a failure, and a successful connection resets the
    count. Defaults to doubling from one second up to 30 seconds.

# `wait_until_connected`

```elixir
@spec wait_until_connected(GenServer.server(), timeout()) :: :ok | {:error, term()}
```

Waits for the client's current connection attempt to finish.

Returns `:ok` once the WebSocket is connected, or `{:error, reason}` with the
reason `c:handle_disconnect/2` received if the attempt fails. While the client
is neither connected nor connecting, for example between reconnect attempts,
it returns `{:error, {:not_connecting, phase}}`, where `phase` is a
`t:phase/0`.

A client started with `start_link/2` whose first attempt fails can stop
before this call arrives. Use `connect/2` to start the client and wait for it
to avoid this.

The default timeout is five seconds beyond the default `:connect_timeout`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
