tortoise icon indicating copy to clipboard operation
tortoise copied to clipboard

Best way to restart connections?

Open travisgriggs opened this issue 2 years ago • 1 comments

(I'd love to ask questions on the elixir-lang#tortoise slack channel, but that seems pretty dead)

This question probably shows my naivety with OTP as much as anything. I'm using the Tortoise.Supervisor to start my connections (I have multiple) as described at (https://hexdocs.pm/tortoise/connection_supervision.html#the-tortoise-supervisor). My code looks like:

{:ok, _pid} =
      Tortoise.Supervisor.start_child(
        client_id: MC.Keypair.mqtt_id(mc.keypair),
        server: server,
        user_name: username,
        password: mc.passkey1,
        subscriptions: subscriptions,
        handler: {handler, [state]}
      )

Sometimes I need to restart this connection with an updated state (a restful endpoint changes the configuration). If this runs again, I'll get an {:error, {:already_started, #PID<0.746.0>}}}

Is there an idiomatic way to (re)start a connection? I want it to start if one by that client_id does not yet exist. And restart if one does.

travisgriggs avatar Sep 22 '21 17:09 travisgriggs

I ended up using the following pattern (#general channel on slack was helpful)

def connect(handler, state) do
  ...
  Tortoise.Supervisor.start_child(
      client_id: MC.Keypair.mqtt_id(mc.keypair),
      server: server,
      user_name: username,
      password: mc.passkey1,
      subscriptions: subscriptions,
      handler: {handler, [state]}
    )
    |> case do
      {:ok, pid} ->
        {:ok, pid}

      {:error, {:already_started, pid}} ->
        :ok = DynamicSupervisor.terminate_child(Tortoise.Supervisor, pid)
        connect(handler, state)

      err ->
        err
    end
end

travisgriggs avatar Sep 22 '21 21:09 travisgriggs