James_E
I’ve got this bit of code; I’m wondering why create_or_open_room always creates a new room, even when there is an existing child process with the same ID:
If a child specification with the specified ID already exists,
child_specis discarded and this function returns an error with:already_startedor:already_presentif the corresponding child process is running or not, respectively.
Supervisor.start_child/2 — Elixir v1.17.3
defmodule FooApp.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
require Logger
def create_or_open_room(<<room_name::binary>>) do # FIXME this is supposed to be idempotent
case DynamicSupervisor.start_child(
FooApp.RoomSupervisor,
%{id: room_name, start: {GenServer, :start_link, [FooApp.Application.Model, room_name]}}
) do
{:ok, pid} -> Logger.debug("=====STARTED #{inspect pid}====="); pid
:ignore -> raise "unreachable"
{:error, {:already_started, pid}} -> Logger.debug("=====IDEMPOTENCE OK #{inspect pid}====="); pid
{:error, error} -> raise inspect error
end
end
@impl true
def start(_type, _args) do
children = [
FooAppWeb.Telemetry,
FooApp.Repo,
{Ecto.Migrator,
repos: Application.fetch_env!(:fooApp, :ecto_repos),
skip: skip_migrations?()},
# {DNSCluster, query: Application.get_env(:fooApp, :dns_cluster_query) || :ignore},
# {Phoenix.PubSub, name: FooApp.PubSub}, # for general app communication
{Phoenix.PubSub, name: FooApp.RoomPubSub}, # ONLY for room statechange announcements, to avoid collision between UGC room names and an actual system topic
# Start the Finch HTTP client for sending emails
# {Finch, name: FooApp.Finch},
# Start a worker by calling: FooApp.Worker.start_link(arg)
# {FooApp.Worker, arg},
{DynamicSupervisor, name: FooApp.RoomSupervisor},
# Start to serve requests, typically the last entry
FooAppWeb.Endpoint
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: FooApp.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
@impl true
def config_change(changed, _new, removed) do
FooAppWeb.Endpoint.config_change(changed, removed)
:ok
end
defp skip_migrations?() do
# By default, sqlite migrations are run when using a release
System.get_env("RELEASE_NAME") != nil
end
end
FooApp.Application.Model (a boring GenServer, not relevant, including for completeness)
defmodule FooApp.Application.Model do
use GenServer
require Logger
defmodule State do
@enforce_keys [:name, :resources]
defstruct [:name, :resources, :_pubsub_topic]
end
defmodule Resource do
@enforce_keys [:name]
defstruct [:name, status: "undefined"]
@allowable_statuses ["green", "green-with-exception", "red"]
def status_ok(status) do
status in @allowable_statuses
end
end
defp list_update_such(list, fun_pred, fun) do
# TODO consider overhauling/replacing this with a new data structure entirely
# https://forum.elixirforum.com/t/need-to-display-resources-in-the-exact-order-they-are-declared-ordered-map/67829/4?u=james_e
Enum.map(list, &if fun_pred.(&1) do fun.(&1) else &1 end)
end
@impl true
def init(name) do
resource_names = [ # FIXME actually load this from ecto
"FROG-0",
"FROG-1",
"FROG-2",
"FROG-3",
"FROG-4",
"FROG-5",
"FROG-6",
"FROG-7",
];
{:ok, %State{
name: name,
resources: resource_names |> Enum.map(&%Resource{name: &1}),
_pubsub_topic: name
}}
end
@impl true
def handle_continue(:broadcast_statechange, state) do
# TODO this seems located inappropriately far from the call to subscribe; is there a better pattern for this?
Phoenix.PubSub.broadcast!(FooApp.RoomPubSub, state._pubsub_topic, {:statechange, state});
{:noreply, state}
end
@impl true
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
@impl true
def handle_call({:act, actor, action}, from, state) do
case action do
{:set_resource_status, resource_name, new_status} -> (
with \
true <- actor === "director" || {:error, "Unauthorized"},
resources = state.resources,
true <- Resource.status_ok(new_status) || {:error, "Invalid status"}
do
{:reply, :ok, %{state |
resources: list_update_such(resources, &(&1.name === resource_name), &%{&1 | status: new_status})
}, {:continue, :broadcast_statechange}}
else
{:error, error} -> {:reply, {:error, error}, state}
end
)
_ -> (
Logger.warning("Client #{inspect from} attempted invalid action");
{:reply, {:error, "Action incongruent with current state"}, state}
)
end
end
end
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
Hi all, I wanted to ask how the community is dealing with post-release steps.
Today we have Ecto migrations, which make sure that the db...
New
Hello,
I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex











Showing Posts 1 to 9- Show Best Posts
- Show All Posts (oldest first)
- Show All Posts (newest first)
al2o3cr
The docs for
DynamicSupervisor.start_childmention that theidis required but ignored:D4no0
Yeah, I think this applies only to named genservers, AKA starting them with option
name: ProcessName.dimitarvp
As @al2o3cr said, the
:idis ignored. Though if my memory serves you can achieve what you like by supplying a:name… which is what @D4no0 said.If none of that works you could just use
DynamicSupervisor.which_childrenand try to look for the already-started child there before attempting to start a new one.James_E
I see… I adapted the code with that in mind, and now it seems to work perfectly:
Thanks all for the tips. I don’t know how I missed that notice about the spec being wack.
dimitarvp
Come on now, spec is not “wack”, you just need a name if you want to, you know, have a named process.
James_E
I was referring the
@spec— where the DynamicSupervisor’s child’sidfield is required, yet ignored — that was a red herring that confused me when trying to implement this.The ID here isn’t meant to be a global name, only a local ID within the scope of that specific DynamicSupervisor.
James_E
Can’t edit the post because it’s too old; here’s an implementation for posterity with proper documentation
dimitarvp
Glad you made it work for you but I still don’t understand how can you not ensure the
DynamicSupervisorgets started at the, ahem, start of your application.James_E
This function — just like
DynamicSupervisor.start_child/2— requires you to pass in an existing, running DynamicSupervisor. Starting that process is handled elsewhere.