WebsockexNova.Client (WebsockexNova v0.1.0)
View SourceMain client API for WebsockexNova WebSocket connections.
This module provides a high-level, user-friendly API for interacting with WebSocket connections using WebsockexNova. It delegates operations to the transport layer and adapter implementations while providing a consistent interface regardless of the underlying transport or adapter.
Usage
# Connect to a WebSocket server using an adapter
{:ok, conn} = WebsockexNova.Client.connect(MyApp.WebSocket.Adapter, %{
host: "example.com",
port: 443,
path: "/ws",
transport_opts: [transport: :tls]
})
# Send a JSON message
{:ok, response} = WebsockexNova.Client.send_json(conn, %{type: "ping"})
# Subscribe to a channel
{:ok, subscription} = WebsockexNova.Client.subscribe(conn, "market.updates")
# Authenticate with credentials
{:ok, auth_result} = WebsockexNova.Client.authenticate(conn, %{api_key: "key", secret: "secret"})
# Close the connection
:ok = WebsockexNova.Client.close(conn)
Comprehensive Example for a Trading/Financial App
{:ok, conn} = WebsockexNova.Client.connect(MyApp.WebSocket.Adapter, %{
host: System.get_env("EXCHANGE_HOST") || "api.exchange.com",
port: 443,
path: "/ws/v1",
headers: [{"X-API-KEY", System.get_env("EXCHANGE_API_KEY") || "demo-key"}],
timeout: 10_000,
transport_opts: %{transport: :tls},
protocols: [:http],
retry: 10,
backoff_type: :exponential,
base_backoff: 1_000,
ws_opts: %{},
# Rate limiting
rate_limit_handler: WebsockexNova.Defaults.DefaultRateLimitHandler,
rate_limit_opts: %{
capacity: 120,
refill_rate: 10,
refill_interval: 1_000,
queue_limit: 200,
cost_map: %{
subscription: 5,
auth: 10,
query: 1,
order: 10
}
},
# Logging
log_level: :info,
log_format: :plain,
# Metrics
metrics_collector: MyApp.CustomMetricsCollector,
# Authentication
credentials: %{
api_key: System.get_env("EXCHANGE_API_KEY"),
secret: System.get_env("EXCHANGE_API_SECRET")
},
# Handler overrides (optional)
auth_handler: MyApp.CustomAuthHandler,
message_handler: MyApp.CustomMessageHandler,
subscription_handler: MyApp.CustomSubscriptionHandler,
error_handler: MyApp.CustomErrorHandler,
logging_handler: MyApp.CustomLoggingHandler,
# Connection handler options
max_reconnect_attempts: 10,
ping_interval: 15_000,
auth_refresh_threshold: 120
})
Adapter Integration
The client API works with any adapter that implements the required behaviors:
WebsockexNova.Behaviors.ConnectionHandler
WebsockexNova.Behaviors.MessageHandler
WebsockexNova.Behaviors.SubscriptionHandler
WebsockexNova.Behaviors.AuthHandler
WebsockexNova.Behaviors.ErrorHandler
If an adapter doesn't implement a behavior, the client falls back to using default implementations
from the WebsockexNova.Defaults
namespace.
Custom Matcher Example
You can pass a custom matcher function to filter or extract specific responses:
matcher = fn
{:websockex_nova, {:websocket_frame, _stream_ref, {:text, "special"}}} -> {:ok, "special"}
_ -> :skip
end
opts = %{matcher: matcher}
{:ok, response} = WebsockexNova.Client.send_text(conn, "ignored", opts)
# response == "special"
The matcher function receives each message and should return:
{:ok, value}
to match and return the value:skip
to ignore and continue waiting
Summary
Types
Authentication options
Authentication response
Connection configuration options. Must include at least :host, :port, and :path. May include any additional keys required by handlers, adapters, or transports.
Connection response
Message options
Message response
Status response
Subscribe options
Subscription response
Functions
Authenticates with the WebSocket server.
Closes the WebSocket connection.
Connects to a WebSocket server using the specified adapter.
Sends a ping message to the WebSocket server.
Registers a process to receive notifications from the connection.
Sends a raw WebSocket frame.
Sends a JSON message.
Sends a text message.
Gets the current connection status.
Subscribes to a channel or topic.
Unregisters a process from receiving notifications.
Unsubscribes from a channel or topic.
Types
@type auth_options() :: %{timeout: pos_integer() | nil}
Authentication options
Authentication response
@type connect_options() :: %{ :host => String.t(), :port => pos_integer(), :path => String.t(), optional(:headers) => Keyword.t() | map(), optional(:timeout) => pos_integer() | nil, optional(:transport_opts) => map() | Keyword.t() | nil, optional(:protocols) => [atom()], optional(:retry) => non_neg_integer() | :infinity, optional(:backoff_type) => atom(), optional(:base_backoff) => non_neg_integer(), optional(:ws_opts) => map(), optional(:rate_limit_handler) => module(), optional(:rate_limit_opts) => map(), optional(:log_level) => :debug | :info | :warn | :error, optional(:log_format) => :plain | :json | atom(), optional(:metrics_collector) => module(), optional(:auth_handler) => module(), optional(:message_handler) => module(), optional(:subscription_handler) => module(), optional(:error_handler) => module(), optional(:logging_handler) => module(), optional(:credentials) => map(), optional(:max_reconnect_attempts) => pos_integer(), optional(:reconnect_attempts) => non_neg_integer(), optional(:ping_interval) => pos_integer(), optional(:auth_refresh_threshold) => pos_integer(), optional(atom()) => any() }
Connection configuration options. Must include at least :host, :port, and :path. May include any additional keys required by handlers, adapters, or transports.
Required keys
- :host - Hostname or IP address (string)
- :port - Port number (integer)
- :path - WebSocket endpoint path (string)
Common optional keys
- :headers - Additional headers (keyword list or map)
- :timeout - Connection timeout in ms (integer)
- :transport_opts - Transport-specific options (map or keyword list)
Examples:
%{verify: :verify_peer}
or[verify: :verify_peer]
- :protocols - List of protocols (e.g., [:http])
- :retry - Number of connection retries (integer or :infinity)
:backoff_type - :linear | :exponential | :jittered
- :base_backoff - Initial backoff in ms (integer)
- :ws_opts - WebSocket-specific options (map)
- :rate_limit_handler - Module implementing RateLimitHandler
- :rate_limit_opts - Map of rate limiting options (see DefaultRateLimitHandler)
:log_level - :debug | :info | :warn | :error
:log_format - :plain | :json
- :metrics_collector - Module implementing MetricsCollector
- :auth_handler, :message_handler, :subscription_handler, :error_handler, :logging_handler - Custom handler modules
- :credentials - Map with :api_key/:secret or :token for authentication
- :max_reconnect_attempts, :reconnect_attempts, :ping_interval, :auth_refresh_threshold, etc.
- Any other keys required by your custom handlers or adapters
All additional keys are passed to the relevant handler, adapter, or transport module.
@type connection_result() :: {:ok, WebsockexNova.ClientConn.t()} | {:error, term()}
Connection response
@type message_options() :: %{timeout: pos_integer() | nil}
Message options
Message response
Status response
@type subscribe_options() :: %{timeout: pos_integer() | nil}
Subscribe options
Subscription response
Functions
@spec authenticate(WebsockexNova.ClientConn.t(), map(), auth_options() | nil) :: {:ok, WebsockexNova.ClientConn.t(), term()} | {:error, term()} | {:error, term(), WebsockexNova.ClientConn.t()}
Authenticates with the WebSocket server.
Parameters
conn
- Client connection structcredentials
- Authentication credentialsoptions
- Authentication options
Options
:timeout
- Response timeout in milliseconds (default: 30,000):matcher
- (optional) A function to match/filter responses. The function should accept a message and return{:ok, response}
to match, or:skip
to ignore and continue waiting. See module doc for examples.
Returns
{:ok, conn, auth_result}
on success (with updated connection){:error, reason}
on failure
@spec close(WebsockexNova.ClientConn.t()) :: :ok
Closes the WebSocket connection.
Parameters
conn
- Client connection struct
Returns
:ok
@spec connect(module(), connect_options()) :: connection_result()
Connects to a WebSocket server using the specified adapter.
This function initializes the adapter, retrieves connection information, establishes a connection using the transport layer, and upgrades to WebSocket.
Parameters
adapter
- Module implementing adapter behaviorsoptions
- Connection options
Options
:host
- Hostname or IP address of the server (required):port
- Port number of the server (required):path
- WebSocket endpoint path (required):headers
- Additional headers for the upgrade request (optional):transport_opts
- Transport-specific options as a map or keyword list (optional):timeout
- Connection timeout in milliseconds (default: 30,000)
Returns
{:ok, conn}
on success{:error, reason}
on failure
@spec ping(WebsockexNova.ClientConn.t(), message_options() | nil) :: {:ok, :pong} | {:error, term()}
Sends a ping message to the WebSocket server.
Parameters
conn
- Client connection structoptions
- Message options
Options
:timeout
- Response timeout in milliseconds (default: 30,000)
Returns
{:ok, :pong}
on success{:error, reason}
on failure
@spec register_callback(WebsockexNova.ClientConn.t(), pid()) :: {:ok, WebsockexNova.ClientConn.t()}
Registers a process to receive notifications from the connection.
Registered processes will receive messages when connection events occur:
{:connection_down, protocol, reason}
- When connection is lost{:connection_reconnected, updated_conn}
- When connection is automatically reconnected(the updated_conn has new transport_pid and stream_ref)
{:ws_message, message}
- When a WebSocket message is received
Parameters
conn
- Client connection structpid
- Process ID to register
Returns
{:ok, ClientConn.t()}
with updated connection{:error, reason}
if registration fails
@spec send_frame(WebsockexNova.ClientConn.t(), WebsockexNova.Transport.frame()) :: :ok | {:error, term()}
Sends a raw WebSocket frame.
Parameters
conn
- Client connection structframe
- WebSocket frame to send
Returns
:ok
on success{:error, reason}
on failure
@spec send_json(WebsockexNova.ClientConn.t(), map(), message_options() | nil) :: message_result()
Sends a JSON message.
Parameters
conn
- Client connection structdata
- Map to encode as JSON and sendoptions
- Message options
Options
:timeout
- Response timeout in milliseconds (default: 30,000):matcher
- (optional) A function to match/filter responses. The function should accept a message and return{:ok, response}
to match, or:skip
to ignore and continue waiting. See module doc for examples.
Returns
{:ok, response}
on success{:error, reason}
on failure
@spec send_text(WebsockexNova.ClientConn.t(), String.t(), message_options() | nil) :: message_result()
Sends a text message.
Parameters
conn
- Client connection structtext
- Text message to sendoptions
- Message options
Options
:timeout
- Response timeout in milliseconds (default: 30,000):matcher
- (optional) A function to match/filter responses. The function should accept a message and return{:ok, response}
to match, or:skip
to ignore and continue waiting. See module doc for examples.
Returns
{:ok, response}
on success{:error, reason}
on failure
@spec status(WebsockexNova.ClientConn.t(), map() | nil) :: status_result()
Gets the current connection status.
Parameters
conn
- Client connection structoptions
- Options
Options
:timeout
- Request timeout in milliseconds (default: 30,000)
Returns
{:ok, status}
on success{:error, reason}
on failure
@spec subscribe(WebsockexNova.ClientConn.t(), String.t(), subscribe_options() | nil) :: subscription_result()
Subscribes to a channel or topic.
Parameters
conn
- Client connection structchannel
- Channel or topic to subscribe tooptions
- Subscription options
Options
:timeout
- Response timeout in milliseconds (default: 30,000):matcher
- (optional) A function to match/filter responses. The function should accept a message and return{:ok, response}
to match, or:skip
to ignore and continue waiting. See module doc for examples.
Returns
{:ok, subscription}
on success{:error, reason}
on failure
@spec unregister_callback(WebsockexNova.ClientConn.t(), pid()) :: {:ok, WebsockexNova.ClientConn.t()}
Unregisters a process from receiving notifications.
Parameters
conn
- Client connection structpid
- Process ID to unregister
Returns
{:ok, ClientConn.t()}
with updated connection
@spec unsubscribe(WebsockexNova.ClientConn.t(), String.t(), subscribe_options() | nil) :: subscription_result()
Unsubscribes from a channel or topic.
Parameters
conn
- Client connection structchannel
- Channel or topic to unsubscribe fromoptions
- Subscription options
Options
:timeout
- Response timeout in milliseconds (default: 30,000):matcher
- (optional) A function to match/filter responses. The function should accept a message and return{:ok, response}
to match, or:skip
to ignore and continue waiting. See module doc for examples.
Returns
{:ok, result}
on success{:error, reason}
on failure