From 68c66b6f9cb98b936cb6b9712d735ef0bee5feff Mon Sep 17 00:00:00 2001 From: Xabier Arbulu Insausti Date: Wed, 5 Jul 2023 17:28:15 +0200 Subject: [PATCH] Filter out deregistered hosts from heartbeat failed checking (#1593) --- .../application/usecases/hosts/heartbeats.ex | 14 +++++++--- .../application/usecases/heartbeats_test.exs | 27 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/lib/trento/application/usecases/hosts/heartbeats.ex b/lib/trento/application/usecases/hosts/heartbeats.ex index 3edb4c793a..d34a03e99b 100644 --- a/lib/trento/application/usecases/hosts/heartbeats.ex +++ b/lib/trento/application/usecases/hosts/heartbeats.ex @@ -4,7 +4,12 @@ defmodule Trento.Heartbeats do """ alias Trento.Domain.Commands.UpdateHeartbeat - alias Trento.Heartbeat + + alias Trento.{ + Heartbeat, + HostReadModel + } + alias Trento.Support.DateService alias Trento.Repo @@ -65,9 +70,12 @@ defmodule Trento.Heartbeats do defp get_all_expired_heartbeats(date_service) do query = from h in Heartbeat, + join: host in HostReadModel, + on: h.agent_id == type(host.id, :string), where: - h.timestamp < - ^DateTime.add(date_service.utc_now(), -@heartbeat_interval, :millisecond) + is_nil(host.deregistered_at) and + h.timestamp < + ^DateTime.add(date_service.utc_now(), -@heartbeat_interval, :millisecond) Repo.all(query) end diff --git a/test/trento/application/usecases/heartbeats_test.exs b/test/trento/application/usecases/heartbeats_test.exs index 5ef41b7fa9..60f15e6a11 100644 --- a/test/trento/application/usecases/heartbeats_test.exs +++ b/test/trento/application/usecases/heartbeats_test.exs @@ -119,4 +119,31 @@ defmodule Trento.HeartbeatsTest do Heartbeats.dispatch_heartbeat_failed_commands(Trento.Support.DateService.Mock) end + + test "filter deregistered hosts from heartbeat failed check" do + %{id: agent_id} = insert(:host, heartbeat: :passing, deregistered_at: DateTime.utc_now()) + %{timestamp: now} = insert(:heartbeat, agent_id: agent_id) + + expired_time = + DateTime.add( + now, + Application.get_env(:trento, Heartbeats)[:interval] + 1, + :millisecond + ) + + expect( + Trento.Support.DateService.Mock, + :utc_now, + fn -> expired_time end + ) + + expect( + Trento.Commanded.Mock, + :dispatch, + 0, + fn _ -> :ok end + ) + + Heartbeats.dispatch_heartbeat_failed_commands(Trento.Support.DateService.Mock) + end end