WebsockexNova.Gun.ConnectionManager (WebsockexNova v0.1.1)

View Source

Manages the WebSocket connection lifecycle using a state machine approach.

Responsibilities

  • Handles connection state transitions.
  • Delegates all reconnection policy decisions to the error handler (single source of truth).
  • On disconnect/error, calls the error handler's should_reconnect?/3.
  • If allowed, calls the transport adapter's schedule_reconnection/2.
  • Does not track reconnection attempts or delays; this is handled by the error handler.

Summary

Functions

Checks if the connection state can transition to the target state.

Initiates a connection.

Schedules a reconnection attempt by delegating policy to the error handler. This function is the only place reconnection is scheduled.

Starts a new connection by transitioning to connecting state and opening a connection.

Attempts to transition the state machine to a new state.

Functions

can_transition?(from_state, to_state)

@spec can_transition?(atom(), atom()) :: boolean()

Checks if the connection state can transition to the target state.

Parameters

  • from_state - Current state
  • to_state - Target state

Returns

  • true if the transition is allowed
  • false if the transition is not allowed

initiate_connection(state)

Initiates a connection.

Parameters

  • state - Current connection state

Returns

  • {:ok, updated_state} on success
  • {:error, reason, updated_state} on failure

schedule_reconnection(state, callback)

Schedules a reconnection attempt by delegating policy to the error handler. This function is the only place reconnection is scheduled.

Parameters

  • state - Current connection state
  • callback - Function to call with (delay, attempt_number) when reconnection should be attempted

Returns

  • updated_state - The new connection state after scheduling (or not scheduling) reconnection

start_connection(state)

Starts a new connection by transitioning to connecting state and opening a connection.

This function centralizes the connection establishment process, handling both the state transition and the actual connection attempt.

Parameters

  • state - Current connection state

Returns

  • {:ok, updated_state} on success
  • {:error, reason, updated_state} on failure

transition_to(state, to_state, params \\ %{})

@spec transition_to(WebsockexNova.Gun.ConnectionState.t(), atom(), map()) ::
  {:ok, WebsockexNova.Gun.ConnectionState.t()} | {:error, :invalid_transition}

Attempts to transition the state machine to a new state.

Parameters

  • state - Current connection state
  • to_state - Desired new state
  • params - Optional parameters for the transition

Returns

  • {:ok, new_state} on successful transition
  • {:error, :invalid_transition} if the transition is not allowed