From 7b8f5beeaf67d8fe1902523156924c239d03a50e Mon Sep 17 00:00:00 2001 From: Rowa Date: Mon, 4 Nov 2024 22:16:59 +0300 Subject: [PATCH] time out idle game process --- lib/battle_ship/game.ex | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/battle_ship/game.ex b/lib/battle_ship/game.ex index 90fe253..94b66e1 100644 --- a/lib/battle_ship/game.ex +++ b/lib/battle_ship/game.ex @@ -3,10 +3,11 @@ defmodule BattleShip.Game do use GenServer, start: {__MODULE__, :start_link, []}, - restart: :transient, + restart: :permanent, shutdown: 5000, type: :worker + alias __MODULE__ alias BattleShip.Board alias BattleShip.Coordinate alias BattleShip.Guesses @@ -14,13 +15,14 @@ defmodule BattleShip.Game do alias BattleShip.Ship @players [:player1, :player2] + @timeout 60 * 60 * 24 * 1000 @spec via_tuple(String.t()) :: {:via, Registry, {Registry.Game, String.t()}} def via_tuple(name), do: {:via, Registry, {Registry.Game, name}} @spec start_link(binary()) :: {:ok, pid()} | :ignore def start_link(name) when is_binary(name) do - case GenServer.start_link(__MODULE__, name, name: via_tuple(name)) do + case GenServer.start_link(Game, name, name: via_tuple(name)) do {:ok, pid} -> {:ok, pid} @@ -39,7 +41,7 @@ defmodule BattleShip.Game do def init(name) do player1 = %{name: name, board: Board.new(), guesses: Guesses.new()} player2 = %{name: nil, board: Board.new(), guesses: Guesses.new()} - {:ok, %{player1: player1, player2: player2, rules: %Rules{}}} + {:ok, %{player1: player1, player2: player2, rules: %Rules{}}, @timeout} end @spec add_player(pid(), binary()) :: :error | {:reply, :ok, %{}} @@ -135,11 +137,15 @@ defmodule BattleShip.Game do end end + def handle_info(:timeout, state_data) do + {:stop, {:shutdown, :timeout}, state_data} + end + defp update_player2_name(state_data, name), do: put_in(state_data.player2.name, name) defp update_rules(state_data, rules), do: %{state_data | rules: rules} - defp reply_success(state_data, reply), do: {:reply, reply, state_data} + defp reply_success(state_data, reply), do: {:reply, reply, state_data, @timeout} defp update_board(state_data, player, board), do: Map.update!(state_data, player, fn player -> %{player | board: board} end)