Starting a GenServer that loads default state

Hi,

I have a multi-tenancy SaaS solution that allows tenants to have integrations with external services. I have written a library to handle the integrations that uses a GenServer to hold the integrations in state so I can run synchronisation jobs based on the configured schedule.

I am saving the list of integrations in a db table and want to load the list when the GenServer starts. I am using the Application behaviour to start the GenServer when the solution starts.

defmodule Integrations.Application do
  use Application

  def start(_type, _args) do

    children = [
      {Integrations.Boundary.Manager, %{}}
    ]

    opts = [strategy: :one_for_one, name: Integrations.Supervisor]
    Supervisor.start_link(children, opts)
  end

end

The Integrations.Boundary.Manager needs access to the MyApp.Repo so that it can check for and load any existing integrations. I have tried a number of ways to pass MyApp.Repo to the GenServer but keep getting the error:

** (RuntimeError) could not lookup Ecto repo My.Repo because it was not started or it does not exist

I removed the Application from my library and added a ChildSpec to the MyApp.Application

def start(_type, _args) do
    children = [
      # Start the Ecto repository
      MyApp.Repo,
      # Start the Telemetry supervisor
      MyAppWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: MyApp.PubSub},
      # Start the Endpoint (http/https)
      MyAppWeb.Endpoint,
      # Start a worker by calling: R2.Worker.start_link(arg)
      # {MyApp.Worker, arg}
      {Integrations.Boundary.Manager, %{}}
    ]

But get the same error. Any guidance will be greatly appreciated.

Andrew

Shouldn’t that be MyApp.Repo?
Also if you have a GenServer from a library, try not to make it an application itself. Better to add the GenServer in your main application like your second style, and also give it a unique name and necessary arguments in the child_spec, in your case you want to pass the Repo name into the GenServer’s start_link.

3 Likes

Thanks mate … that got me there :slight_smile: