Skip to content

Commit

Permalink
Clean stale DeviceConnections
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
joshk committed Jan 10, 2025
1 parent 38dee14 commit 1edf1ab
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
16 changes: 16 additions & 0 deletions lib/nerves_hub/devices/connections.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 5 additions & 1 deletion lib/nerves_hub/workers/clean_device_connection_states.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 1edf1ab

Please sign in to comment.