watchdog.ex 1.2 KB

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