Skip to content

Commit

Permalink
Clean up cached client reconnection info when the websocket process dies
Browse files Browse the repository at this point in the history
  • Loading branch information
alco committed Apr 23, 2024
1 parent 4169713 commit e3973a7
Showing 1 changed file with 20 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,6 @@ defmodule Electric.Satellite.ClientReconnectionInfo do
"""
@spec restore_cache_for_client(Connectors.origin(), String.t()) :: :ok | {:error, Exception.t()}
def restore_cache_for_client(origin, client_id) do
clear_all_ets_data(client_id)
GenServer.call(name(origin), {:restore_cache_for_client, client_id})
end

Expand Down Expand Up @@ -814,16 +813,20 @@ defmodule Electric.Satellite.ClientReconnectionInfo do
actions_table: actions_table,
debounce_timer: nil,
debounced_client_ids: [],
waiting_callers: []
waiting_callers: [],
client_monitors: %{}
}}
end

@impl GenServer
def handle_call({:restore_cache_for_client, client_id}, from, state) do
def handle_call({:restore_cache_for_client, client_id}, {pid, _} = from, state) do
monitor = Process.monitor(pid)

state =
state
|> Map.update!(:debounced_client_ids, &[client_id | &1])
|> Map.update!(:waiting_callers, &[from | &1])
|> Map.update!(:client_monitors, &Map.put(&1, monitor, client_id))
|> debounce()

{:noreply, state}
Expand All @@ -836,6 +839,20 @@ defmodule Electric.Satellite.ClientReconnectionInfo do
{:noreply, %{state | debounce_timer: nil, debounced_client_ids: [], waiting_callers: []}}
end

def handle_info({:DOWN, monitor, :process, _pid, _reason}, state) do
%{client_monitors: client_monitors} = state

with {:ok, client_id} <- Map.fetch(client_monitors, monitor) do
Logger.debug(
"WebsocketProcess for client_id=#{client_id} is down. Cleaning up cached info."
)

clear_all_ets_data(client_id)
end

{:noreply, %{state | client_monitors: Map.delete(client_monitors, monitor)}}
end

defp debounce(%{debounce_timer: nil} = state) do
timer = Process.send_after(self(), :restore_cache_for_clients, @debounce_duration)
%{state | debounce_timer: timer}
Expand Down

0 comments on commit e3973a7

Please sign in to comment.