Skip to content

Commit c0f4caa

Browse files
author
Zach Robert
committed
[feat] performing checks as gen server
1 parent 505ef20 commit c0f4caa

File tree

3 files changed

+65
-1
lines changed

3 files changed

+65
-1
lines changed

lib/situation_room/application.ex

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ 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+
SituationRoom.CheckSup
2122
]
2223

2324
# See https://hexdocs.pm/elixir/Supervisor.html
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
defmodule SituationRoom.CheckGen 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.Check.run(site.endpoint) do
26+
{:ok, %{"response_time" => res_time, "status" => status}} ->
27+
IO.inspect(
28+
Check.create_check(%{
29+
"site_id" => site.id,
30+
"response_time" => res_time,
31+
"status_code" => status
32+
})
33+
)
34+
35+
{:error, reason} ->
36+
reason
37+
end
38+
end
39+
40+
defp schedule_site_check(interval) do
41+
Process.send_after(self(), :run_check, interval)
42+
end
43+
end
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
defmodule SituationRoom.CheckSup 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.Site.get_all_sites() do
15+
Supervisor.child_spec({SituationRoom.CheckGen, site}, id: site.id)
16+
end
17+
18+
Supervisor.init(children, strategy: :one_for_one)
19+
end
20+
end

0 commit comments

Comments
 (0)