Construct an Elixir DynamicSupervisor that starts children on demand when a user…
- User
Construct an Elixir
DynamicSupervisorthat starts children on demand when a user connects to a WebSocket. Assistant
Construct an Elixir DynamicSupervisor that starts children on demand when a user connects to a WebSocket.
The user wants an Elixir DynamicSupervisor that starts children on demand, specifically when a user connects to a WebSocket.
Key Components Required:
DynamicSupervisor: This will manage the child processes (likely GenServers or similar) representing the user sessions or WebSocket handlers.DynamicSupervisor (and potentially the Web Server endpoint).UserSession): This represents the logic for a connected user.Scenario Choice:
Since the prompt mentions WebSockets, I need to choose a web framework. Phoenix is the industry standard. I shouldn't assume a full Phoenix app structure but rather provide the core logic that fits into one. Alternatively, I could use a simple cowboy setup, but that's more boilerplate-heavy. Phoenix is the most practical answer.
Step-by-Step Implementation Plan:
Define the Child Process (UserSession):
GenServer.start_link function that accepts a user ID or socket path.child_spec to define how the supervisor starts it (though use GenServer often provides defaults).Define the DynamicSupervisor:
DynamicSupervisor.Connect the WebSocket to the Supervisor:
DynamicSupervisor.start_child.Refining the Architecture:
Registry is highly recommended alongside the DynamicSupervisor. This allows looking up the PID by user_id.user:123), we ensure the backing process exists.Drafting the Code Structure:
Registry and MyApp.DynamicSupervisor.SessionServer):
start_link/1 takes [id: user_id].via_tuple logic for registration.DynamicSupervisor wrapper.start_session/1 to wrap the start_child call.join("session:" <> user_id, ...) calls SessionSupervisor.start_session(user_id).Handling "On Demand":
The crucial part is where the call happens.
If using Phoenix Channels:
UserSocket -> connect (authenticate) -> Channel -> join.
In join/3, call the supervisor.
Simplicity vs. Robustness: I should provide a robust solution.
Registry for unique names.DynamicSupervisor.Code Sketch:
# 1. The Child
defmodule MyApp.UserSession do
use GenServer
def start_link(user_id) do
GenServer.start_link(__MODULE__, user_id, name: via_tuple(user_id))
end
def via_tuple(user_id) do
{:via, Registry, {MyApp.Registry, user_id}}
end
# ... init/callbacks ...
end
# 2. The Supervisor
defmodule MyApp.SessionSupervisor do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
def start_session(user_id) do
spec = {MyApp.UserSession, user_id}
DynamicSupervisor.start_child(__MODULE__, spec)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
# 3. Application Supervisor Setup
children = [
{Registry, keys: :unique, name: MyApp.Registry},
MyApp.SessionSupervisor
]
# 4. The Trigger (Conceptually in a Phoenix Channel)
def join("user:" <> user_id, _params, socket) do
case MyApp.SessionSupervisor.start_session(user_id) do
{:ok, _pid} -> :ok
{:error, {:already_started, _pid}} -> :ok
end
{:ok, socket}
end
Reviewing the Draft:
DynamicSupervisor.start_child return {:error, {:already_started, pid}}? Only if the child spec uses a :start link that returns that, or if the name registration fails during start_link.Registry, calling start_link on a name that exists will cause the GenServer to crash/exist with {:error, {:already_started, pid}}.lookup and start_child, you fail. If you just try start_child, the Registry handles the locking.Structuring the Output:
application.ex.I will use a Phoenix Channel as the example context because it's the most common use case for WebSockets in Elixir. I'll clarify that the "WebSocket" part is usually handled by Phoenix transports, and the business logic happens in the Channel.
Refinement on the Trigger: The user asked for "When a user connects". In Phoenix:
UserSocket.connect/2: Good for auth, maybe too early to spawn a persistent session if the connection drops immediately.Channel.join/3: Better, implies the user has successfully established the WS and is subscribing to a specific topic.Let's stick to the Channel join event as the trigger.
Self-Correction/Edge Case:
What if the user connects twice (e.g., two tabs)?
The Registry approach handles this gracefully. The UserSession is unique per user_id. Both sockets connect to the same process. This is usually desired behavior.
Final Code Blocks:
MyApp.UserSession (The GenServer child)MyApp.SessionSupervisor (The DynamicSupervisor)application.ex snippet (Wiring)MyAppWeb.UserChannel (The Trigger)Let's write the response. Here is a complete implementation strategy.
To achieve this, you need three main components:
First, define the GenServer that represents a user's connection. Note the usage of via_tuple—this allows us to look up the process by user ID in the Registry.
# lib/my_app/user_session.ex
defmodule MyApp.UserSession do
use GenServer
# 1. Start Link logic
# We use a "via" tuple to register the process in the Registry under the user_id
def start_link(user_id) do
name = via_tuple(user_id)
GenServer.start_link(__MODULE__, user_id, name: name)
end
# Helper to generate the registration name
defp via_tuple(user_id) do
{:via, Registry, {MyApp.Registry, user_id}}
end
# 2. Lookup Helper
# Other parts of the app can use this to find the PID
def lookup(user_id) do
case Registry.lookup(MyApp.Registry, user_id) do
[{pid, _}] -> {:ok, pid}
[] -> {:error, :not_found}
end
end
# 3. GenServer Callbacks
@impl true
def init(user_id) do
IO.puts("Session started for user: #{user_id}")
{:ok, %{user_id: user_id, connected_at: DateTime.utc_now()}}
end
end
This is the supervisor that will host the UserSession processes.
# lib/my_app/session_supervisor.ex
defmodule MyApp.SessionSupervisor do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
# Public API to start a child safely
def start_session(user_id) do
spec = {MyApp.UserSession, user_id}
case DynamicSupervisor.start_child(__MODULE__, spec) do
{:ok, pid} ->
{:ok, pid}
{:error, {:already_started, pid}} ->
# This happens if the user is already connected
{:ok, pid}
error ->
error
end
end
end
You must add the Registry and the DynamicSupervisor to your application supervision tree in application.ex.
# lib/my_app/application.ex
defmodule MyApp.Application do
use Application
@impl true
def start(_type, _args) do
children = [
# 1. Add the Registry first
{Registry, keys: :unique, name: MyApp.Registry},
# 2. Add the DynamicSupervisor
MyApp.SessionSupervisor,
# ... your Endpoint, etc.
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
Where you place this logic depends on your stack (Phoenix, Cowboy, etc.), but the logic remains the same. You trigger the Supervisor when the connection initializes.
If you are using Phoenix Sockets, the "connect" happens in UserSocket or inside a Channel join/3.
# lib/my_app_web/channels/room_channel.ex
defmodule MyAppWeb.RoomChannel do
use Phoenix.Channel
def join("room:lobby", _message, socket) do
# Extract user_id (assuming it was assigned in the Socket connect/2)
user_id = socket.assigns.user_id
# Tell the Supervisor to start this child
case MyApp.SessionSupervisor.start_session(user_id) do
{:ok, _pid} ->
{:ok, socket}
{:error, reason} ->
{:error, %{reason: "Failed to start session: #{inspect(reason)}"}}
end
end
end
If you are using a raw Cowboy handler:
defmodule MyAppWeb.WebsocketHandler do
@behavior :cowboy_websocket
def init(request, state) do
# Assuming user_id is in the query params
user_id = request.qs_vals["user_id"]
# Schedule the session start for after the connection upgrades
send(self(), {:start_session, user_id})
{:cowboy_websocket, request, state}
end
def websocket_init(state) do
{:ok, state}
end
def websocket_handle({:text, msg}, state) do
# Handle incoming text
{:reply, {:text, msg}, state}
end
def websocket_info({:start_session, user_id}, state) do
# Start the child process here
MyApp.SessionSupervisor.start_session(user_id)
{:ok, state}
end
end
MyApp.SessionSupervisor.start_session/1.DynamicSupervisor attempts to start a UserSession.
MyApp.Registry.start_child returns {:error, {:already_started, pid}}. The helper function matches this and returns {:ok, pid} gracefully.UserSession GenServer stays alive, handling logic, even if the WebSocket process dies and reconnects (depending on your design).