From 1edf1ab4af259593b0e964728cd30d108bc84b46 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Fri, 10 Jan 2025 16:41:25 +1300 Subject: [PATCH] Clean stale `DeviceConnection`s When we added the `DeviceConnection` schema and relationships, we didn't add a way to clean the stale connections, which might linger due to unforeseen circumstances, like the app crashing. --- lib/nerves_hub/devices/connections.ex | 16 ++++++++++++++++ .../workers/clean_device_connection_states.ex | 6 +++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/nerves_hub/devices/connections.ex b/lib/nerves_hub/devices/connections.ex index 4176e65ac..08279283f 100644 --- a/lib/nerves_hub/devices/connections.ex +++ b/lib/nerves_hub/devices/connections.ex @@ -128,4 +128,20 @@ defmodule NervesHub.Devices.Connections do |> distinct(:device_id) |> order_by([:device_id, desc: :last_seen_at]) end + + def clean_stale_connections() do + interval = Application.get_env(:nerves_hub, :device_last_seen_update_interval_minutes) + a_minute_ago = DateTime.shift(DateTime.utc_now(), minute: -(interval + 1)) + + DeviceConnection + |> where(status: :connected) + |> where([d], d.last_seen_at < ^a_minute_ago) + |> Repo.update_all( + set: [ + status: :disconnected, + disconnected_at: DateTime.utc_now(), + disconnected_reason: "Stale connection" + ] + ) + end end diff --git a/lib/nerves_hub/workers/clean_device_connection_states.ex b/lib/nerves_hub/workers/clean_device_connection_states.ex index 3d554eb3a..3008237a8 100644 --- a/lib/nerves_hub/workers/clean_device_connection_states.ex +++ b/lib/nerves_hub/workers/clean_device_connection_states.ex @@ -3,9 +3,13 @@ defmodule NervesHub.Workers.CleanDeviceConnectionStates do max_attempts: 5, queue: :device + alias NervesHub.Devices + alias NervesHub.Devices.Connections + @impl true def perform(_) do - NervesHub.Devices.clean_connection_states() + Devices.clean_connection_states() + Connections.clean_stale_connections() :ok end