A behaviour for WebSocket clients built on Mint and
Mint.WebSocket.
use Julep to build a WebSocket client as a GenServer.
Your module keeps the usual handle_call/3, handle_cast/2 and
handle_info/2, and gains handle_frame/2 for frames from the server and
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}
endLifecycle
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
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 prepare/3.
Sending and receiving frames
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.
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 handle_disconnect/2 with
:remote_close.
Closing does not stop the client. To stop it, return {:stop, reason, state}
from 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 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
init/1, handle_frame/2 and handle_disconnect/2 are required.
use Julep defines the others to do nothing, except handle_call/3, which
stops the client with {:bad_call, request} as a GenServer does.
handle_connect/1, handle_frame/2, handle_cast/2 and
handle_info/2 return a 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
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.
Summary
Types
What a callback can ask Julep to do once it returns: send one frame, or a list of frames in order.
Why a connection attempt failed or a connection ended.
A frame a client can send.
Where a client is in its lifecycle.
What handle_connect/1, handle_frame/2, handle_cast/2 and
handle_info/2 return.
Callbacks
Handles a call to the client process, as in GenServer.handle_call/3.
Handles a cast to the client process, as in GenServer.handle_cast/2.
Runs when the WebSocket upgrade succeeds, before any frame from the server is handled.
Runs when a connection attempt fails or an established connection drops.
Handles a text or binary frame from the server.
Handles any other message to the client process.
Builds the initial state from the :arg option.
Shapes the request for stage before every connection attempt.
Runs when the client stops, before the connection is closed.
Functions
Sends a frame, or a list of frames in order, without waiting.
Starts a client process linked to the caller and waits for its first connection attempt.
Sends a frame, or a list of frames in order, and waits until they are written.
Starts a client process linked to the caller.
Waits for the client's current connection attempt to finish.
Types
What a callback can ask Julep to do once it returns: send one frame, or a list of frames in order.
@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:econnrefusedor a TLS alert.{:tunnel_failed, status}- the proxy answered theCONNECTrequest with an HTTP status other than 2xx.{:tunnel_error, reason}- the tunnel through the proxy failed for another reason. Aws://URL fails with:plaintext_not_supported, since onlywss://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.
@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.:pingand{:ping, data}ask the server for a pong. The:keepaliveoption sends them on a timer.:pongand{:pong, data}answer a ping. Julep answers the server's pings itself, so a client rarely needs to.:closeand{:close, reason}start the closing handshake with status 1000 (normal closure), and{:close, code, reason}picks the status code.
@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() -> non_neg_integer())}
@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.
@type result() :: {:noreply, state :: term()} | {:noreply, state :: term(), action()} | {:stop, reason :: term(), state :: term()}
What handle_connect/1, handle_frame/2, handle_cast/2 and
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.
@type stage() :: :upgrade | :connect
The request prepare/3 shapes.
:upgrade- the WebSocket upgrade request.:connect- theCONNECTrequest that opens a tunnel through a proxy.
Callbacks
@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 GenServer.handle_call/3.
Handles a cast to the client process, as in GenServer.handle_cast/2.
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.
@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.
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.
Handles any other message to the client process.
Julep's own messages, including socket traffic and timers, never reach this callback.
Builds the initial state from the :arg option.
Runs in the client process before the first connection attempt.
@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.
Runs when the client stops, before the connection is closed.
Functions
@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.
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 handle_disconnect/2
received, and stops the client process normally, even if
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.
@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 phase/0. If a write fails, returns {:error, reason} with a
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}.
@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 handle_connect/1 runs when it succeeds.
Options
:url- thews://orwss://URL to connect to. Required.:arg- passed toinit/1. Defaults tonil.:name- registers the process, as forGenServer.start_link/3.:tls_opts- TLS options for awss://server, merged over Mint's defaults, which verify the server against the system trust store.:proxy- aJulep.Proxyto tunnel through. Onlywss://URLs can be proxied. Defaults tonil, 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 tonil, 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 tonil, 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.
@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 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
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.