Skip to content

Commit a50dbe7

Browse files
author
Zach Robert
committed
[feat] perform checks as gen server
1 parent 850348a commit a50dbe7

File tree

3 files changed

+72
-1
lines changed

3 files changed

+72
-1
lines changed

lib/situation_room/application.ex

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ defmodule SituationRoom.Application do
1515
# Start the PubSub system
1616
{Phoenix.PubSub, name: SituationRoom.PubSub},
1717
# Start the Endpoint (http/https)
18-
SituationRoomWeb.Endpoint
18+
SituationRoomWeb.Endpoint,
1919
# Start a worker by calling: SituationRoom.Worker.start_link(arg)
2020
# {SituationRoom.Worker, arg}
21+
{Finch, name: SituationRoom.Finch},
22+
SituationRoom.ChecksSupervisor
2123
]
2224

2325
# See https://hexdocs.pm/elixir/Supervisor.html
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
defmodule SituationRoom.ChecksGenServer do
2+
@moduledoc """
3+
The Genserver for checking sites
4+
"""
5+
use GenServer
6+
require Logger
7+
alias SituationRoom.Site.Check
8+
9+
def start_link(args) do
10+
GenServer.start_link(__MODULE__, args)
11+
end
12+
13+
def init(site) do
14+
schedule_site_check(site.interval)
15+
{:ok, site}
16+
end
17+
18+
def handle_info(:run_check, site) do
19+
handle_check(site)
20+
schedule_site_check(site.interval)
21+
{:noreply, site}
22+
end
23+
24+
defp handle_check(site) do
25+
case SituationRoom.Site.LiveCheck.run(site.endpoint) do
26+
{:ok, %{response_time: res_time, status: status}} ->
27+
Check.create_check(%{
28+
"site_id" => site.id,
29+
"response_time" => res_time,
30+
"status_code" => status
31+
})
32+
33+
{:error, reason} ->
34+
reason
35+
end
36+
end
37+
38+
defp schedule_site_check(interval) do
39+
Process.send_after(self(), :run_check, interval)
40+
end
41+
end
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
defmodule SituationRoom.ChecksSupervisor do
2+
@moduledoc """
3+
Supervisor for Site Check GenServers
4+
"""
5+
use Supervisor
6+
7+
def start_link(opts) do
8+
Supervisor.start_link(__MODULE__, opts)
9+
end
10+
11+
@impl true
12+
def init(_opts) do
13+
children =
14+
for site <- SituationRoom.Sites.get_all_sites() do
15+
Supervisor.child_spec({SituationRoom.ChecksGenServer, site}, id: site.id)
16+
end
17+
18+
Supervisor.init(children, strategy: :one_for_one)
19+
end
20+
21+
# def add_child(site) do
22+
# Supervisor.start_child()
23+
# end
24+
25+
# def remove_child() do
26+
# Supervisor.delete_child()
27+
# end
28+
end

0 commit comments

Comments
 (0)