Internal reconnection helper for Client GenServer.
This module provides reconnection logic that runs within the Client GenServer process to maintain Gun message ownership. It handles:
- Connection establishment with retry logic
- Exponential backoff calculations
- Subscription restoration after reconnection
Architecture
This module is called by the Client GenServer during its handle_continue and handle_info callbacks. All functions run in the Client GenServer process to ensure the new Gun connection sends messages to the correct process.
Not for External Use
This module is internal to ZenWebsocket. External code should use
ZenWebsocket.Client.connect/2 which handles initial connection attempts
and automatic reconnection.
API Functions
| Function | Arity | Description | Param Kinds |
|---|---|---|---|
max_retries_exceeded? | 2 | Check if the retry attempt count has exceeded the maximum. | attempt: value, max_retries: value |
should_reconnect? | 1 | Check whether an error should trigger reconnection. | error: value |
calculate_backoff | 3 | Calculate exponential backoff delay for a reconnection attempt. | attempt: value, base_delay: value, max_backoff: value |
build_gun_opts | 1 | Build Gun connection options for a URI scheme. | uri: value |
establish_connection | 1 | Establish a Gun WebSocket connection from the given config. | config: value |
Summary
Functions
Build Gun connection options for the given URI.
Calculate exponential backoff delay for reconnection attempts.
Attempt to establish a Gun connection with the given configuration.
Check if maximum retry attempts have been exceeded.
Determine if a connection error should trigger reconnection.
Functions
Build Gun connection options for the given URI.
For WSS connections, configures TLS ALPN to force HTTP/1.1 negotiation. Without this, Cloudflare-fronted servers negotiate HTTP/2 via ALPN, which strips Connection: Upgrade headers and breaks WebSocket upgrades.
@spec calculate_backoff( attempt :: non_neg_integer(), base_delay :: pos_integer(), max_backoff :: pos_integer() | nil ) :: pos_integer()
Calculate exponential backoff delay for reconnection attempts.
Examples
iex> calculate_backoff(0, 1000)
1000
iex> calculate_backoff(1, 1000)
2000
iex> calculate_backoff(5, 1000, 30000)
30000 # Capped at max_backoff
@spec establish_connection(ZenWebsocket.Config.t()) :: {:ok, gun_pid :: pid(), stream_ref :: reference(), monitor_ref :: reference()} | {:error, term()}
Attempt to establish a Gun connection with the given configuration.
This function must be called from within the Client GenServer process to ensure Gun sends messages to the correct process.
@spec max_retries_exceeded?( attempt :: non_neg_integer(), max_retries :: non_neg_integer() ) :: boolean()
Check if maximum retry attempts have been exceeded.
Determine if a connection error should trigger reconnection.
Returns true for recoverable errors like network issues, false for unrecoverable errors like invalid credentials.