watchdog.ex 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. defmodule CvGen.Watchdog do
  2. use GenServer
  3. require Logger
  4. @name __MODULE__
  5. def start_link(_), do: GenServer.start(__MODULE__, [], name: @name)
  6. def force_reload(), do: GenServer.call(@name, :reload, 500)
  7. @impl true
  8. def init(_), do: {:ok, %{tpl_hash: "", json_hash: ""}, {:continue, :trigger_timer}}
  9. @impl true
  10. def handle_info(:timer_expired, state) do
  11. state =
  12. with tpl_hash <- hash("lib/templates/cv.html.eex"),
  13. json_hash <- hash("lib/templates/cv.json") do
  14. if tpl_hash != state.tpl_hash or json_hash != state.json_hash do
  15. Logger.info("Content has changed, reloading")
  16. CvGen.generate()
  17. %{tpl_hash: tpl_hash, json_hash: json_hash}
  18. else
  19. state
  20. end
  21. end
  22. {:noreply, state, {:continue, :trigger_timer}}
  23. end
  24. defp hash(path) do
  25. contents = File.read!(path)
  26. :crypto.hash(:md5, contents) |> Base.encode16()
  27. end
  28. @impl true
  29. def handle_call(:reload, _, _) do
  30. CvGen.generate()
  31. {:reply, :ok,
  32. %{tpl_hash: hash("lib/templates/cv.html.eex"), json_hash: hash("lib/templates/cv.json")},
  33. {:continue, :trigger_timer}}
  34. end
  35. @impl true
  36. def handle_continue(:trigger_timer, state) do
  37. Process.send_after(self(), :timer_expired, 100)
  38. {:noreply, state}
  39. end
  40. end