From 021e4121673493418fd032648d8df9969183ed53 Mon Sep 17 00:00:00 2001 From: Owen Rees Date: Fri, 13 Nov 2026 15:36:59 +0100 Subject: [PATCH] Make tablebase and empty-pool failures recoverable (#163) (#170) Tablebase failures now render one message per class, with a Retry action when fetching again can help. The generic class no longer interpolates inspect(reason) into the page; the reason goes to the log instead. Positions outside the tablebase offer the next puzzle (in a session) or the existing back link, rather than a futile retry. Train's no-puzzles and exhausted-difficulty flashes become in-page states with Retry and Change difficulty. The guest pool gets the same treatment, and GuestLimits.remaining/1 lets a guest see the wall, or the empty pool, without spending a puzzle. --- docs/error-states.md | 3 + lib/chesstrainer/guest_limits.ex | 27 +++ .../components/play_components.ex | 38 +++-- .../live/endgame_live/guest_train.ex | 158 ++++++++++++------ .../live/endgame_live/play.ex | 2 +- .../live/endgame_live/play_core.ex | 82 ++++++--- .../live/endgame_live/train.ex | 143 +++++++++++----- test/chesstrainer/guest_limits_test.exs | 12 ++ .../live/endgame_live/guest_train_test.exs | 39 ++++- .../live/endgame_live/play_test.exs | 48 +++++- .../live/endgame_live/train_test.exs | 57 +++++++ 11 files changed, 476 insertions(+), 133 deletions(-) diff --git a/docs/error-states.md b/docs/error-states.md index 4fe5011..69d13ee 100644 --- a/docs/error-states.md +++ b/docs/error-states.md @@ -15,6 +15,9 @@ Verdicts: "Internal detail" means an exception term, an `inspect/1` result, a raw HTTP status body, a stacktrace, or a raw FEN appearing in rendered HTML. +**Status:** #163 implements T1–T6, S1–S3 and S5. The rows below describe the +state before that change; #164 records what was verified afterwards. + ## Play and tablebase | ID | State | Trigger | What the user sees today | Verdict | Action | diff --git a/lib/chesstrainer/guest_limits.ex b/lib/chesstrainer/guest_limits.ex index 17c2887..210525b 100644 --- a/lib/chesstrainer/guest_limits.ex +++ b/lib/chesstrainer/guest_limits.ex @@ -40,6 +40,18 @@ defmodule Chesstrainer.GuestLimits do @doc "Clears every budget. Intended for tests." def reset, do: GenServer.call(__MODULE__, :reset) + @doc """ + Returns the puzzles left today without consuming one. + + Mirrors `take/2`'s result shape so a caller can show the wall before doing + work that would otherwise spend a puzzle. + """ + @spec remaining(address, Date.t()) :: + {:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer} + def remaining(address, today \\ Date.utc_today()) do + GenServer.call(__MODULE__, {:remaining, address, today}) + end + @doc "The daily puzzle allowance for a guest." def limit, do: config() |> Keyword.get(:limit, @default_limit) @@ -67,6 +79,21 @@ defmodule Chesstrainer.GuestLimits do @impl true def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state} + def handle_call({:remaining, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state} + + def handle_call({:remaining, address, today}, _from, state) do + day = Date.to_gregorian_days(today) + key = key(state.secret, day, address) + + case count(key, day) do + used when used >= state.limit -> + {:reply, {:limit_reached, ms_until_utc_midnight()}, state} + + used -> + {:reply, {:ok, state.limit - used}, state} + end + end + def handle_call({:take, address, today}, _from, state) do day = Date.to_gregorian_days(today) key = key(state.secret, day, address) diff --git a/lib/chesstrainer_web/components/play_components.ex b/lib/chesstrainer_web/components/play_components.ex index a29553a..82492c5 100644 --- a/lib/chesstrainer_web/components/play_components.ex +++ b/lib/chesstrainer_web/components/play_components.ex @@ -14,14 +14,14 @@ defmodule ChesstrainerWeb.PlayComponents do attr :endgame, :any, required: true attr :fen, :string, default: nil attr :status, :atom, required: true - attr :blocked_reason, :string, default: nil + attr :blocked, :map, default: nil attr :best_move, :string, default: nil attr :plies, :list, required: true attr :line, :list, required: true attr :reviewing, :boolean, required: true attr :review_index, :integer, required: true attr :review_tablebase, :any, default: nil - attr :review_blocked, :string, default: nil + attr :review_blocked, :map, default: nil attr :awaiting_reply, :boolean, required: true attr :last_grade, :atom, default: nil attr :awaiting_best_line, :boolean, default: false @@ -169,7 +169,23 @@ defmodule ChesstrainerWeb.PlayComponents do > <.icon name="hero-eye" /> Review - <.button phx-click="reset" variant="primary"> + <.button + :if={@status == :blocked && @blocked && @blocked.retry} + id="retry-blocked" + phx-click="reset" + variant="primary" + > + <.icon name="hero-arrow-path" /> Retry + + <.button + :if={@status == :blocked && @blocked && !@blocked.retry && @session} + id="next-after-blocked" + phx-click="next_puzzle" + variant="primary" + > + Next puzzle + + <.button :if={@status != :blocked} phx-click="reset" variant="primary"> <.icon name="hero-arrow-path" /> {if @status in [:solved, :failed], do: "Try again", else: "Reset"} @@ -194,7 +210,7 @@ defmodule ChesstrainerWeb.PlayComponents do <%= cond do %> <% @review_blocked -> %>

Best move unavailable here

-

{@review_blocked}

+

{@review_blocked.message}

<% @review_tablebase -> %>

Best move:

{PlayCore.best_move_text(@review_tablebase) || "—"}

@@ -211,9 +227,9 @@ defmodule ChesstrainerWeb.PlayComponents do <%= cond do %> <% @status == :loading -> %>

Loading tablebase…

- <% @status == :blocked -> %> -

Tablebase unavailable

-

{@blocked_reason}

+ <% @status == :blocked && @blocked -> %> +

{@blocked.title}

+

{@blocked.message}

<% @status == :solved -> %>

{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"} @@ -460,8 +476,7 @@ defmodule ChesstrainerWeb.PlayComponents do defp move_hint(:loading, _awaiting), do: "Loading the tablebase…" - defp move_hint(:blocked, _awaiting), - do: "The tablebase is unavailable, so moves cannot be entered." + defp move_hint(:blocked, _awaiting), do: "Moves are paused." defp move_hint(status, _awaiting) when status in [:solved, :failed], do: "This puzzle is finished. Reset or try again." @@ -488,7 +503,10 @@ defmodule ChesstrainerWeb.PlayComponents do "Loading the tablebase." assigns.status == :blocked -> - "Tablebase unavailable. #{assigns.blocked_reason || "Moves cannot be graded."}" + case assigns.blocked do + %{title: title, message: message} -> "#{title}. #{message}" + _ -> "Tablebase unavailable." + end assigns.reviewing -> review_announcement(assigns) diff --git a/lib/chesstrainer_web/live/endgame_live/guest_train.ex b/lib/chesstrainer_web/live/endgame_live/guest_train.ex index 943c54e..885fdbb 100644 --- a/lib/chesstrainer_web/live/endgame_live/guest_train.ex +++ b/lib/chesstrainer_web/live/endgame_live/guest_train.ex @@ -70,12 +70,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do Picking a random puzzle…

-

- No endgames are available yet. Please check back soon. -

+

No more puzzles are available right now

+

+ Try again in a moment, or create a free account to train at your level. +

+
+ <.button id="retry-pool" phx-click="retry_pool" variant="primary"> + <.icon name="hero-arrow-path" /> Retry + + <.button navigate={~p"/users/register"}>Sign up free + <.button navigate={~p"/users/log-in"}>Log in +
+ + +
+

No endgames are available yet

+

+ Please check back soon, or create a free account to be ready when they land. +

+
+ <.button id="retry-pool" phx-click="retry_pool" variant="primary"> + <.icon name="hero-arrow-path" /> Retry + + <.button navigate={~p"/users/register"}>Sign up free + <.button navigate={~p"/users/log-in"}>Log in +
+
""" end @@ -120,6 +149,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do socket |> assign(:loading, true) |> assign(:endgame, nil) + |> assign(:empty, nil) |> assign(:guest_remaining, nil) |> assign(:limit_reached, nil) |> assign(:guest_address, nil)} @@ -127,29 +157,14 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do end @impl true - def handle_event("next_puzzle", _params, socket) do - case GuestLimits.take(socket.assigns.guest_address) do - {:ok, remaining} -> - endgame = - Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) || - Endgames.random_endgame() + def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)} - case endgame do - nil -> - {:noreply, put_flash(socket, :info, "No more puzzles are available right now.")} - - endgame -> - {:noreply, - socket - |> assign(:guest_remaining, remaining) - |> PlayCore.init(endgame, page_title: "Train")} - end - - {:limit_reached, retry_ms} -> - {:noreply, - socket - |> assign(:guest_remaining, nil) - |> assign(:limit_reached, retry_ms)} + def handle_event("retry_pool", _params, socket) do + if socket.assigns.empty == :exhausted do + {:noreply, next_puzzle(socket)} + else + {:ok, socket} = take_puzzle(socket, socket.assigns.guest_address) + {:noreply, socket} end end @@ -193,36 +208,75 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket) - defp take_puzzle(socket, address) do - case GuestLimits.take(address) do - {:ok, remaining} -> - socket = - socket - |> assign(:loading, false) - |> assign(:guest_address, address) - |> assign(:guest_remaining, remaining) - |> assign(:limit_reached, nil) - - {:ok, load_random_endgame(socket)} - + defp next_puzzle(socket) do + case GuestLimits.remaining(socket.assigns.guest_address) do {:limit_reached, retry_ms} -> - {:ok, - socket - |> assign(:loading, false) - |> assign(:guest_address, address) - |> assign(:guest_remaining, nil) - |> assign(:limit_reached, retry_ms) - |> assign(:endgame, nil)} + socket + |> assign(:guest_remaining, nil) + |> assign(:empty, nil) + |> assign(:limit_reached, retry_ms) + + {:ok, _remaining} -> + endgame = + Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) || + Endgames.random_endgame() + + case endgame do + nil -> assign(socket, :empty, :exhausted) + endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame) + end end end - defp load_random_endgame(socket) do - case Endgames.random_endgame() do - nil -> assign(socket, :endgame, nil) - endgame -> PlayCore.init(socket, endgame, page_title: "Train") + defp take_puzzle(socket, address) do + case GuestLimits.remaining(address) do + {:limit_reached, retry_ms} -> + {:ok, limit_wall(socket, address, retry_ms)} + + {:ok, _remaining} -> + case Endgames.random_endgame() do + nil -> {:ok, empty_pool(socket, address)} + endgame -> {:ok, start_guest_puzzle(socket, address, endgame)} + end end end + defp start_guest_puzzle(socket, address, endgame) do + case GuestLimits.take(address) do + {:ok, remaining} -> + socket + |> assign(:loading, false) + |> assign(:guest_address, address) + |> assign(:guest_remaining, remaining) + |> assign(:limit_reached, nil) + |> assign(:empty, nil) + |> PlayCore.init(endgame, page_title: "Train") + + {:limit_reached, retry_ms} -> + limit_wall(socket, address, retry_ms) + end + end + + defp empty_pool(socket, address) do + socket + |> assign(:loading, false) + |> assign(:guest_address, address) + |> assign(:endgame, nil) + |> assign(:empty, nil) + |> assign(:guest_remaining, nil) + |> assign(:limit_reached, nil) + end + + defp limit_wall(socket, address, retry_ms) do + socket + |> assign(:loading, false) + |> assign(:guest_address, address) + |> assign(:guest_remaining, nil) + |> assign(:limit_reached, retry_ms) + |> assign(:endgame, nil) + |> assign(:empty, nil) + end + defp signed_in?(socket) do case socket.assigns.current_scope do %{user: %{}} -> true diff --git a/lib/chesstrainer_web/live/endgame_live/play.ex b/lib/chesstrainer_web/live/endgame_live/play.ex index f584bb4..00a2835 100644 --- a/lib/chesstrainer_web/live/endgame_live/play.ex +++ b/lib/chesstrainer_web/live/endgame_live/play.ex @@ -48,7 +48,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do endgame={@endgame} fen={@fen} status={@status} - blocked_reason={@blocked_reason} + blocked={@blocked} best_move={@best_move} plies={@plies} line={@line} diff --git a/lib/chesstrainer_web/live/endgame_live/play_core.ex b/lib/chesstrainer_web/live/endgame_live/play_core.ex index 3bb3fda..4746e85 100644 --- a/lib/chesstrainer_web/live/endgame_live/play_core.ex +++ b/lib/chesstrainer_web/live/endgame_live/play_core.ex @@ -21,8 +21,23 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do alias Chesstrainer.Ratings alias ChesstrainerWeb.RatingComponents + require Logger + @uci_pattern ~r/^[a-h][1-8][a-h][1-8][qrbn]?$/ + @typedoc """ + A blocked puzzle's user-facing state. + + `kind` names the failure class, `title` and `message` are the only copy shown + to the player, and `retry` says whether fetching again can plausibly help. + """ + @type blocked :: %{ + kind: :cooldown | :rate_limited | :not_covered | :unavailable, + title: String.t(), + message: String.t(), + retry: boolean() + } + @doc """ Loads `endgame` and starts an attempt on it. @@ -39,7 +54,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do |> assign(:fen, endgame.fen) |> assign(:tablebase, nil) |> assign(:status, :loading) - |> assign(:blocked_reason, nil) + |> assign(:blocked, nil) |> assign(:best_move, nil) |> assign(:plies, []) |> assign(:reviewing, false) @@ -164,7 +179,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do |> snapshot(fen, tablebase) |> assign(:awaiting_reply, false) |> assign(:status, :playing) - |> assign(:blocked_reason, nil) + |> assign(:blocked, nil) |> assign(:move_input_error, nil) |> push_event("resume_board", %{})} @@ -173,7 +188,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do socket |> assign(:awaiting_reply, false) |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other))} + |> assign(:blocked, blocked(other))} end end else @@ -359,14 +374,14 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do |> assign(:tablebase, tablebase) |> snapshot(fen, tablebase) |> assign(:status, :playing) - |> assign(:blocked_reason, nil) + |> assign(:blocked, nil) |> push_init_board(fen) other -> socket |> assign(:tablebase, nil) |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other)) + |> assign(:blocked, blocked(other)) |> push_init_board(fen) end else @@ -383,25 +398,54 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do }) end - defp blocked_reason({:cooldown, remaining_ms}) do + @doc """ + Classifies a failed tablebase fetch into the copy the player sees. + + One message per failure class; the underlying reason never reaches the page. + """ + @spec blocked(term()) :: blocked() + def blocked({:cooldown, remaining_ms}) do seconds = max(div(remaining_ms + 999, 1000), 1) - "The tablebase is rate-limited. Try again in about #{seconds}s." + + %{ + kind: :cooldown, + title: "Tablebase cooling down", + message: "The tablebase is rate-limited. Try again in about #{seconds}s.", + retry: true + } end - defp blocked_reason({:error, {:too_many_requests, _, _}}) do - "The tablebase is rate-limited. Try again in a minute." + def blocked({:error, {:too_many_requests, _, _}}) do + %{ + kind: :rate_limited, + title: "Tablebase rate-limited", + message: "The tablebase is rate-limited. Try again in a minute.", + retry: true + } end - defp blocked_reason({:error, {:client_error, 404, _}}) do - "This position is not covered by the tablebase." + def blocked({:error, {:client_error, 404, _}}), do: not_covered() + def blocked({:error, :not_covered}), do: not_covered() + def blocked({:error, :invalid_endgame}), do: not_covered() + + def blocked({:error, reason}) do + Logger.warning("tablebase.unavailable", reason: inspect(reason)) + + %{ + kind: :unavailable, + title: "Tablebase unavailable", + message: "The tablebase is unavailable right now. Try again in a moment.", + retry: true + } end - defp blocked_reason({:error, :not_covered}) do - "This position is not covered by the tablebase." - end - - defp blocked_reason({:error, reason}) do - "The tablebase is unavailable (#{inspect(reason)})." + defp not_covered do + %{ + kind: :not_covered, + title: "Position not covered", + message: "This position isn't in the tablebase, so it can't be graded.", + retry: false + } end defp grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate) do @@ -464,7 +508,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do {:noreply, socket |> assign(:status, :blocked) - |> assign(:blocked_reason, blocked_reason(other))} + |> assign(:blocked, blocked(other))} end end @@ -727,7 +771,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do :error -> case Tablebase.new(fen) do {:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)} - other -> {:unavailable, blocked_reason(other), socket} + other -> {:unavailable, blocked(other), socket} end end end diff --git a/lib/chesstrainer_web/live/endgame_live/train.ex b/lib/chesstrainer_web/live/endgame_live/train.ex index 72bd281..f2b2738 100644 --- a/lib/chesstrainer_web/live/endgame_live/train.ex +++ b/lib/chesstrainer_web/live/endgame_live/train.ex @@ -77,11 +77,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do + +
+

You've finished every puzzle at this difficulty

+

+ There are no more {difficulty_label(@session.difficulty)} puzzles right now. + Try again, or pick another difficulty. +

+
+ <.button id="retry-pool" phx-click="retry_pool" variant="primary"> + <.icon name="hero-arrow-path" /> Retry + + <.button id="change-difficulty" phx-click="stop_session"> + Change difficulty + +
+
<% else %>
@@ -155,6 +176,19 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
+
+

No puzzles available right now

+

+ There are no {difficulty_label(@pool.difficulty)} puzzles yet. Try again, or choose another difficulty. +

+ <.button id="retry-pool" phx-click="retry_pool" class="mt-3"> + <.icon name="hero-arrow-path" /> Retry + +
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %> <.button @@ -188,62 +222,32 @@ defmodule ChesstrainerWeb.EndgameLive.Train do |> assign(:last_session, nil) |> assign(:puzzle_started_mono, nil) |> assign(:puzzle_counted, false) + |> assign(:pool, nil) |> assign(:user_rating, socket.assigns.current_scope.user.rating) |> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)} end @impl true def handle_event("start_session", %{"difficulty" => difficulty}, socket) do - difficulty = parse_difficulty(difficulty) - - case Puzzles.next_endgame(selection_user(socket), difficulty) do - nil -> - {:noreply, put_flash(socket, :error, "No puzzles are available right now.")} - - endgame -> - session = %{ - difficulty: difficulty, - started_at_ms: System.system_time(:millisecond), - baseline: socket.assigns.user_rating, - count: 0, - sum_ms: 0 - } - - socket = - socket - |> assign(:session, session) - |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) - |> assign(:puzzle_counted, false) - |> assign(:last_rating_delta, nil) - |> PlayCore.init(endgame, page_title: "Train") - - {:noreply, socket} - end + {:noreply, start_session(socket, parse_difficulty(difficulty))} end - def handle_event("next_puzzle", _params, socket) do - session = socket.assigns.session + def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)} - if session do - case Puzzles.next_endgame(selection_user(socket), session.difficulty, - exclude_ids: [socket.assigns.endgame.id] - ) do + def handle_event("retry_pool", _params, socket) do + socket = + case socket.assigns.session do nil -> - {:noreply, put_flash(socket, :info, "No more puzzles at this difficulty.")} + case socket.assigns.pool do + %{difficulty: difficulty} -> start_session(socket, difficulty) + _ -> socket + end - endgame -> - socket = - socket - |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) - |> assign(:puzzle_counted, false) - |> assign(:last_rating_delta, nil) - |> PlayCore.init(endgame, page_title: "Train") - - {:noreply, socket} + _session -> + next_puzzle(socket) end - else - {:noreply, socket} - end + + {:noreply, socket} end def handle_event("stop_session", _params, socket) do @@ -253,7 +257,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating)) end - {:noreply, assign(socket, :session, nil)} + {:noreply, socket |> assign(:session, nil) |> assign(:pool, nil)} end def handle_event("endgame_move_played", params, socket) do @@ -300,6 +304,53 @@ defmodule ChesstrainerWeb.EndgameLive.Train do def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket) + defp start_session(socket, difficulty) do + case Puzzles.next_endgame(selection_user(socket), difficulty) do + nil -> + assign(socket, :pool, %{difficulty: difficulty}) + + endgame -> + session = %{ + difficulty: difficulty, + started_at_ms: System.system_time(:millisecond), + baseline: socket.assigns.user_rating, + count: 0, + sum_ms: 0 + } + + socket + |> assign(:session, session) + |> assign(:pool, nil) + |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) + |> assign(:puzzle_counted, false) + |> assign(:last_rating_delta, nil) + |> PlayCore.init(endgame, page_title: "Train") + end + end + + defp next_puzzle(socket) do + session = socket.assigns.session + + if session do + case Puzzles.next_endgame(selection_user(socket), session.difficulty, + exclude_ids: [socket.assigns.endgame.id] + ) do + nil -> + assign(socket, :pool, %{difficulty: session.difficulty}) + + endgame -> + socket + |> assign(:pool, nil) + |> assign(:puzzle_started_mono, System.monotonic_time(:millisecond)) + |> assign(:puzzle_counted, false) + |> assign(:last_rating_delta, nil) + |> PlayCore.init(endgame, page_title: "Train") + end + else + socket + end + end + # A completed puzzle contributes one first-attempt time to the average. A # retry happens after this point and is deliberately ignored. defp account_completion(socket) do diff --git a/test/chesstrainer/guest_limits_test.exs b/test/chesstrainer/guest_limits_test.exs index 762c713..6afc689 100644 --- a/test/chesstrainer/guest_limits_test.exs +++ b/test/chesstrainer/guest_limits_test.exs @@ -37,9 +37,21 @@ defmodule Chesstrainer.GuestLimitsTest do assert {:ok, 4} = GuestLimits.take(@other, @today) end + test "remaining reports the budget without consuming it" do + assert {:ok, 5} = GuestLimits.remaining(@address, @today) + assert {:ok, 5} = GuestLimits.remaining(@address, @today) + + assert {:ok, 4} = GuestLimits.take(@address, @today) + assert {:ok, 4} = GuestLimits.remaining(@address, @today) + + for _ <- 1..4, do: assert({:ok, _} = GuestLimits.take(@address, @today)) + assert {:limit_reached, _} = GuestLimits.remaining(@address, @today) + end + test "does not limit a missing address" do assert {:ok, nil} = GuestLimits.take(nil, @today) assert {:ok, nil} = GuestLimits.take(nil, @today) + assert {:ok, nil} = GuestLimits.remaining(nil, @today) end test "reset clears spent budgets" do diff --git a/test/chesstrainer_web/live/endgame_live/guest_train_test.exs b/test/chesstrainer_web/live/endgame_live/guest_train_test.exs index acc4f41..8946f3d 100644 --- a/test/chesstrainer_web/live/endgame_live/guest_train_test.exs +++ b/test/chesstrainer_web/live/endgame_live/guest_train_test.exs @@ -80,11 +80,21 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do end describe "without puzzles" do - test "shows an empty state", %{conn: conn} do + test "shows an empty state with a retry that does not spend a puzzle", %{conn: conn} do {:ok, view, _html} = live(conn, ~p"/guest-train") - assert render(view) =~ "No endgames are available yet" + assert has_element?(view, "#guest-pool-empty") + assert has_element?(view, "#retry-pool") refute has_element?(view, "#endgame-board") + assert {:ok, 5} = GuestLimits.remaining(@guest_address) + + endgame = endgame_fixture() + seed_tablebase(endgame.fen, moves: grading_moves()) + + view |> element("#retry-pool") |> render_click() + + assert has_element?(view, "#endgame-board") + assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4 end end @@ -133,6 +143,31 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4 end + + test "shows an in-page state when no puzzles are left, and retry loads one", %{conn: conn} do + endgame = endgame_fixture() + seed_tablebase(endgame.fen, moves: grading_moves()) + + {:ok, view, _html} = live(conn, ~p"/guest-train") + solve_current(view) + + Repo.delete!(endgame) + + view |> element("#next-puzzle-button") |> render_click() + + assert has_element?(view, "#guest-pool-exhausted") + assert has_element?(view, "#retry-pool") + refute has_element?(view, "#endgame-board") + assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4 + + new_endgame = endgame_fixture() + seed_tablebase(new_endgame.fen, moves: grading_moves()) + + view |> element("#retry-pool") |> render_click() + + assert :sys.get_state(view.pid).socket.assigns.endgame.id == new_endgame.id + assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 3 + end end describe "daily budget" do diff --git a/test/chesstrainer_web/live/endgame_live/play_test.exs b/test/chesstrainer_web/live/endgame_live/play_test.exs index 0c21ade..a3de5b6 100644 --- a/test/chesstrainer_web/live/endgame_live/play_test.exs +++ b/test/chesstrainer_web/live/endgame_live/play_test.exs @@ -12,6 +12,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do alias Chesstrainer.FEN alias Chesstrainer.Ratelimiters alias Chesstrainer.Repo + alias ChesstrainerWeb.EndgameLive.PlayCore defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do %{proxy: {ref, _topic, _}} = view @@ -266,10 +267,22 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do {:ok, view, html} = live(conn, ~p"/endgames/#{endgame.public_code}/play") - assert html =~ "Tablebase unavailable" + assert html =~ "Tablebase cooling down" + refute html =~ "inspect(" + refute html =~ "too_many_requests" play_move(view, endgame, "d1", "d7", "Qd7+") assert render(view) =~ "cannot be graded" + + # Retry re-fetches: with the cache seeded and the cooldown cleared, the + # same puzzle becomes playable in one click. + seed_tablebase(endgame.fen) + Ratelimiters.lichess_reset_cooldown() + + view |> element("#retry-blocked") |> render_click() + + assert :sys.get_state(view.pid).socket.assigns.status == :playing + refute render(view) =~ "Tablebase cooling down" end test "blocks an out-of-range endgame as not covered", %{conn: conn} do @@ -278,8 +291,37 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play") html = render(view) - assert html =~ "Tablebase unavailable" - assert html =~ "not covered by the tablebase" + assert html =~ "Position not covered" + assert html =~ "can't be graded" + refute has_element?(view, "#retry-blocked") + refute html =~ "not_covered" + refute html =~ "inspect(" + end + + @tag capture_log: true + test "classifies every failure class without exposing the reason" do + cases = [ + {{:cooldown, 30_000}, :cooldown, true}, + {{:error, {:too_many_requests, 429, "upstream body"}}, :rate_limited, true}, + {{:error, {:client_error, 404, "upstream body"}}, :not_covered, false}, + {{:error, :not_covered}, :not_covered, false}, + {{:error, :invalid_endgame}, :not_covered, false}, + {{:error, {:server_error, 500, "upstream body"}}, :unavailable, true}, + {{:error, :econnrefused}, :unavailable, true} + ] + + for {input, kind, retry?} <- cases do + blocked = PlayCore.blocked(input) + + assert blocked.kind == kind + assert blocked.retry == retry? + refute blocked.message =~ "inspect" + refute blocked.message =~ "server_error" + refute blocked.message =~ "econnrefused" + refute blocked.message =~ "upstream" + refute blocked.message =~ "500" + refute blocked.message =~ "429" + end end end diff --git a/test/chesstrainer_web/live/endgame_live/train_test.exs b/test/chesstrainer_web/live/endgame_live/train_test.exs index e2342fe..742a4fe 100644 --- a/test/chesstrainer_web/live/endgame_live/train_test.exs +++ b/test/chesstrainer_web/live/endgame_live/train_test.exs @@ -225,6 +225,63 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do end end + describe "empty pools" do + setup :register_and_log_in_user + + test "shows an in-page state when a difficulty has no puzzles", %{conn: conn} do + {:ok, view, _html} = live(conn, ~p"/train") + + view |> element("#difficulty-medium") |> render_click() + + assert has_element?(view, "#pool-empty") + assert has_element?(view, "#retry-pool") + assert has_element?(view, "#difficulty-picker") + refute has_element?(view, "#session-bar") + + endgame = endgame_fixture(rating: 1500) + seed_tablebase(endgame.fen) + + view |> element("#retry-pool") |> render_click() + + assert has_element?(view, "#session-bar") + refute has_element?(view, "#pool-empty") + end + + test "shows an in-page end-of-run state when the difficulty is exhausted", %{conn: conn} do + {view, [_endgame]} = start_medium_session(conn, 1) + solve_current(view) + + view |> element("#next-puzzle-button") |> render_click() + + assert has_element?(view, "#pool-exhausted") + assert has_element?(view, "#retry-pool") + assert has_element?(view, "#change-difficulty") + refute has_element?(view, "#endgame-board") + + view |> element("#change-difficulty") |> render_click() + + assert has_element?(view, "#difficulty-picker") + assert :sys.get_state(view.pid).socket.assigns.session == nil + end + + test "retry loads a puzzle once the pool grows", %{conn: conn} do + {view, [_endgame]} = start_medium_session(conn, 1) + solve_current(view) + + view |> element("#next-puzzle-button") |> render_click() + assert has_element?(view, "#pool-exhausted") + + rating = :sys.get_state(view.pid).socket.assigns.user_rating + new_endgame = endgame_fixture(fen: "4k3/8/8/8/8/8/8/4K3 w - - 0 1", rating: round(rating)) + seed_tablebase(new_endgame.fen) + + view |> element("#retry-pool") |> render_click() + + assert :sys.get_state(view.pid).socket.assigns.endgame.id == new_endgame.id + refute has_element?(view, "#pool-exhausted") + end + end + defp elapsed_id(view) do :sys.get_state(view.pid).socket.assigns.session.started_at_ms end