Phoenix.SocketClient.Agent (phoenix_socket_client v0.8.6)

Copy Markdown View Source

Agent-compatible state management for WebSocket connection configuration and status.

This module provides centralized state management for socket connections, including configuration parameters, connection status, and custom state values. State is stored in a GenServer that supports the Agent call protocol and owns diagnostic formatting to omit private configuration and queued content.

The state is managed by the Phoenix.SocketClient.State struct.

Shared State Limitation

Multiple processes (the Socket, Channels and external callers) read and write this state. Individual Agent operations are serialized, but separate read and write calls are not atomic together and can race. Compound changes must use a single Agent.get_and_update/2 operation or a dedicated callback.

See GitHub issue #31 for discussion.

Summary

Functions

Returns a specification to start this module under a supervisor.

Checks if the socket is connected.

Retrieves a value from the state by key.

Retrieves the entire state map.

Pops all messages pending to be sent.

Updates the state with a new key-value pair.

Removes a channel from the state.

Starts the Agent with the given configuration options.

Updates the connection timestamp.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

connected?(pid)

@spec connected?(pid()) :: boolean()

Checks if the socket is connected.

get(pid, key)

@spec get(pid(), atom() | String.t()) :: any()

Retrieves a value from the state by key.

Parameters

  • pid - The Agent PID
  • key - The key to retrieve

Examples

value = Phoenix.SocketClient.Agent.get(pid, :url)

get_state(pid)

@spec get_state(pid()) :: map()

Retrieves the entire state map.

pop_all_to_send(pid)

@spec pop_all_to_send(pid()) :: [Phoenix.SocketClient.Message.t()]

Pops all messages pending to be sent.

put(pid, key, value)

@spec put(pid(), atom() | String.t(), any()) :: :ok

Updates the state with a new key-value pair.

Parameters

  • pid - The Agent PID
  • key - The key to set
  • value - The value to associate with the key

Examples

:ok = Phoenix.SocketClient.Agent.put(pid, :status, :connected)

remove_channel(pid, topic)

@spec remove_channel(pid(), String.t()) :: :ok

Removes a channel from the state.

start_link(opts)

@spec start_link(keyword() | map()) :: {:ok, pid()} | {:error, term()}

Starts the Agent with the given configuration options.

Parameters

  • opts - Keyword list or map of configuration options

Examples

{:ok, pid} = Phoenix.SocketClient.Agent.start_link(url: "ws://localhost:4000/socket")

update_channel_status(pid, channel_pid, topic, status, params \\ nil)

@spec update_channel_status(pid(), pid(), String.t(), atom(), map() | nil) :: :ok

Updates the status of a channel.

update_connect_time(pid)

@spec update_connect_time(pid()) :: :ok

Updates the connection timestamp.