Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove old device_connections in worker, remove connection state stored on device #1807

Merged
merged 6 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ config :nerves_hub,
String.to_integer(System.get_env("DEVICE_LAST_SEEN_UPDATE_INTERVAL_MINUTES", "5")),
device_connection_max_age_days:
String.to_integer(System.get_env("DEVICE_CONNECTION_MAX_AGE_DAYS", "14")),
device_connection_delete_limit:
String.to_integer(System.get_env("DEVICE_CONNECTION_DELETE_LIMIT", "100000")),
deployment_calculator_interval_seconds:
String.to_integer(System.get_env("DEPLOYMENT_CALCULATOR_INTERVAL_SECONDS", "3600")),
mapbox_access_token: System.get_env("MAPBOX_ACCESS_TOKEN"),
Expand Down
32 changes: 18 additions & 14 deletions lib/nerves_hub/devices/connections.ex
Original file line number Diff line number Diff line change
Expand Up @@ -109,26 +109,30 @@ defmodule NervesHub.Devices.Connections do

def delete_old_connections() do
interval = Application.get_env(:nerves_hub, :device_connection_max_age_days)
delete_limit = Application.get_env(:nerves_hub, :device_connection_delete_limit)
days_ago = DateTime.shift(DateTime.utc_now(), day: -interval)

query =
ids =
DeviceConnection
|> join(:inner, [dc], d in Device, on: dc.device_id == d.id)
|> where([dc, _d], dc.last_seen_at < ^days_ago)
|> where([dc, _d], dc.status != :connected)
|> where([dc, d], dc.id != d.latest_connection_id)
|> select([dc, _d], dc.id)

Repo.transaction(fn ->
query
|> Repo.stream(max_rows: 500)
|> Stream.chunk_every(500)
|> Stream.each(fn ids ->
DeviceConnection
|> where([dc], dc.id in ^ids)
|> Repo.delete_all()
end)
|> Stream.run()
end)
|> select([dc], dc.id)
|> limit(^delete_limit)
|> Repo.all()

{delete_count, _} =
DeviceConnection
|> where([d], d.id in ^ids)
|> Repo.delete_all()

if delete_count == 0 do
:ok
else
# relax stress on Ecto pool and go again
Process.sleep(2000)
delete_old_connections()
end
end
end
Loading