# Julep

WebSocket clients for Elixir, built on [Mint](https://github.com/elixir-mint/mint)
and [Mint.WebSocket](https://github.com/elixir-mint/mint_web_socket).

A Julep client is a GenServer that speaks WebSocket. It handles the nuances of
the protocol for you, from the upgrade to the closing handshake, and comes with
what a long-lived connection needs:

  * Sends and receives text and binary frames.
  * Reconnects with configurable backoff.
  * Sends keepalive heartbeats and drops idle connections.
  * Lets you sign or shape the request on every connection attempt.
  * Tunnels through HTTP and HTTPS proxies.
  * Emits `:telemetry` for connection attempts, disconnects and frames.
  * Applies stricter frame checks than `Mint.WebSocket`, per RFC 6455.

Julep is at a release candidate, and its API may change before 0.1.0.

## Installation

Requires Elixir 1.17 or later. Tested on OTP 27 to 29.

```elixir
def deps do
  [
    {:julep, "~> 0.1.0-rc.1"}
  ]
end
```

## Usage

```elixir
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}

  @impl Julep
  def prepare(:upgrade, request, _state) do
    timestamp = Integer.to_string(System.os_time(:second))
    %{request | headers: [{"x-timestamp", timestamp} | request.headers]}
  end

  def prepare(_stage, request, _state), do: request
end
```

Start it under a supervisor:

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

Or start it and wait for the first connection:

```elixir
{:ok, pid} = Julep.connect(MyApp.Ticker, url: "wss://example.com/ws")
```

## Limits

  * HTTP/1.1 only.
  * No WebSocket extensions, such as per-message compression.
  * No `ws://` through a proxy. Only `wss://` URLs can be tunnelled.
  * No queueing. A frame sent while disconnected is never held for later.

## Documentation

The documentation is on [HexDocs](https://hexdocs.pm/julep):

  * [`Julep`](https://hexdocs.pm/julep/Julep.html) - the lifecycle, the
    callbacks and every option.
  * [`Julep.Proxy`](https://hexdocs.pm/julep/Julep.Proxy.html) - connecting
    through a proxy, and finding one in the environment.
  * [`Julep.Relay`](https://hexdocs.pm/julep/Julep.Relay.html) - a ready-made
    client that relays frames to another process.
  * [`Julep.Telemetry`](https://hexdocs.pm/julep/Julep.Telemetry.html) - the
    events and what they measure.

## License

Julep is released under the MIT License. See [LICENSE](https://github.com/RiverFinancial/julep/blob/main/LICENSE).
