Skip to content

Commit

Permalink
Optimize the queries needed for Accounts.list_org_keys (#1614)
Browse files Browse the repository at this point in the history
- The Org related to the Device doesn't need to be preloaded
- Don't load the user (`created_by`) when sending the keys to devices
  • Loading branch information
joshk authored Oct 28, 2024
1 parent 729b03b commit d9b6d39
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
16 changes: 14 additions & 2 deletions lib/nerves_hub/accounts.ex
Original file line number Diff line number Diff line change
Expand Up @@ -368,10 +368,22 @@ defmodule NervesHub.Accounts do
|> Repo.insert()
end

def list_org_keys(%Org{id: org_id}) do
def list_org_keys(org_or_org_id, load_created_by \\ true)

def list_org_keys(%Org{id: org_id}, load_created_by) do
list_org_keys(org_id, load_created_by)
end

def list_org_keys(org_id, load_created_by) do
OrgKey
|> where(org_id: ^org_id)
|> preload(:created_by)
|> then(fn query ->
if load_created_by do
preload(query, :created_by)
else
query
end
end)
|> order_by(:id)
|> Repo.all()
end
Expand Down
3 changes: 1 addition & 2 deletions lib/nerves_hub_web/channels/device_channel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ defmodule NervesHubWeb.DeviceChannel do
device
|> Devices.verify_deployment()
|> Deployments.set_deployment()
|> Repo.preload(:org)
|> deployment_preload()

maybe_send_public_keys(device, socket, params)
Expand Down Expand Up @@ -507,7 +506,7 @@ defmodule NervesHubWeb.DeviceChannel do
defp maybe_send_public_keys(device, socket, params) do
Enum.each(["fwup_public_keys", "archive_public_keys"], fn key_type ->
if params[key_type] == "on_connect" do
org_keys = NervesHub.Accounts.list_org_keys(device.org)
org_keys = NervesHub.Accounts.list_org_keys(device.org_id, false)

push(socket, key_type, %{
keys: Enum.map(org_keys, fn ok -> ok.key end)
Expand Down

0 comments on commit d9b6d39

Please sign in to comment.