defmodule Polymarket.WebSocket.SocketSupervisor do @moduledoc """ Dynamic supervisor for all websocket connections to polymarket. A single websocket can only hold so many asset ids, so sharding is required to make sure we can subscribe to more assets than a single connection allows. """ use DynamicSupervisor alias Polymarket.WebSocket @doc false @spec start_link(term()) :: Supervisor.on_start() 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 @doc """ Adds a new websocket connection to the supervisor. Accepts the same options as `Polymarket.WebSocket.start_link/1` (for example `handler:`) to inject a custom event handler. Connections are `:temporary` children: a dead connection is not restarted, because the restarted process would carry a new pid and no subscriptions, invisible to whoever opened it. Owners are expected to monitor the returned pid and open a replacement themselves. """ @spec add_connection(keyword()) :: DynamicSupervisor.on_start_child() def add_connection(opts \\ []) do DynamicSupervisor.start_child( __MODULE__, Supervisor.child_spec({WebSocket, opts}, restart: :temporary) ) end end