From 2ec9600a61b89a50d0b8b28b302dae41c9055bae Mon Sep 17 00:00:00 2001 From: Luke Imhoff Date: Mon, 17 Dec 2018 14:40:04 -0600 Subject: [PATCH] Only query for coin balance when channel connected Normally, it is good idea to only query the database once no matter the number of sockets for a channel, but most addresses don't have listeners, so it is cheaper to not query unless the channel is in use. If we start to see popular addresses, con_cache can be used to only do the query once across all connected sockets for the same address. Co-authored-by: Chris McCord --- .../lib/block_scout_web/channels/address_channel.ex | 9 ++++++--- apps/block_scout_web/lib/block_scout_web/notifier.ex | 4 +--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/apps/block_scout_web/lib/block_scout_web/channels/address_channel.ex b/apps/block_scout_web/lib/block_scout_web/channels/address_channel.ex index 83d6d47a34..ffba90df33 100644 --- a/apps/block_scout_web/lib/block_scout_web/channels/address_channel.ex +++ b/apps/block_scout_web/lib/block_scout_web/channels/address_channel.ex @@ -5,13 +5,14 @@ defmodule BlockScoutWeb.AddressChannel do use BlockScoutWeb, :channel alias BlockScoutWeb.{AddressCoinBalanceView, AddressView, InternalTransactionView, TransactionView} + alias Explorer.Chain alias Explorer.Chain.Hash alias Phoenix.View intercept(["balance_update", "coin_balance", "count", "internal_transaction", "transaction"]) - def join("addresses:" <> _address_hash, _params, socket) do - {:ok, %{}, socket} + def join("addresses:" <> address_hash, _params, socket) do + {:ok, %{}, assign(socket, :address_hash, address_hash)} end def handle_out( @@ -63,7 +64,9 @@ defmodule BlockScoutWeb.AddressChannel do def handle_out("transaction", data, socket), do: handle_transaction(data, socket, "transaction") - def handle_out("coin_balance", %{coin_balance: coin_balance}, socket) do + def handle_out("coin_balance", %{block_number: block_number}, socket) do + coin_balance = Chain.get_coin_balance(socket.assigns.address_hash, block_number) + Gettext.put_locale(BlockScoutWeb.Gettext, socket.assigns.locale) rendered_coin_balance = diff --git a/apps/block_scout_web/lib/block_scout_web/notifier.ex b/apps/block_scout_web/lib/block_scout_web/notifier.ex index 7fdacedfec..4816c89dc2 100644 --- a/apps/block_scout_web/lib/block_scout_web/notifier.ex +++ b/apps/block_scout_web/lib/block_scout_web/notifier.ex @@ -95,10 +95,8 @@ defmodule BlockScoutWeb.Notifier do def handle_event(_), do: nil defp broadcast_address_coin_balance(%{address_hash: address_hash, block_number: block_number}) do - coin_balance = Chain.get_coin_balance(address_hash, block_number) - Endpoint.broadcast("addresses:#{address_hash}", "coin_balance", %{ - coin_balance: coin_balance + block_number: block_number }) end