Phoenix.SocketClient.Agent (phoenix_socket_client v0.8.0)
View SourceAgent-based 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. All state is stored in an Agent process for concurrent access and updates.
The state is managed by the Phoenix.SocketClient.State struct.
Shared State Limitation
This module uses an Agent as shared mutable state that is read and written to
by multiple processes (the Socket GenServer, Channel GenServers, and external
callers). While Agent serializes individual get and update calls, it does
not provide compound read-then-write atomicity across callers. This means
concurrent operations that depend on reading the current state and then updating
it can race with each other.
Future Refactoring Direction
A more robust approach would be to replace this Agent with a dedicated GenServer that owns and mediates all state access. A GenServer would allow:
- Compound read-modify-write operations handled atomically in
handle_call - Explicit control over which operations are synchronous vs asynchronous
- Better visibility into state access patterns via callbacks
- Easier addition of validation or side effects on state transitions
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 status of a channel.
Updates the connection timestamp.
Functions
Returns a specification to start this module under a supervisor.
See Supervisor.
Checks if the socket is connected.
Retrieves a value from the state by key.
Parameters
pid- The Agent PIDkey- The key to retrieve
Examples
value = Phoenix.SocketClient.Agent.get(pid, :url)
Retrieves the entire state map.
@spec pop_all_to_send(pid()) :: [Phoenix.SocketClient.Message.t()]
Pops all messages pending to be sent.
Updates the state with a new key-value pair.
Parameters
pid- The Agent PIDkey- The key to setvalue- The value to associate with the key
Examples
:ok = Phoenix.SocketClient.Agent.put(pid, :status, :connected)
Removes a channel from the state.
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")
Updates the status of a channel.
@spec update_connect_time(pid()) :: :ok
Updates the connection timestamp.