Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way to restart connections? #138

Open
travisgriggs opened this issue Sep 22, 2021 · 1 comment
Open

Best way to restart connections? #138

travisgriggs opened this issue Sep 22, 2021 · 1 comment

Comments

@travisgriggs
Copy link

travisgriggs commented Sep 22, 2021

(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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant