<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="157874" data-post-id="157874">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="apr" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/apr/120/11951_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  apr
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Unfortunately, the <code>on_load</code> callback won’t work in this case because the module itself is not loaded when the callback is run, so I can’t query using the module. I suppose I need to use something like <code>after_load</code>, but I don’t think it exists. Will take a look at some of the other suggestions in this thread.</p>
<p>Thanks for the pointer tho, I see it being useful in some other cases <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="157874" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/structure-code-to-run-before-any-application-starts/28125/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-157874" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="157874"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="157893" data-post-id="157893">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="amnu3387" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  amnu3387
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>If you’re using an umbrella I found it useful to create an application that is responsible for bootstrapping the actual app. This allows you to setup things before starting your actual “core”.<br>
As an example, on the umbrella mix.exs I have the following release:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule YourApp.MixProject do
  use Mix.Project

  def project do
    [
      apps_path: "apps",
      version: "1.0.0",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      releases: [
        your_release_name: [
          applications: [
            bootstrap: :permanent, #this is so that when releasing it starts this app which in turn will run its logic
            server: :load #this is the actual core application, we set it to only load its modules but not start the supervision tree
          ],
          include_executables_for: [:unix]
        ]
      ]
    ]
  end
  #other things.... like deps etc
end
</code></pre>
<p>Then the <code>bootstrap</code> app is a simple app with a supervision tree, it has a <code>bootstrap.ex</code> which is a gen_server to be started from the supervision tree, eg:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Bootstrap do
  
  @moduledoc """
  This starts mnesia and etc and once ok starts the web interface
  """

  use GenServer, shutdown: 50_000
  require Logger
  
  @mnesia_tables_attrs %{
    categories: [:slug, :title, :description, :image, :id, :struct]
  }

  @mnesia_tables Enum.reduce(@mnesia_tables_attrs, [], fn({table, _}, acc) -&gt;
    [table | acc]
  end) |&gt; :lists.reverse

  def start_link(_) do
    GenServer.start_link(__MODULE__, nil, name: __MODULE__)
  end

  def init(_) do
    System.cmd("epmd", ["-daemon"])

    #random_uuid = (:crypto.strong_rand_bytes(4) |&gt; Base.encode16())
    #name = :"#{random_uuid}@#{:net_adm.localhost()}"

    #:net_kernel.start([name])
    
    case :mnesia.start() do
      :ok -&gt;
        
        Enum.each(@mnesia_tables_attrs, fn({table, attributes}) -&gt;
          :mnesia.create_table(table, [attributes: attributes])
        end)
        
        case :mnesia.wait_for_tables(@mnesia_tables, 5_000) do
          :ok -&gt;
            Logger.warn("Mnesia tables loaded")
            {:ok, :started, {:continue, :ensure_all_started}}
          {:timeout, tables} -&gt;
            Logger.error("Mnesia Unable to load tables: #{inspect tables} - shutting down...")
            :init.stop()
        end

      error -&gt; :init.stop()
    end
  end

  def handle_continue(:ensure_all_started, state) do
    Logger.info("Starting server")
    {:ok, _started_apps} = :application.ensure_all_started(:server, :permanent)
    {:noreply, :started}
  end

  def copy_hex_cache(_, _, _) do
    File.cp_r!(Path.expand("~/.hex"), File.cwd!() &lt;&gt; "/hex")
    :ok
  end

  def delete_hex_cache(_, _, _) do
    File.rm_rf!(File.cwd!() &lt;&gt; "/hex")
    :ok
  end

end
</code></pre>
<p>Then it’s application file includes:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Bootstrap.Application do
  @moduledoc false

  use Application

  def start(_type, _args) do
    children = [
      {Bootstrap, []}
    ]

    opts = [strategy: :one_for_one, name: Bootstrap.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
</code></pre>
<p>And it has a task in all similar to the phx.server task:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Mix.Tasks.Bootstrap do
  use Mix.Task

  def run(_) do
    Application.put_env(:phoenix, :serve_endpoints, true, persistent: true)
    {:ok, _} = Application.ensure_all_started(:bootstrap)
    Mix.Tasks.Run.run run_args() ++ ["--no-start"]
  end

  defp run_args do
    if iex_running?(), do: [], else: ["--no-halt"]
  end

  defp iex_running? do
    Code.ensure_loaded?(IEx) and IEx.started?
  end

end
</code></pre>
<p>This task is to be run when in dev, so that you can do <code>iex -S mix bootstrap</code><br>
In my case I do Ecto migrations when I need manually, but there’s nothing preventing you from adding a step to run migrations as well as part of the <code>bootstrap</code> gen_server. Any other things you need to do before starting your actual core, can be done here too if needed. When running the release it will start the bootstrap app (you don’t run the task) and that start your actual app.</p>
<p>I have found this a good way of structuring the startup of an application.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="157893" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/structure-code-to-run-before-any-application-starts/28125/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-157893" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="157893"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="157968" data-post-id="157968">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="apr" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/apr/120/11951_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  apr
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Thanks for the suggestions everyone! I looked at all of them and this reply as well: <a href="https://forum.elixirforum.com/t/change-my-mind-migrations-in-a-start-phase/26337/2" class="inline-onebox" rel="nofollow">Change my mind: Migrations in a start phase - #2 by benwilson512</a>.</p>
<p>I finally decided to use a <code>Genserver</code> like <a class="mention" href="/u/axelson" rel="nofollow">@axelson</a> suggested, but ran it directly in my application supervision tree. Since I need to populate <code>:persistent_term</code>  with DB rows, I need the <code>Repo</code> running. I could always start the repo process in another application that my main application depends on, but just running a temporary <code>Genserver</code> after the <code>Repo</code> process starts in the main application was simpler. Also, the <code>Genserver</code>’s blocking <code>init</code> fn returns <code>:ignore</code> once it populates <code>:persistent_term</code>, so it exits normally without entering the msg receive loop. Works well for my use case <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="157968" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/structure-code-to-run-before-any-application-starts/28125/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-157968" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="157968"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>