Compare commits

...
7 Commits
Author SHA1 Message Date
owenrees aebb2aecfb Fix the error-state regressions from the #164 verification (#171) (#173)
T8: the invalid-FEN flash is generic; the client message and FEN go to the
log. A2: an expired confirmation link says so and lands on log-in, where an
unconfirmed account resends the email. W3: the connection banner gains Reload
and Home actions. D1: a failed export logs and redirects to the data tab with
a support address instead of a bare 500. D2: an unknown export format renders
the styled 404. H1: the empty-database home CTA points at the guest trainer
instead of auth-gated /endgames. X2/X3: the importer hides inspect(reason)
behind generic copy and logs it.

Adds coverage for the T8 copy, A2 destination, D2 404 page, H1 CTA and the W3
actions; the H1 tests now restore the curated-code override so async page
tests cannot poison each other.
2026-11-13 16:46:29 +01:00
owenrees 8934d191ad Record the launch observability decision and verify the error states (#172)
ADR 0012 states the launch bar, the deferred error tracking/metrics/log
shipping with a concrete revisit trigger for each, and the accepted risk of
journald plus off-box backups.

The verification page walks the #162 checklist against a local MIX_ENV=prod
build with forced failures: Postgres stopped, missing tablebase, empty pool,
expired tokens and exhausted guest budget. 14 rows pass, 6 fail; the eight
regressions are filed in #171. The audit's X1 row is corrected: an unknown
play code already returns the styled 404 page.
2026-11-13 16:10:42 +01:00
owenrees 021e412167 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.
2026-11-13 15:36:59 +01:00
owenrees 0563b5aca2 Audit the user-facing error states (#162) (#169)
Records 35 states across play, sessions, accounts, mailing list, site-level, data and admin surfaces, each with its trigger, today's copy, a verdict and a concrete action. Calls out the five places where an internal detail can reach rendered HTML, and closes with the sign-off checklist for #164.
2026-11-13 15:04:30 +01:00
owenrees 0ae4c5b6fd Record the probe outage drill and its outcome (#168)
Adds the stop-Phoenix drill to the runbook, using forced probe runs so the
outage stays under a minute, and a dated drill log with the first run's
results. The log notes that the manual probe was started twice during the
outage, which is why two notifications arrived for one down/up transition.
2026-11-13 14:48:01 +01:00
owenrees b41c8bf1a6 Fix deploy docs: Bot Fight Mode status and probe reinstall (#167)
* Record that Bot Fight Mode is off

Both docs still claimed Bot Fight Mode was enabled. It is off; the Caddy
origin allowlist stays in force. Neither CI nor the on-box probe can get
past it on the free plan, so re-enabling needs the changes tracked in #153.

* Note that the probe must be installed to two places

The timer runs /usr/local/sbin/chesstrainer-probe, not the copy under
/opt/chesstrainer/src. Say so next to the install block, as the backup
section already does, so a changed deploy/probe does not silently drift
from what the timer runs.
2026-11-13 13:57:33 +01:00
owenrees 69b89f68ef Add a public health probe and monitoring runbook (#166)
* move theme picker position in add endgames form

* Add branded favicons and web manifest

- Replace the placeholder favicon with the knight mark: .ico (16/32/48),
  SVG, and 16/32 PNGs.
- Add opaque apple-touch and Android launcher icons plus a site
  webmanifest naming the app and using the brand palette.
- Link the icon set, manifest, and theme-color from the root layout and
  the 404/500 pages.
- Whitelist the new static files in static_paths/0 and the prelaunch
  allowlist so they are served in production and behind the gate.
- Sync the coming-soon site's favicon.ico and drop the unused Phoenix
  logo.

* Add a public health probe and monitoring runbook

Probe https://<PHX_HOST>/health through Cloudflare every two minutes and
report to a healthchecks.io check. A healthy run posts the raw health JSON;
a tablebase mismatch is a green check-in with the mismatch recorded; a
non-200, non-JSON, down database or network failure posts one fail ping with
the response body and a loopback cross-check as evidence.

--dry-run evaluates the success, degraded, fail, non-JSON and unreachable
fixtures without reading config or touching the network. The runbook covers
the healthchecks.io check, install, what /health proves, Beszel's blind spot
and the drills.

* Fix theme picker search after moving it into the endgame form

The picker moved inside the endgame form, which nested the component's
own <form>. Browsers, and the LiveView test DOM, drop a nested form along
with its phx-change and phx-submit bindings, so the search box did nothing
and three form tests lost their #theme-form selector.

The component now renders no form: phx-change sits on the search input,
which works both inside the endgame form and standalone on the bulk
importer. The unreachable create_theme_from_search handlers go away; theme
creation uses the existing button. Tests search through the input and
click that button.
2026-11-13 13:24:35 +01:00
47 changed files with 1590 additions and 200 deletions
+228 -5
View File
@@ -100,6 +100,10 @@ DNS:
`/etc/chesstrainer/postgres.env` holds the Postgres container credentials,
also `root:root` and `0600`.
`/etc/chesstrainer/probe.env` holds the public probe's URL and its
healthchecks.io ping URL, also `root:root` and `0600`. See §Monitoring and
alerting.
The app runs as the dedicated `chesstrainer` system user. It must own
`/opt/chesstrainer` so it can write `priv/static/backups`.
@@ -562,9 +566,9 @@ receive `403 Access Denied`.
Do not let a deploy overwrite the shared Caddyfile.
See `docs/security.md` for the application throttle, real-IP setup and the
Cloudflare edge controls. Production currently has Bot Fight Mode enabled and
the free-plan login flood rule: 10 POSTs per 10 seconds per IP, blocked for 10
seconds.
Cloudflare edge controls. Production currently has Bot Fight Mode off (see
#153) and the free-plan login flood rule: 10 POSTs per 10 seconds per IP,
blocked for 10 seconds.
## Building a release
@@ -752,7 +756,9 @@ curl -i http://127.0.0.1:4100/health
`/health` returns JSON with `status`, `db`, `tablebase`, and `process`.
It returns 200 for `ok`/`degraded` and 503 for `down`. A missing local tablebase
reports `degraded` but still 200 because Lichess fallback is available.
reports `degraded` but still 200 because Lichess fallback is available. See
§Monitoring and alerting for the public probe that watches it, and for what a
green check does and does not prove.
### Reading production logs
@@ -800,6 +806,221 @@ Set `Storage=persistent` and a `SystemMaxUse=` value in
rate-limits bursts; if a crash storm drops lines, raise `RateLimitBurst` or
`RateLimitIntervalSec` there.
## Monitoring and alerting
Three checks watch production at three different layers:
| Where | What | Notices | Alerts |
|---|---|---|---|
| VPS | `chesstrainer-probe.timer` → `chesstrainer-probe.service` | the user-facing HTTP path: DNS, Cloudflare, Caddy, Phoenix, Postgres | healthchecks.io |
| VPS | Beszel hub + agent | host liveness, CPU, memory, disk, container restarts and OOM kills | Beszel notifications |
| VPS | `chesstrainer-backup.timer` heartbeat | whether the nightly dump finished | healthchecks.io (its own check) |
The backup heartbeat is documented in §Backups. The probe and the Beszel gap
are below.
### On-box prober, off-box alerting
The probe runs on the VPS and curls the **public** hostname, so it crosses the
same path a visitor does: Cloudflare's DNS and edge, the proxy back to Caddy,
Caddy's Cloudflare allowlist, the Phoenix router, and one database query.
That is deliberately not `127.0.0.1:4100`. A loopback probe stays green through
every failure that makes the site unusable: a bad `cloudflare-ranges.caddy`
reload, a stopped Caddy (`521`), an expired origin certificate (`526`), a
deleted proxied DNS record, a WAF rule blocking `/health`, or a Cloudflare
incident. Beszel is green through all of those too, because the host and the
container are fine.
The trade-off is that the prober shares a host with the app. It cannot report
that its own host is down, and it cannot prove the view from another network.
Host death is caught by **silence**: the timer stops, no ping arrives, and
healthchecks.io — which is off-box — alerts after the grace period. That is the
whole reason the check-in URL points at a SaaS rather than at another box here.
Do not describe this as external uptime monitoring.
### The healthchecks.io check
Create the check at healthchecks.io:
- Name `innersquare.app /health`, period **2 minutes**, grace **2 minutes**
- Integrations: email and Discord (webhook). Use each integration's test
notification once, and keep recovery notifications enabled so a resolved
incident is visible.
- Copy the ping URL. It is a secret: anyone who has it can mark the check
green. It belongs only in the root-owned env file.
Every check-in carries evidence:
- A healthy run posts the raw `/health` JSON.
- A tablebase mismatch still posts a **success**, because a Lichess fallback is
not an outage. The body carries the expected and actual values, so the
mismatch is visible in the check history without alerting anyone.
- A non-200, a malformed body, a `db` that is not `ok`, or a network/TLS
failure posts to `<ping-url>/fail` with a JSON body containing the reason,
the HTTP status, the curl exit code, the response body, and a loopback
`origin_status`/`origin_body` for comparison. The origin fields are evidence
only; the verdict comes from the public request.
A ping that cannot be delivered is a journal warning, not a second verdict:
the next timer run reports the state again.
### Install the probe
Write the env file, root-owned and `0600`:
```sh
sudo install -m 600 /dev/null /etc/chesstrainer/probe.env
sudoedit /etc/chesstrainer/probe.env
```
Start from `deploy/probe.env.example`. `PROBE_URL` and `HEALTHCHECK_URL` are the
only required values. Then install the script, the units, and the timer:
```sh
sudo install -m 0755 /opt/chesstrainer/src/deploy/probe \
/usr/local/sbin/chesstrainer-probe
sudo install -m 0644 \
/opt/chesstrainer/src/deploy/chesstrainer-probe.service \
/opt/chesstrainer/src/deploy/chesstrainer-probe.timer \
/etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now chesstrainer-probe.timer
```
The timer runs the installed `/usr/local/sbin/chesstrainer-probe`, not the copy
under `/opt/chesstrainer/src`, because that tree belongs to the application
user. When `deploy/probe` changes, install it to both places so the timer and
the repo agree.
Verify:
```sh
systemctl list-timers chesstrainer-probe.timer
sudo journalctl -u chesstrainer-probe -n 5 -o cat
```
Expect a `probe.ok` line every two minutes and a green check within one period.
Each run prints exactly one JSON line (`probe.ok`, `probe.degraded` or
`probe.failed`), like the backup script, so #140's log shipping can pick it up.
### What `/health` does and does not mean
`/health` returns `status`, `db`, `tablebase` and `process`. It returns 200 for
`ok` and `degraded`, and 503 for `down`.
- `db` is one `SELECT 1` through the connection pool. It proves the pool can
reach Postgres. It does not prove migrations are current or that writes work.
- `tablebase` reflects the local Syzygy directory. `fallback` means lookups go
to Lichess. `degraded` is 200 because the fallback is usable.
- `process` is always `"ok"`. It is not independent evidence of liveness.
A green probe therefore means: DNS resolved, Cloudflare served the request,
Caddy routed it under the Cloudflare allowlist, Phoenix answered, and Postgres
answered one query. It does not mean background jobs are running, SES accepts
mail, writes succeed, tablebase lookups are fast, or the site is fast under
load. Beszel covers resource exhaustion and container restarts; the release
health check and the logs cover deploy mistakes.
### Beszel's blind spot
Beszel watches the host: agent connection, CPU, memory, disk, container
restarts, OOM kills. Its hub runs on the same VPS as the agent, so a VPS
outage or network loss silences it as well — that case is covered by the probe
check going quiet. More importantly, Beszel never calls `/health`. A Phoenix
release returning 500s on a healthy host, or Postgres refusing connections
inside a running container, reads green in Beszel and red in the probe. The two
are complementary, not redundant.
### Drills
Nothing below touches production data, and the app keeps serving throughout.
`--dry-run` needs no network and no env file. It evaluates the success,
degraded, fail, non-JSON and unreachable fixtures and sends no check-ins:
```sh
sudo /usr/local/sbin/chesstrainer-probe --dry-run
```
A degraded check-in, recorded but never alerting. A value passed on the command
line wins over the env file:
```sh
sudo EXPECT_TABLEBASE=not_configured /usr/local/sbin/chesstrainer-probe
```
Expect exit 0, a green check, and a body showing `tablebase: local` against
`expected_tablebase: not_configured`. No email and no Discord message.
The one fail ping, and the full alert path. Stop the timer first so the next
scheduled run cannot mask the result:
```sh
sudo systemctl stop chesstrainer-probe.timer
sudo PROBE_URL=https://innersquare.app/health-does-not-exist \
/usr/local/sbin/chesstrainer-probe
```
Expect exit 1, one `probe.failed` line with `http_status: 404`, one fail ping
whose body shows `origin_status: 200`, one alert in Discord/email, and no
second fail ping. Then send a real check-in and re-arm:
```sh
sudo /usr/local/sbin/chesstrainer-probe
sudo systemctl start chesstrainer-probe.timer
```
The real run posts a success, and healthchecks.io notifies that the check is
back up. For the unreachable branch, point the probe at a closed port instead;
the origin evidence should still show `200`:
```sh
sudo PROBE_URL=https://127.0.0.1:9/health /usr/local/sbin/chesstrainer-probe
```
The outage drill: stop Phoenix, prove the alert, bring it back. Forcing each
probe run instead of waiting for the timer keeps the outage under a minute.
Start the probe **once** per step: every run sends its own check-in, so a
second start during the outage is a second alert.
```sh
sudo systemctl start chesstrainer-probe.service # baseline: probe.ok
sudo systemctl stop chesstrainer
sudo systemctl start chesstrainer-probe.service || true # probe.failed, http 502
# confirm one Discord message and one email, then:
sudo systemctl start chesstrainer
curl -sS -o /dev/null -w '%{http_code}\n' https://innersquare.app/health # 200
sudo systemctl start chesstrainer-probe.service # probe.ok, recovery
```
Expect `http_status: 502` from Caddy and `origin_status: 000` with
`origin_curl_exit: 7` in the fail body: Phoenix is down, while the host and the
edge are fine.
Planned maintenance: stopping the timer is reported as a down check after
period plus grace, so about four minutes. Pause the check in the healthchecks.io
UI for the duration, or accept the alert.
The probe reaches the edge as a plain `curl`. If a bot policy or WAF rule ever
starts rejecting it, the fail body's `origin_status` shows the app itself is
healthy; that is an edge-policy change, not an application outage. Re-enabling
Bot Fight Mode is tracked in #153.
### Drill log
- **2026-11-13 — install and first drills.** Script and units installed 12:34
UTC, timer enabled, first scheduled `probe.ok` at 12:35. Forced-failure drill
(`PROBE_URL` at a missing path): one fail ping with `http_status: 404` and
`origin_status: 200`, one Discord message and one email, then one recovery
notification. Degraded drill (`EXPECT_TABLEBASE=not_configured`): green
check-in with the mismatch in the body, no notification. Outage drill: the
app was stopped 13:32:55 and started 13:33:42 UTC; the manual probe was
started twice while it was down, so `probe.failed` fired at 13:33:06 and
13:33:14 (`http 502`) and two notifications arrived for one down → up
transition. `probe.ok` at 13:34:03 and one recovery notification. No
production data was touched. Start the probe once per drill step.
## Interactive shell and user management
Attach an IEx shell to the **running** release. This does not restart the
@@ -1223,5 +1444,7 @@ restore over `chesstrainer_prod` while the application is running.
globals file.
12. Workstation age key and pull configuration installed, user timers and linger
enabled, first pull verified, first drill passes.
13. Remote shell attaches and exits cleanly:
13. `/etc/chesstrainer/probe.env` written, probe script and units installed,
timer enabled, and the healthchecks.io check green within one period.
14. Remote shell attaches and exits cleanly:
`sudo /opt/chesstrainer/current/bin/chesstrainer remote` (Ctrl-C twice).
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=Probe the public Inner Square Chess app and report to healthchecks.io
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=root
Group=root
ExecStart=/usr/local/sbin/chesstrainer-probe
TimeoutStartSec=90s
SyslogIdentifier=chesstrainer-probe
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=Probe the public Inner Square Chess app every two minutes
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
[Timer]
OnBootSec=30s
OnUnitActiveSec=2min
AccuracySec=5s
Unit=chesstrainer-probe.service
[Install]
WantedBy=timers.target
Executable
+359
View File
@@ -0,0 +1,359 @@
#!/usr/bin/env bash
#
# Probe the public Inner Square Chess app and report the verdict to
# healthchecks.io.
#
# Installed as /usr/local/sbin/chesstrainer-probe (root-owned 0755) and run by
# chesstrainer-probe.timer every two minutes. The probe deliberately goes
# through the public hostname, not loopback: DNS, Cloudflare, Caddy and the
# origin allowlist are part of what a visitor depends on. A loopback health
# URL is still consulted on failure, as evidence only.
#
# sudo /usr/local/sbin/chesstrainer-probe
# sudo /usr/local/sbin/chesstrainer-probe --dry-run # no network, no config
#
# Configuration lives in /etc/chesstrainer/probe.env (root:root 0600). See
# deploy/README.md §Monitoring and alerting. Individual settings can be passed
# as environment variables to a manual run, which is how the drills vary the
# URL and the expected tablebase.
#
# Each run prints exactly one JSON line (probe.ok, probe.degraded or
# probe.failed) so journald, and #140's log shipping, can pick it up.
set -euo pipefail
umask 077
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/probe.env}"
START_SECONDS=$SECONDS
DRY_RUN=0
TMPDIR_PROBE=""
HTTP_BODY_FILE=""
HTTP_HEADER_FILE=""
HTTP_ERROR_FILE=""
usage() {
cat <<'EOF'
Usage: chesstrainer-probe [--dry-run]
--dry-run print the verdict for the success, degraded, fail, non-JSON and
unreachable fixtures without reading the env file or making a
network request
EOF
}
while (($# > 0)); do
case "$1" in
--dry-run) DRY_RUN=1 ;;
-h | --help)
usage
exit 0
;;
*)
usage >&2
echo "probe: unknown argument: $1" >&2
exit 2
;;
esac
shift
done
log_event() {
local event="$1"
local extra="${2:-}"
printf '{"timestamp":"%s","event":"%s"%s}\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
}
fail() {
echo "probe: $*" >&2
exit 1
}
json_escape() {
local text="$1"
text="${text//\\/\\\\}"
text="${text//\"/\\\"}"
text="${text//$'\n'/\\n}"
text="${text//$'\r'/\\r}"
text="${text//$'\t'/\\t}"
text="$(printf '%s' "$text" | LC_ALL=C tr -d '[:cntrl:]')"
printf '%s' "$text"
}
body_snippet() {
local file="$1"
if [[ -s "$file" ]]; then
head -c "$MAX_BODY_BYTES" "$file"
fi
}
json_field() {
local key="$1"
local json="$2"
if [[ "$json" =~ \"$key\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
printf '%s' "${BASH_REMATCH[1]}"
fi
}
http_get() {
local url="$1"
local prefix="$2"
local proto="$3"
local status=""
local exit_code=0
HTTP_BODY_FILE="$prefix.body"
HTTP_HEADER_FILE="$prefix.headers"
HTTP_ERROR_FILE="$prefix.error"
: >"$HTTP_BODY_FILE"
: >"$HTTP_HEADER_FILE"
: >"$HTTP_ERROR_FILE"
if status="$(curl --silent --show-error --location \
--proto "$proto" \
--connect-timeout 5 \
--max-time "$PROBE_TIMEOUT_SECONDS" \
--output "$HTTP_BODY_FILE" \
--dump-header "$HTTP_HEADER_FILE" \
--write-out '%{http_code}' \
"$url")"; then
exit_code=0
else
exit_code=$?
fi
HTTP_STATUS="${status:-000}"
CURL_EXIT="$exit_code"
}
# Sets VERDICT (ok, degraded, failed), REASON, DB and TABLEBASE. The database is
# the only hard dependency; a missing local tablebase still serves users from
# Lichess, so it is reported as a green but degraded check-in.
evaluate() {
local status="$1"
local exit_code="$2"
local body="$3"
local trimmed=""
VERDICT="failed"
REASON=""
DB=""
TABLEBASE=""
if ((exit_code != 0)); then
REASON="unreachable: curl exit $exit_code"
return
fi
if [[ "$status" != "200" ]]; then
REASON="http $status"
return
fi
trimmed="${body#"${body%%[![:space:]]*}"}"
trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
if [[ "${trimmed:0:1}" != "{" || "${trimmed: -1}" != "}" ]]; then
REASON="non-JSON response"
return
fi
DB="$(json_field db "$body")"
TABLEBASE="$(json_field tablebase "$body")"
if [[ -z "$DB" ]]; then
REASON="response has no db field"
return
fi
if [[ "$DB" != "ok" ]]; then
REASON="db is $DB"
return
fi
if [[ "$EXPECT_TABLEBASE" != "any" && "$TABLEBASE" != "$EXPECT_TABLEBASE" ]]; then
VERDICT="degraded"
REASON="tablebase is ${TABLEBASE:-unknown}, expected $EXPECT_TABLEBASE"
return
fi
VERDICT="ok"
}
# Exactly one call site per run, and one call site per outcome, so a forced
# failure can only ever produce one fail ping.
ping_check() {
local outcome="$1"
local body="$2"
local url=""
local body_file=""
if [[ -z "$HEALTHCHECK_URL" ]]; then
echo "probe: HEALTHCHECK_URL is not set, not reporting" >&2
return 0
fi
url="${HEALTHCHECK_URL%/}"
if [[ "$outcome" == "fail" ]]; then
url="$url/fail"
fi
body_file="$(mktemp)"
printf '%s' "$body" >"$body_file"
if ! curl --silent --show-error --fail \
--max-time 10 --retry 2 --retry-delay 2 \
--header 'Content-Type: application/json' \
--data-binary "@$body_file" \
--output /dev/null "$url"; then
echo "probe: check-in ping failed (run result is unaffected)" >&2
fi
rm -f "$body_file"
}
origin_evidence() {
local prefix="$1"
http_get "$ORIGIN_URL" "$prefix" '=https,http'
ORIGIN_STATUS="$HTTP_STATUS"
ORIGIN_EXIT="$CURL_EXIT"
ORIGIN_BODY="$(body_snippet "$HTTP_BODY_FILE")"
ORIGIN_ERROR="$(body_snippet "$HTTP_ERROR_FILE")"
}
fail_evidence() {
local evidence=""
evidence="$(printf '{"probe":"failed","reason":"%s","url":"%s","http_status":"%s","curl_exit":%s' \
"$(json_escape "$REASON")" "$(json_escape "$PROBE_URL")" "$PUBLIC_STATUS" "$PUBLIC_EXIT")"
if [[ -n "$ERROR_TEXT" ]]; then
evidence+="$(printf ',"error":"%s"' "$(json_escape "$ERROR_TEXT")")"
fi
if [[ -n "$BODY" ]]; then
evidence+="$(printf ',"body":"%s"' "$(json_escape "$BODY")")"
fi
evidence+="$(printf ',"origin_url":"%s","origin_status":"%s","origin_curl_exit":%s' \
"$(json_escape "$ORIGIN_URL")" "$ORIGIN_STATUS" "$ORIGIN_EXIT")"
if [[ -n "$ORIGIN_BODY" ]]; then
evidence+="$(printf ',"origin_body":"%s"' "$(json_escape "$ORIGIN_BODY")")"
fi
if [[ -n "$ORIGIN_ERROR" ]]; then
evidence+="$(printf ',"origin_error":"%s"' "$(json_escape "$ORIGIN_ERROR")")"
fi
printf '%s}' "$evidence"
}
dry_run() {
local -a scenarios=(
'HTTP 200, healthy|200|0|{"process":"ok","status":"ok","db":"ok","tablebase":"local"}'
'HTTP 200, tablebase fallback|200|0|{"process":"ok","status":"degraded","db":"ok","tablebase":"fallback"}'
'HTTP 503, db down|503|0|{"process":"ok","status":"down","db":"down","tablebase":"local"}'
'HTTP 200, non-JSON|200|0|<html><body>502 Bad Gateway</body></html>'
'timeout, no response|000|28|'
)
local row name status exit_code body action
printf 'probe: dry run, no network calls and no configuration read\n'
printf 'probe: every fixture is evaluated with EXPECT_TABLEBASE=local\n\n'
printf '%-28s %-9s %-46s %s\n' "scenario" "verdict" "reason" "would ping"
for row in "${scenarios[@]}"; do
IFS='|' read -r name status exit_code body <<<"$row"
EXPECT_TABLEBASE="local"
evaluate "$status" "$exit_code" "$body"
case "$VERDICT" in
ok) action="success, raw /health JSON" ;;
degraded) action="success, mismatch evidence" ;;
*) action="fail, evidence JSON" ;;
esac
printf '%-28s %-9s %-46s %s\n' "$name" "$VERDICT" "${REASON:--}" "$action"
done
printf '\nprobe: dry run complete, no check-ins sent\n'
}
if ((DRY_RUN)); then
dry_run
exit 0
fi
# Overrides passed on the command line survive the env file, so the drills can
# vary the URL or the expected tablebase without editing a root-only file.
_OVERRIDE_PROBE_URL="${PROBE_URL:-}"
_OVERRIDE_EXPECT_TABLEBASE="${EXPECT_TABLEBASE:-}"
_OVERRIDE_PROBE_TIMEOUT_SECONDS="${PROBE_TIMEOUT_SECONDS:-}"
if [[ -r "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
else
fail "cannot read $ENV_FILE (set ENV_FILE to override)"
fi
PROBE_URL="${_OVERRIDE_PROBE_URL:-${PROBE_URL:-}}"
EXPECT_TABLEBASE="${_OVERRIDE_EXPECT_TABLEBASE:-${EXPECT_TABLEBASE:-local}}"
PROBE_TIMEOUT_SECONDS="${_OVERRIDE_PROBE_TIMEOUT_SECONDS:-${PROBE_TIMEOUT_SECONDS:-10}}"
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
ORIGIN_URL="${ORIGIN_URL:-http://127.0.0.1:4100/health}"
MAX_BODY_BYTES="${MAX_BODY_BYTES:-2000}"
[[ "$PROBE_URL" == https://* ]] || fail "PROBE_URL must be an https URL"
[[ -n "$HEALTHCHECK_URL" ]] || fail "HEALTHCHECK_URL is not set"
[[ "$EXPECT_TABLEBASE" =~ ^(local|fallback|not_configured|any)$ ]] ||
fail "EXPECT_TABLEBASE must be local, fallback, not_configured or any"
[[ "$PROBE_TIMEOUT_SECONDS" =~ ^[0-9]+$ ]] || fail "PROBE_TIMEOUT_SECONDS must be an integer"
command -v curl >/dev/null 2>&1 || fail "missing command: curl"
TMPDIR_PROBE="$(mktemp -d)"
cleanup() {
if [[ -n "$TMPDIR_PROBE" && -d "$TMPDIR_PROBE" ]]; then
rm -rf "$TMPDIR_PROBE"
fi
}
trap cleanup EXIT
trap 'exit 143' TERM INT
http_get "$PROBE_URL" "$TMPDIR_PROBE/public" '=https'
PUBLIC_STATUS="$HTTP_STATUS"
PUBLIC_EXIT="$CURL_EXIT"
BODY="$(body_snippet "$HTTP_BODY_FILE")"
ERROR_TEXT="$(body_snippet "$HTTP_ERROR_FILE")"
evaluate "$PUBLIC_STATUS" "$PUBLIC_EXIT" "$BODY"
case "$VERDICT" in
ok)
log_event probe.ok ",\"status\":\"$PUBLIC_STATUS\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
ping_check ok "$BODY"
;;
degraded)
evidence="$(printf '{"expected_tablebase":"%s","health":%s}' \
"$(json_escape "$EXPECT_TABLEBASE")" "$BODY")"
log_event probe.degraded ",\"reason\":\"$(json_escape "$REASON")\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
ping_check ok "$evidence"
;;
*)
origin_evidence "$TMPDIR_PROBE/origin"
evidence="$(fail_evidence)"
log_event probe.failed ",\"reason\":\"$(json_escape "$REASON")\",\"http_status\":\"$PUBLIC_STATUS\",\"curl_exit\":$PUBLIC_EXIT,\"duration_s\":$((SECONDS - START_SECONDS))"
ping_check fail "$evidence"
exit 1
;;
esac
+28
View File
@@ -0,0 +1,28 @@
# /etc/chesstrainer/probe.env -- root:root, mode 0600.
#
# Sourced by /usr/local/sbin/chesstrainer-probe. The check-in URL is a secret:
# anyone who has it can mark the check green, so keep it out of the repo and
# out of world-readable files.
# The public URL a visitor actually requests. Probing the edge rather than
# loopback is deliberate: DNS, TLS, Cloudflare, Caddy and the origin allowlist
# are part of the contract. Must be https.
PROBE_URL=https://innersquare.app/health
# healthchecks.io ping URL for the two-minute probe check. A healthy run posts
# to it; a failed run posts to <url>/fail.
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
# The tablebase value /health should report. "local" means Syzygy files are
# loaded, "fallback" means Lichess is used, "not_configured" means
# TABLEBASE_PATH is unset. A mismatch is reported as degraded, never as down.
# Set to "any" to accept whatever the app reports.
EXPECT_TABLEBASE=local
# Whole-request timeout. The timer runs every two minutes, so keep this well
# under that.
PROBE_TIMEOUT_SECONDS=10
# Loopback health URL. It is consulted only when the public probe fails, and
# only as evidence: it does not change the verdict. Defaults to the value shown.
# ORIGIN_URL=http://127.0.0.1:4100/health
Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 B

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,65 @@
# Launch observability is the probe, honest error states, and the runbook
_Status: accepted._
At launch, observability means three things and no more: an external check that
the public app answers, error states that are honest and recoverable, and a
written runbook for when either fails. Everything else is deferred with a named
trigger, so the gaps are explicit rather than ambient.
## The launch bar
- **Probe.** A healthchecks.io check with a two-minute period and grace, fed by
an on-box prober with off-box alerting (#160, #161). It curls the public
`/health` through Cloudflare, so DNS, TLS, Caddy, the origin allowlist,
Phoenix and one Postgres query are covered. The loopback cross-check in a
failure body is evidence only. The prober shares a host with the app, so host
death is caught by silence, not by a ping.
- **Error states.** The audit (#162) and its fixes (#163), verified by #164.
Every failure mode has copy and a retry or a way home; exception details and
raw error terms do not reach the page.
- **Runbook.** `deploy/README.md` §Monitoring and alerting: the check, install,
what `/health` proves and does not, Beszel's blind spot, the drills, and the
dated drill log.
## Deferred, with triggers
- **Error tracking (#109, GlitchTip/Sentry).** Deferred because JSON logs
already carry the crash reason and stacktrace per request, and there is no
traffic to aggregate over. Revisit when the first production 500 cannot be
diagnosed from its journal line (missing or truncated stacktrace), or a user
reports an error without a request id, or unexplained errors exceed roughly
50 a day and per-line grep stops being practical.
- **Metrics and LiveDashboard (#111).** Deferred because Beszel covers host
resources and the probe covers the HTTP contract. Revisit when a capacity
question needs a number neither can answer (database pool saturation, p95
latency, queue depth), or daily active users pass 100, or a performance
incident takes more than an hour to localise.
- **Off-box log shipping and error-rate alerts (#140).** Deferred because
journald is persistent on the host and the probe alerts on downness. Revisit
when an alert must fire on a log pattern (error rate, authentication
failures), or the journal retention budget cannot cover a 30-day
investigation, or the host is rebuilt and local logs would be lost in the same
incident.
## Why journald and backups are enough at launch
Persistent journald (`Storage=persistent`, `SystemMaxUse`) holds one JSON object
per line: crashes carry a reason and stacktrace, access lines carry status and
duration, and token-shaped paths, emails and credentials are redacted. Off-box
encrypted backups cover the data.
The accepted risk: losing the host loses the logs with it, and there is no
aggregate error rate. At launch that is acceptable — one host, one operator,
low traffic, and an incident is diagnosed from the journal on the box or from
the probe's alert body. The triggers above are the point at which that risk
stops being acceptable.
## Consequences
- Investigation starts with `journalctl -u chesstrainer -o cat | jq`, not a
dashboard.
- Error tracking, metrics and log shipping stay explicit backlog items with
triggers rather than ambient gaps.
- The probe is an on-box prober with off-box alerting; it is not external
uptime monitoring and the runbook says so.
+61
View File
@@ -0,0 +1,61 @@
# Error-state verification
The #162 checklist, walked on 2026-11-13 against a local production-like build.
Failures were filed as #171 and fixed in the follow-up for that issue; this page
records the verification run, not the current state. It is linked from the
audit.
## Method
- **Build:** `MIX_ENV=prod` `mix phx.server` on `127.0.0.1:4010`, commit
`021e412` plus this branch's documentation.
- **Database:** a scratch `postgres:18.6` on port 55432. Empty at first, then
one confirmed user and one 8+ piece endgame (inserted directly, because the
admin changeset rejects positions beyond seven pieces).
- **Configuration:** `PRELAUNCH=false`, `MAILING_LIST_ENABLED=true`,
`TABLEBASE_PATH` pointing at a missing directory, dummy SES credentials.
- **Forced failures:** Postgres stopped, missing tablebase directory, empty
puzzle pool, expired reset and confirmation tokens (backdated
`users_tokens.inserted_at`), stale and invalid mailing-list forms, guest
budget exhausted, unknown public play code.
- **Observation:** `curl` for controller-rendered pages, headless Chrome over
the DevTools Protocol for LiveView-connected pages, and `mix test` for the
interactive states that need a click. Each row names its evidence.
- **Not forced:** a real Lichess 429 (the cooldown and classifier paths were
exercised by the tests), a crash after connect, and the two admin-only import
leaks (code inspection and tests). The first run rejected the socket origin
because `PHX_HOST` defaulted to `example.com`; setting `PHX_HOST=127.0.0.1`
fixed it. That was local configuration, not a product finding.
## Results
| Checklist row | Result | Evidence |
|---|---|---|
| T1 cooldown | **pass** | LiveView test: mount with a cooldown shows "Tablebase cooling down"; Retry re-fetches and returns to play. |
| T2 429 | **pass** | LiveView test: classifier maps 429 to "Tablebase rate-limited"; HTML carries no `429`, `too_many_requests` or upstream body. |
| T3 not covered | **pass** | Prod run: guest page with a 12-piece endgame shows "Position not covered… can't be graded", no `not_covered` in the DOM, Next puzzle or back available. |
| T4 generic | **pass** | LiveView test: classifier returns "Tablebase unavailable"; the reason is logged and never rendered. |
| T5/T6 load and reply failure | **pass** | T5 covered by the cooldown-at-mount test and Retry. T6 shares the blocked panel and `reset/1` path; not separately forced. |
| T8 invalid FEN | **fail** | Existing test: the flash still contains the client message and the raw FEN. #171. |
| S1/S2/S3/S5 empty pools | **pass** | S1 prod: Medium picker shows the in-page empty state and Retry. S5 prod: guest shows "No endgames are available yet" and Retry. S2/S3 tests: exhausted state, Retry and Change difficulty. |
| S4 guest limit | **pass** | Prod run: five visits exhaust the budget; the wall shows the reset time, Sign up free and Log in. |
| A1 reset token | **pass** | Prod run: an expired token flashes "Reset password link is invalid or it has expired." on the log-in page, with Forgot your password available. |
| A2 confirmation token | **fail** | Prod run: an expired token flashes "User not found or token is invalid." and lands on registration, not log in. #171. |
| A3/A4 login | **pass** | Tests: invalid credentials use one message; the throttle reports the remaining minutes. |
| M1–M5 mailing list | **pass** | Prod run: invalid confirmation link, removed address, stale form, invalid email and an SES send failure each show their specific copy with the form reachable. |
| W1/W2 404 and 500 | **pass** | Prod run: styled 404 for an unknown path; with Postgres stopped, `/` returns the styled 500 with no exception or stacktrace. |
| W3 crash | **fail** | The server-error banner has no reload action; a repeating crash has no manual escape. Not separately forced; same banner as W4. #171. |
| W4 disconnect | **pass** | Observed "Something went wrong! Attempting to reconnect" while the socket was rejected, with automatic retries; the banner hides on reconnect. |
| W5 database down | **pass** | Prod run: `/health` returns 503 `db:down`; `/` returns the 500 page. Note the loop: the home link also needs the database, so it 500s too. |
| D1/D2 export | **fail** | Prod run: an export with the database stopped returns the 500 page (no export-specific copy); `/users/profile/export/xml` returns plain text "Unknown export format". #171. |
| H1 empty-database home | **fail** | Prod run: the fallback board renders, but "Try today's puzzle" points at the auth-gated `/endgames`. #171. |
| X1 unknown play code | **pass** | Prod run: `/endgames/nope/play` returns the styled 404 page. This corrects the audit's earlier claim that it 500ed. |
| X2/X3 admin leaks | **fail** | Code inspection and tests: both importer messages still interpolate `inspect(reason)`. Not forced. #171. |
## Tally
- 14 checklist rows pass, 6 fail (8 individual regressions, because D1/D2 and
X2/X3 share a row).
- Every failure row is a state that was already listed as "improve" in the
audit and was outside #163; no new regression came from the #163 changes.
- The regressions are filed together in #171 rather than fixed silently.
+152
View File
@@ -0,0 +1,152 @@
# User-facing error states
What a player sees when something fails, with a verdict for every state and the
concrete change each one needs. This is the audit required by #162; #163
implements the tablebase and empty-pool items, and #164 walks the sign-off
checklist on a production-like build.
Verdicts:
- **keep** — the state is honest, recoverable and leak-free as it stands
- **improve** — a state exists but needs different copy, a recovery action, or
both
- **add** — there is no user-facing state today
"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 walked this checklist on a local prod build:
see [error-states-verification.md](error-states-verification.md).
## Play and tablebase
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| T1 | Cooldown | A previous 429 put Lichess in cooldown; `Tablebase.new/1` returns `{:cooldown, ms}` (`play_core.ex:386`) | Panel headed **Tablebase unavailable**, body "The tablebase is rate-limited. Try again in about Ns."; move hint "The tablebase is unavailable, so moves cannot be entered."; **Reset** | improve | Heading per failure class ("Tablebase cooling down"), keep the countdown, and relabel Reset to **Retry** while blocked. Fold into #163. |
| T2 | Lichess 429 | Lichess returns 429; the parser records a cooldown (`tablebase/parser.ex:69`) | Same panel; "The tablebase is rate-limited. Try again in a minute." | improve | Same class as T1, with the real countdown once known. Never show `429` or the response body. Fold into #163. |
| T3 | Position not covered | More than seven pieces, Lichess 404, or `:not_covered` (`play_core.ex:394-401`) | Panel headed **Tablebase unavailable**, body "This position is not covered by the tablebase."; **Reset** | improve | Say the puzzle cannot be graded, and offer **Try another puzzle** (session) or **Browse endgames** (single). Retry is futile here, so do not present it as the primary action. Fold into #163. |
| T4 | Generic tablebase failure | 5xx, transport error, malformed response (`play_core.ex:403`) | **"The tablebase is unavailable (#{inspect(reason)})."** | improve | Replace with "The tablebase is unavailable right now. Try again in a moment." and log the reason. This is the leak #163 calls out. Also applies to the review panel's `review_blocked` copy. |
| T5 | Load failure at session start | `Tablebase.new/1` fails in `PlayCore.init/2` → `load_attempt/1` | Board non-interactive; blocked panel and reason; **Reset** | improve | Class-correct copy plus **Retry**; `reset/1` already re-fetches, so this is a label and copy change. Fold into #163. |
| T6 | Fetch failure for the opponent's reply | `start_opponent_reply/2` cannot fetch the new position (`play_core.ex:457`) | Play stops; blocked panel; the move already played is still on the board; **Reset** | improve | Explain that the puzzle is paused and **Retry** resumes from the current position. Fold into #163. |
| T7 | Move while blocked | A move event arrives while `status == :blocked` (`play_core.ex:76`) | Flash "The tablebase is unavailable, so this move cannot be graded." | keep | Defensive guard; the board should already be non-interactive. #164 asserts that. |
| T8 | Invalid FEN from the board hook | `chess_fen_invalid` (`play_core.ex:184`) | Flash **"Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})"** | improve | Generic copy ("The board couldn't load this position. Reset to try again."), log the details, and keep **Reset** visible. Leak: client message and raw FEN. |
## Sessions and puzzle pools
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| S1 | No puzzles available | `Puzzles.next_endgame/3` returns `nil` on start (`train.ex:201`) | Flash error "No puzzles are available right now."; the difficulty picker stays behind it | improve | Replace the flash with an in-page state inside the picker: what happened, **Retry**, and a way to pick another difficulty. Fold into #163. |
| S2 | No more puzzles at this difficulty | `next_endgame` returns `nil` with `exclude_ids` (`train.ex:232`) | Flash info "No more puzzles at this difficulty."; the finished puzzle and **Next puzzle** remain | improve | In-page end-of-run panel: "You've finished every puzzle at this difficulty" with **Retry**, **Change difficulty** (stop session) and the existing Stop session. Hide or disable Next. Fold into #163. |
| S3 | Guest: no more puzzles | Guest `next_puzzle` finds nothing (`guest_train.ex:137`) | Flash info "No more puzzles are available right now." | improve | In-page state with **Retry** and the sign-up/log-in actions, matching the guest-limit panel's tone. Fold into #163. |
| S4 | Guest limit reached | `GuestLimits.take/1` returns `{:limit_reached, ms}` (`guest_train.ex:45-70`) | In-page panel: used N free puzzles, reset time, **Sign up free**, **Log in** | keep | This is the reference state for tone and recovery. |
| S5 | Guest pool empty on load | Random endgame is `nil` (`guest_train.ex:98`) | In-page "No endgames are available yet. Please check back soon." | improve | Add a **Retry** action so the state is not a dead end. Fold into #163. |
## Accounts and email
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| A1 | Reset token invalid or expired | `get_user_by_reset_password_token/1` returns `nil` (`reset_password.ex:66`) | Flash "Reset password link is invalid or it has expired." then the log-in page, where **Forgot your password?** is available | keep | Honest and recoverable in two clicks. |
| A2 | Confirmation token invalid or expired | `Accounts.confirm_user/1` returns `:error` (`user_confirmation_controller.ex:17`) | Flash **"User not found or token is invalid."** then the registration page | improve | Say "That confirmation link is invalid or has expired." and send the user to log in, where an unconfirmed account triggers a fresh confirmation email. No "user not found" phrasing. |
| A3 | Invalid credentials | `get_user_by_login_and_password/2` returns `nil` | Flash "Invalid email, username or password"; email is prefilled | keep | Deliberately identical for unknown and wrong-password logins, so it does not enumerate accounts. |
| A4 | Login throttle | 5 failures per login or 10 per address in 15 minutes (`LoginThrottle`) | Flash "Too many attempts. Try again in N minutes." | keep | Accurate countdown, no account information. |
## Mailing list
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| M1 | Confirmation link invalid or expired | Token fails verification (`mailing_list_controller.ex:36`) | Flash "That confirmation link is invalid or has expired." → `/#mailing-list` | keep | The signup form is on the destination page. |
| M2 | Confirmed address no longer subscribed | `MailingList.confirm/1` returns `:not_found` (`:52`) | Flash "That address is no longer on the mailing list. Please sign up again." → `/#mailing-list` | keep | Actionable and specific. |
| M3 | Stale signup form | `MailingListFormToken.verify/1` fails (`:126`) | Flash "Please refresh the page and try again." → `/#mailing-list` | keep | The form is on the page; refresh is the fix. |
| M4 | Invalid email | Missing or invalid address (`:132`) | Flash "Enter a valid email address." | keep | Specific and actionable. |
| M5 | Confirmation email send failure | `Notifier.deliver_confirmation_instructions/2` returns an error (`:111`) | Flash "We couldn't send the confirmation email. Please try again." | improve | Keep the copy, add "If it keeps happening, email …" from `Branding.support_email/0`, and log the reason — the controller currently discards it. |
| M6 | List closed / honeypot / already subscribed | Feature flag, honeypot, or existing address | "The mailing list isn't open yet." / success copy / "You're already on the mailing list." | keep | Closed and honeypot are deliberate; the existing-address message is honest. |
## Site-level
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| W1 | 404 | Unknown route (`ErrorHTML`, catch-all route) | Styled page: "This page isn't on the board", **Back to home**, plus **Browse puzzles** for premium users | keep | Uses the shared `error_page/1`. |
| W2 | 500 | Controller or render crash | Styled page: "Something went wrong", **Back to home**, **Browse puzzles**, support email | keep | Honest, no exception detail. |
| W3 | LiveView crash | Raise in `mount` or `handle_event` | Mount crash → the 500 page. A crash after connect → the **"Something went wrong!"** banner, automatic reconnect, no manual action | improve | Add a **Reload** action (and keep home) to the server-error banner so a crash that repeats on reconnect has an escape. The banner lives in `layouts.ex:274`. |
| W4 | Disconnect | Socket or network loss | **"We can't find the internet"** banner with a spinner; hides on reconnect | keep | Automatic recovery, no action needed. |
| W5 | Database unavailable | Postgres stopped or pool exhausted | DB-backed pages and LiveView mounts raise → the 500 page; `/health` returns 503 | keep | The 500 page is the right state, but note the loop: the home page also needs the database, so "Back to home" fails too. The probe is the operational signal. No app change proposed here. |
## Data and landing
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| D1 | Export failure | `Attempts.list_attempts_for_user/1` raises in `UserDataController.export/2` | The 500 page, with no export-specific explanation | improve | Rescue, log, and redirect to `/users/profile/data` with "We couldn't build your export. Try again; if it keeps failing, email …". |
| D2 | Unknown export format | `/users/profile/export/<anything else>` | Plain text `404 "Unknown export format"` with no chrome, links, or home | improve | Return the styled 404 page instead. |
| D3 | Export of an empty account | No attempts | CSV with the header and an empty row; JSON with an empty list | keep | Deliberate and documented by the shape. |
| H1 | Home page with an empty database | No endgames (`PageController.home/2`) | Fallback KRK board, "Featured position", "0 players training", and a **Try today's puzzle** button pointing at `/endgames` | improve | When `active_endgame` is `nil`, do not send the visitor to an auth-gated page with no puzzles: point the call to action at `/guest-train` (which has its own empty state) or disable it with "New puzzles are coming". |
## Admin surfaces (extra)
| ID | State | Trigger | What the user sees today | Verdict | Action |
|---|---|---|---|---|---|
| X1 | Unknown public play code | `/endgames/:code/play` with a code that does not exist (`play.ex:79`) | The styled 404 page: `Ecto.NoResultsError` maps to 404 through `Plug.Exception` | keep | Verified by #164; no change. |
| X2 | Bulk import lookup crash | `handle_async` exits (`import.ex:271`) | Flash **"Could not look up the FENs: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
| X3 | Bulk import tablebase load failure | `Local.check/0` returns an unexpected error (`import.ex:287`) | **"Local tablebase failed to load: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
## Internal-detail leaks
These are the only places where an exception term, a raw HTTP status or a raw
FEN can reach rendered HTML. T4 is the one #162 calls out; the rest are smaller
but real.
| Where | Leak | Fix |
|---|---|---|
| `play_core.ex:404` | `inspect(reason)` in the blocked panel | T4 |
| `play_core.ex:189` | client message and raw FEN in a flash | T8 |
| `import.ex:271` | `inspect(reason)` in a flash | X2 |
| `import.ex:287` | `inspect(reason)` in the tablebase status | X3 |
| `user_data_controller.ex:21` | plain-text "Unknown export format" | D2 |
Server logs already carry the real reasons, so none of these fixes lose
diagnostic information.
## Sign-off checklist
For #164 to walk against a production-like build. Every row passes only if the
state offers **retry or a way home** and rendered HTML contains no exception,
stacktrace, raw error term, or raw FEN.
- [ ] **T1 cooldown** — force a cooldown: class-correct heading, countdown, Retry re-fetches.
- [ ] **T2 429** — make Lichess return 429: rate-limit copy, no `429` or response body.
- [ ] **T3 not covered** — play a position with more than seven pieces: explanation, another puzzle or home, no futile Retry.
- [ ] **T4 generic** — make Lichess fail (network off or 5xx): generic copy, Retry works when it recovers, no `inspect`.
- [ ] **T5/T6 load and reply failure** — start a puzzle and lose the tablebase mid-game: paused explanation, Retry resumes.
- [ ] **T8 invalid FEN** — force `chess_fen_invalid`: no client message or raw FEN, Reset visible.
- [ ] **S1/S2/S3/S5 empty pools** — empty the pool: in-page states on train and guest, Retry and change-difficulty reachable.
- [ ] **S4 guest limit** — exhaust the guest allowance: panel, reset time, sign-up and log-in reachable.
- [ ] **A1 reset token** — use an expired link: message, log-in page, forgot-password reachable.
- [ ] **A2 confirmation token** — use an expired link: message, log-in page, fresh confirmation email on next login.
- [ ] **A3/A4 login** — wrong password and throttled login: no account enumeration, countdown.
- [ ] **M1-M5 mailing list** — expired confirmation, stale form, invalid address, send failure: specific copy and the form reachable.
- [ ] **W1/W2 404 and 500** — unknown path and forced crash: styled page, home and browse reachable, no exception.
- [ ] **W3 crash** — raise in a `handle_event`: reload action reachable.
- [ ] **W4 disconnect** — drop the socket: reconnect banner and automatic recovery.
- [ ] **W5 database down** — stop Postgres: 500 pages, `/health` 503, no stacktrace; note that home is also down.
- [ ] **D1/D2 export** — force an export error and an unknown format: flash or 404 page, home reachable.
- [ ] **H1 empty database** — empty the pool: home renders, call to action is not an auth-gated dead end.
- [ ] **X1 unknown play code** — open a stale link: 404 page, not a 500.
- [ ] **X2/X3 admin leaks** — force an import crash and a tablebase error: no `inspect` output.
## Fix list
Fold into **#163** (tablebase and empty-pool recoverability): T1, T2, T3, T4,
T5, T6, S1, S2, S3, S5.
Separate changes, each independently testable:
- **T8** — generic invalid-FEN flash; log the details.
- **A2** — confirmation-token copy and destination.
- **M5** — support fallback on send failure; log the reason.
- **W3** — reload action in the server-error banner.
- **D1** — rescue export errors into a flash on the data tab.
- **D2** — styled 404 for unknown export formats.
- **H1** — empty-database call to action.
- **X2/X3** — generic admin import copy; log the details.
No code changes are part of this audit.
+9 -5
View File
@@ -11,7 +11,8 @@ addresses and would ban Cloudflare edge addresses on this deployment.
`CF-Connecting-IP` as `X-Forwarded-For`. The ranges are refreshed hourly by
`chesstrainer-cloudflare-ranges.timer`.
- `TRUST_FORWARDED_FOR=true`, so the app throttles by the real visitor address.
- Cloudflare Bot Fight Mode is enabled.
- Cloudflare Bot Fight Mode is off. The Caddy origin allowlist above stays in
force; re-enabling is tracked in #153.
- The free-plan login flood rule allows 10 login POSTs per 10 seconds per IP and
blocks for 10 seconds.
@@ -155,10 +156,13 @@ address after ten failures within fifteen minutes. A slow attacker staying under
10 requests per 10 seconds never gets to make useful guesses because of the app
throttle.
Bot Fight Mode is enabled as the plan-level bot control. If the plan later gains
longer rate-limit windows or managed WAF rules, raise the block duration and
consider a broader site-wide rule, such as 100 requests per 10 seconds per IP
with a managed challenge. Use Under Attack Mode during an active incident.
Bot Fight Mode is off. On the free plan it cannot be skipped for CI or for the
on-box health probe, so a datacenter `curl` gets a 403 while the site itself is
healthy; #153 covers the gate and probe changes needed before it goes back on.
If the plan later gains longer rate-limit windows or managed WAF rules, raise
the block duration and consider a broader site-wide rule, such as 100 requests
per 10 seconds per IP with a managed challenge. Use Under Attack Mode during an
active incident.
### Registration cannot be limited this way
+27
View File
@@ -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)
+5 -1
View File
@@ -17,7 +17,11 @@ defmodule ChesstrainerWeb do
those modules here.
"""
def static_paths, do: ~w(assets fonts images favicon.ico)
def static_paths do
~w(assets fonts images favicon.ico favicon.svg favicon-16x16.png favicon-32x32.png
apple-touch-icon.png android-chrome-192x192.png android-chrome-512x512.png
site.webmanifest)
end
@doc "Whether the app is gated behind the prelaunch page."
def prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
@@ -282,6 +282,17 @@ defmodule ChesstrainerWeb.Layouts do
{gettext("Attempting to reconnect")}
<.icon name="hero-arrow-path" class="ml-1 size-3 motion-safe:animate-spin" />
</.flash>
<div
id="connection-actions"
hidden
phx-disconnected={show("#connection-actions")}
phx-connected={hide("#connection-actions")}
class="pointer-events-auto flex items-center gap-3 rounded-lg border border-base-300 bg-base-100 px-4 py-2 text-sm shadow-lg"
>
<a href="" class="font-semibold text-primary-text hover:underline">Reload</a>
<.link href={~p"/"} class="text-muted hover:underline">Home</.link>
</div>
</div>
"""
end
@@ -41,6 +41,14 @@
name="twitter:description"
content={assigns[:meta_description]}
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="#17352d" />
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<link
rel="preload"
@@ -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>
<.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>
<.button
:if={@status == :blocked && @blocked && !@blocked.retry && @session}
id="next-after-blocked"
phx-click="next_puzzle"
variant="primary"
>
Next puzzle
</.button>
<.button :if={@status != :blocked} phx-click="reset" variant="primary">
<.icon name="hero-arrow-path" />
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
</.button>
@@ -194,7 +210,7 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %>
<% @review_blocked -> %>
<p class="text-muted">Best move unavailable here</p>
<p class="text-muted">{@review_blocked}</p>
<p class="text-muted">{@review_blocked.message}</p>
<% @review_tablebase -> %>
<p class="text-muted font-semibold mb-1">Best move:</p>
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
@@ -211,9 +227,9 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %>
<% @status == :loading -> %>
<p class="text-muted">Loading tablebase…</p>
<% @status == :blocked -> %>
<p class="font-semibold text-error-text">Tablebase unavailable</p>
<p class="text-error-text">{@blocked_reason}</p>
<% @status == :blocked && @blocked -> %>
<p class="font-semibold text-error-text">{@blocked.title}</p>
<p class="text-error-text">{@blocked.message}</p>
<% @status == :solved -> %>
<p class="font-semibold text-success-text">
{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)
@@ -3,8 +3,12 @@ defmodule ChesstrainerWeb.ThemePicker do
Search-and-select control shared by the endgame form and bulk importer.
The parent LiveView owns the assignments and handles the events:
`search_themes`, `add_theme`, `create_theme`, `create_theme_from_search` and
`remove_theme`.
`search_themes`, `add_theme`, `create_theme` and `remove_theme`.
The control renders no `<form>` of its own. It is embedded in the endgame
form, where a nested form would be dropped by the HTML parser and take its
bindings with it, and it is used standalone on the bulk importer. Binding
`phx-change` on the search input keeps both call sites working.
"""
use ChesstrainerWeb, :html
@@ -35,10 +39,11 @@ defmodule ChesstrainerWeb.ThemePicker do
</.badge>
</div>
<form id="theme-form" phx-change="search_themes" phx-submit="create_theme_from_search">
<div id="theme-picker">
<.input
name="theme_search"
value={@theme_query}
phx-change="search_themes"
phx-debounce="200"
autocomplete="off"
placeholder="Search or create a theme…"
@@ -67,7 +72,7 @@ defmodule ChesstrainerWeb.ThemePicker do
</button>
</li>
</ul>
</form>
</div>
</div>
"""
end
@@ -6,6 +6,14 @@
<meta name="robots" content="noindex" />
<title>{Branding.title("Page not found")}</title>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="#17352d" />
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<link
rel="preload"
@@ -6,6 +6,14 @@
<meta name="robots" content="noindex" />
<title>{Branding.title("Something went wrong")}</title>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32" />
<link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="#17352d" />
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
<link
rel="preload"
@@ -8,6 +8,6 @@ defmodule ChesstrainerWeb.PageHTML do
embed_templates "page_html/*"
defp play_path(nil), do: ~p"/endgames"
defp play_path(nil), do: ~p"/guest-train"
defp play_path(%{public_code: public_code}), do: ~p"/endgames/#{public_code}/play"
end
@@ -12,9 +12,15 @@
Train your intuition to find the winning moves under pressure. Puzzle sessions focused purely on technical execution.
</p>
<div class="hero-actions">
<.pill_button variant={:primary} navigate={play_path(@active_endgame)}>
Try today's puzzle <.icon_arrow />
</.pill_button>
<%= if @active_endgame do %>
<.pill_button variant={:primary} navigate={play_path(@active_endgame)}>
Try today's puzzle <.icon_arrow />
</.pill_button>
<% else %>
<.pill_button variant={:primary} navigate={play_path(nil)}>
Start training <.icon_arrow />
</.pill_button>
<% end %>
<div class="rating-note">
<span class="avatar-stack">
<i>♟</i>
@@ -15,8 +15,11 @@ defmodule ChesstrainerWeb.UserConfirmationController do
:error ->
conn
|> put_flash(:error, "User not found or token is invalid.")
|> redirect(to: ~p"/users/register")
|> put_flash(
:error,
"That confirmation link is invalid or has expired. Log in to request a new one."
)
|> redirect(to: ~p"/users/log-in")
end
end
end
@@ -1,7 +1,10 @@
defmodule ChesstrainerWeb.UserDataController do
use ChesstrainerWeb, :controller
require Logger
alias Chesstrainer.Attempts
alias Chesstrainer.Branding
@user_columns ~w(user_username user_email user_rating user_rating_deviation user_plan user_joined_at)
@attempt_columns ~w(played_at puzzle public_code color result outcome rated_at)
@@ -9,16 +12,41 @@ defmodule ChesstrainerWeb.UserDataController do
def export(conn, %{"format" => format}) when format in ["csv", "json"] do
user = conn.assigns.current_scope.user
attempts = Attempts.list_attempts_for_user(user.id)
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
conn
|> put_resp_content_type(content_type(format))
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|> send_resp(200, body(format, user, attempts))
try do
attempts = Attempts.list_attempts_for_user(user.id)
filename = "lucid-chess-data-#{Date.utc_today()}.#{format}"
conn
|> put_resp_content_type(content_type(format))
|> put_resp_header("content-disposition", ~s(attachment; filename="#{filename}"))
|> send_resp(200, body(format, user, attempts))
rescue
exception ->
export_failed(conn, Exception.message(exception))
catch
:exit, reason ->
export_failed(conn, inspect(reason))
end
end
def export(conn, _params), do: send_resp(conn, 404, "Unknown export format")
def export(conn, _params) do
conn
|> put_status(:not_found)
|> put_view(ChesstrainerWeb.ErrorHTML)
|> render("404.html")
end
defp export_failed(conn, reason) do
Logger.error("profile.export_failed", reason: reason)
conn
|> put_flash(
:error,
"We couldn't build your export. Try again; if it keeps failing, email #{Branding.support_email()}."
)
|> redirect(to: ~p"/users/profile/data")
end
defp body("csv", user, attempts), do: to_csv(user, attempts)
+7 -11
View File
@@ -21,13 +21,6 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
<:subtitle>Use this form to manage endgame records in your database.</:subtitle>
</.header>
<.theme_picker
selected_themes={@selected_themes}
theme_query={@theme_query}
theme_results={@theme_results}
can_create={@can_create}
/>
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
<div class="flex flex-col gap-6 sm:flex-row sm:items-start">
<div class="min-w-0 flex-1">
@@ -40,6 +33,13 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
label="Rating"
/>
<.theme_picker
selected_themes={@selected_themes}
theme_query={@theme_query}
theme_results={@theme_results}
can_create={@can_create}
/>
<.input field={@form[:message]} type="textarea" label="Message" />
<.input field={@form[:notes]} type="textarea" label="Notes" />
<.input
@@ -122,10 +122,6 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
{:noreply, create_theme(socket, name)}
end
def handle_event("create_theme_from_search", %{"theme_search" => name}, socket) do
{:noreply, create_theme(socket, name)}
end
def handle_event("remove_theme", %{"id" => id}, socket) do
selected = Enum.reject(socket.assigns.selected_themes, &(Integer.to_string(&1.id) == id))
{:noreply, assign(socket, :selected_themes, selected)}
@@ -70,12 +70,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
</section>
<PlayComponents.play_surface
:if={@endgame}
:if={@endgame && @empty != :exhausted}
session={is_nil(@limit_reached)}
endgame={@endgame}
fen={@fen}
status={@status}
blocked_reason={@blocked_reason}
blocked={@blocked}
best_move={@best_move}
plies={@plies}
line={@line}
@@ -94,12 +94,41 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
<p
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
class="text-base-content/70"
<section
:if={@empty == :exhausted}
id="guest-pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
No endgames are available yet. Please check back soon.
</p>
<h2 class="text-lg font-semibold">No more puzzles are available right now</h2>
<p class="mt-1 text-sm text-muted">
Try again in a moment, or create a free account to train at your level.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
<section
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
id="guest-pool-empty"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">No endgames are available yet</h2>
<p class="mt-1 text-sm text-muted">
Please check back soon, or create a free account to be ready when they land.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
</Layouts.app>
"""
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
@@ -8,6 +8,8 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
use ChesstrainerWeb, :live_view
require Logger
alias Chesstrainer.Endgames.BulkImport
alias Chesstrainer.Endgames.Tablebase.Local
@@ -194,10 +196,6 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
{:noreply, create_theme(socket, name)}
end
def handle_event("create_theme_from_search", %{"theme_search" => name}, socket) do
{:noreply, create_theme(socket, name)}
end
def handle_event("remove_theme", %{"id" => id}, socket) do
selected = Enum.reject(socket.assigns.selected_themes, &(Integer.to_string(&1.id) == id))
{:noreply, assign(socket, :selected_themes, selected)}
@@ -272,7 +270,14 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
end
def handle_async(:lookup, {:exit, reason}, socket) do
{:noreply, put_flash(socket, :error, "Could not look up the FENs: #{inspect(reason)}")}
Logger.error("bulk_import.lookup_failed", reason: inspect(reason))
{:noreply,
put_flash(
socket,
:error,
"The lookup failed. Try again; if it keeps happening, check the server log."
)}
end
defp tablebase_status do
@@ -288,7 +293,8 @@ defmodule ChesstrainerWeb.EndgameLive.Import do
{:error, "Local tablebase is not configured. Set TABLEBASE_PATH to enable imports."}
{:error, reason} ->
{:error, "Local tablebase failed to load: #{inspect(reason)}"}
Logger.warning("bulk_import.tablebase_unavailable", reason: inspect(reason))
{:error, "The local tablebase failed to load. Check TABLEBASE_PATH and the server log."}
end
end
@@ -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}
@@ -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
@@ -182,12 +197,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
end
def fen_invalid(socket, %{"fen" => fen, "message" => message}) do
Logger.warning("board.fen_invalid", fen: fen, message: message)
{:noreply,
put_flash(
socket,
:error,
"Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})"
)}
put_flash(socket, :error, "The board couldn't load this position. Reset to try again.")}
end
def reset(socket) do
@@ -359,14 +372,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 +396,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 +506,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 +769,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
+97 -46
View File
@@ -77,11 +77,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
</div>
<PlayComponents.play_surface
:if={is_nil(@pool)}
session={true}
endgame={@endgame}
fen={@fen}
status={@status}
blocked_reason={@blocked_reason}
blocked={@blocked}
best_move={@best_move}
plies={@plies}
line={@line}
@@ -99,6 +100,26 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
rating={@user_rating}
rating_delta={@last_rating_delta}
/>
<section
:if={@pool}
id="pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">You've finished every puzzle at this difficulty</h2>
<p class="mt-1 text-sm text-muted">
There are no more {difficulty_label(@session.difficulty)} puzzles right now.
Try again, or pick another difficulty.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button id="change-difficulty" phx-click="stop_session">
Change difficulty
</.button>
</div>
</section>
<% else %>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div id="difficulty-picker" class="w-full max-w-md rounded-xl bg-base-100 p-6 shadow-xl">
@@ -155,6 +176,19 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<div class="mt-4">
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
</div>
<div
:if={@pool}
id="pool-empty"
class="mt-4 rounded-lg border border-warning/30 bg-warning/10 p-3 text-sm"
>
<p class="font-semibold">No puzzles available right now</p>
<p class="mt-1 text-muted">
There are no {difficulty_label(@pool.difficulty)} puzzles yet. Try again, or choose another difficulty.
</p>
<.button id="retry-pool" phx-click="retry_pool" class="mt-3">
<.icon name="hero-arrow-path" /> Retry
</.button>
</div>
<div class="mt-4 grid gap-2">
<%= 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
+7
View File
@@ -20,6 +20,13 @@ defmodule ChesstrainerWeb.Plugs.Prelaunch do
/robots.txt
/sitemap.xml
/favicon.ico
/favicon.svg
/favicon-16x16.png
/favicon-32x32.png
/apple-touch-icon.png
/android-chrome-192x192.png
/android-chrome-512x512.png
/site.webmanifest
)
@allowed_prefixes ~w(
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 781 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 B

After

Width:  |  Height:  |  Size: 15 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<circle cx="32" cy="32" r="32" fill="#17352d"/>
<path fill="#f4f0e6" d="M28.75 19.15Q29.69 18.56 29.69 17.57Q29.69 16.94 29.31 16.21Q28.93 15.49 28.93 14.93Q28.93 13.76 30.4 13Q32.56 15.06 32.75 16.19Q32.94 17.32 32.94 17.65Q32.94 18.84 32.08 19.15H32.18Q32.18 19.17 32.13 19.17Q45.74 27.81 46.89 51H22.25Q21.92 49.58 21.92 48.1Q21.92 44.04 27.06 40.45Q32.2 36.85 32.2 33.98Q32.2 33.78 32.18 33.6Q30.5 37.84 27.53 37.84H27.28Q24.99 41.55 22.37 41.55Q22.27 41.55 22.2 41.55L23.41 38.91L20.7 40.94Q17.8 40.23 17.11 38.12Q19.35 32.3 19.35 27.48Q19.35 26.79 19.3 26.13Q20.52 23.36 23.03 20.72Q23.11 20.47 23.11 20.24Q23.11 19.53 22.54 19.2Q21.97 18.87 21.97 17.98Q21.97 17.04 22.47 15.36Q25.12 16.05 26.54 19.15ZM22.22 25.62V26.03Q22.32 26.79 22.53 26.79H23.06Q24.81 26.79 24.81 25.55Q24.81 24.68 25.9 23.47H25.75Q23.31 23.47 22.37 25.09ZM19.45 37.05V37.66Q19.45 38.4 20.16 38.4H20.42Q22.25 38.02 22.25 36.67L22.07 35.81Q20.49 35.81 19.45 37.05ZM32.1 21.18 33.42 23.44Q42.95 30.27 43.1 49.68H45.06Q43.91 28.09 32.1 21.18Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 71 48" fill="currentColor" aria-hidden="true">
<path
d="m26.371 33.477-.552-.1c-3.92-.729-6.397-3.1-7.57-6.829-.733-2.324.597-4.035 3.035-4.148 1.995-.092 3.362 1.055 4.57 2.39 1.557 1.72 2.984 3.558 4.514 5.305 2.202 2.515 4.797 4.134 8.347 3.634 3.183-.448 5.958-1.725 8.371-3.828.363-.316.761-.592 1.144-.886l-.241-.284c-2.027.63-4.093.841-6.205.735-3.195-.16-6.24-.828-8.964-2.582-2.486-1.601-4.319-3.746-5.19-6.611-.704-2.315.736-3.934 3.135-3.6.948.133 1.746.56 2.463 1.165.583.493 1.143 1.015 1.738 1.493 2.8 2.25 6.712 2.375 10.265-.068-5.842-.026-9.817-3.24-13.308-7.313-1.366-1.594-2.7-3.216-4.095-4.785-2.698-3.036-5.692-5.71-9.79-6.623C12.8-.623 7.745.14 2.893 2.361 1.926 2.804.997 3.319 0 4.149c.494 0 .763.006 1.032 0 2.446-.064 4.28 1.023 5.602 3.024.962 1.457 1.415 3.104 1.761 4.798.513 2.515.247 5.078.544 7.605.761 6.494 4.08 11.026 10.26 13.346 2.267.852 4.591 1.135 7.172.555ZM10.751 3.852c-.976.246-1.756-.148-2.56-.962 1.377-.343 2.592-.476 3.897-.528-.107.848-.607 1.306-1.336 1.49Zm32.002 37.924c-.085-.626-.62-.901-1.04-1.228-1.857-1.446-4.03-1.958-6.333-2-1.375-.026-2.735-.128-4.031-.61-.595-.22-1.26-.505-1.244-1.272.015-.78.693-1 1.31-1.184.505-.15 1.026-.247 1.6-.382-1.46-.936-2.886-1.065-4.787-.3-2.993 1.202-5.943 1.06-8.926-.017-1.684-.608-3.179-1.563-4.735-2.408l-.077.057c1.29 2.115 3.034 3.817 5.004 5.271 3.793 2.8 7.936 4.471 12.784 3.73A66.714 66.714 0 0 1 37 40.877c1.98-.16 3.866.398 5.753.899Zm-9.14-30.345c-.105-.076-.206-.266-.42-.069 1.745 2.36 3.985 4.098 6.683 5.193 4.354 1.767 8.773 2.07 13.293.51 3.51-1.21 6.033-.028 7.343 3.38.19-3.955-2.137-6.837-5.843-7.401-2.084-.318-4.01.373-5.962.94-5.434 1.575-10.485.798-15.094-2.553Zm27.085 15.425c.708.059 1.416.123 2.124.185-1.6-1.405-3.55-1.517-5.523-1.404-3.003.17-5.167 1.903-7.14 3.972-1.739 1.824-3.31 3.87-5.903 4.604.043.078.054.117.066.117.35.005.699.021 1.047.005 3.768-.17 7.317-.965 10.14-3.7.89-.86 1.685-1.817 2.544-2.71.716-.746 1.584-1.159 2.645-1.07Zm-8.753-4.67c-2.812.246-5.254 1.409-7.548 2.943-1.766 1.18-3.654 1.738-5.776 1.37-.374-.066-.75-.114-1.124-.17l-.013.156c.135.07.265.151.405.207.354.14.702.308 1.07.395 4.083.971 7.992.474 11.516-1.803 2.221-1.435 4.521-1.707 7.013-1.336.252.038.503.083.756.107.234.022.479.255.795.003-2.179-1.574-4.526-2.096-7.094-1.872Zm-10.049-9.544c1.475.051 2.943-.142 4.486-1.059-.452.04-.643.04-.827.076-2.126.424-4.033-.04-5.733-1.383-.623-.493-1.257-.974-1.889-1.457-2.503-1.914-5.374-2.555-8.514-2.5.05.154.054.26.108.315 3.417 3.455 7.371 5.836 12.369 6.008Zm24.727 17.731c-2.114-2.097-4.952-2.367-7.578-.537 1.738.078 3.043.632 4.101 1.728a13 13 0 0 0 1.182 1.106c1.6 1.29 4.311 1.352 5.896.155-1.861-.726-1.861-.726-3.601-2.452Zm-21.058 16.06c-1.858-3.46-4.981-4.24-8.59-4.008a9.667 9.667 0 0 1 2.977 1.39c.84.586 1.547 1.311 2.243 2.055 1.38 1.473 3.534 2.376 4.962 2.07-.656-.412-1.238-.848-1.592-1.507Zl-.006.006-.036-.004.021.018.012.053Za.127.127 0 0 0 .015.043c.005.008.038 0 .058-.002Zl-.008.01.005.026.024.014Z"
fill="#FD4F00"
/>
</svg>

Before

Width:  |  Height:  |  Size: 3.0 KiB

+13
View File
@@ -0,0 +1,13 @@
{
"name": "Inner Square Chess",
"short_name": "Inner Square",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#f4f0e6",
"theme_color": "#17352d",
"icons": [
{ "src": "/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
{ "src": "/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
]
}
+12
View File
@@ -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
@@ -61,7 +61,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert html =~ "menu-button"
assert html =~ ~s(class="site-footer")
assert html =~ "© #{DateTime.utc_now().year} #{Branding.name()}"
assert html =~ ~p"/endgames"
assert html =~ ~p"/guest-train"
assert html =~ "/assets/js/marketing.js"
refute html =~ "/assets/js/app.js"
@@ -318,6 +318,9 @@ defmodule ChesstrainerWeb.PageControllerTest do
end
test "renders without endgames", %{conn: conn} do
previous = Application.get_env(:chesstrainer, :curated_endgame_codes)
on_exit(fn -> Application.put_env(:chesstrainer, :curated_endgame_codes, previous) end)
Application.put_env(:chesstrainer, :curated_endgame_codes, [])
html = conn |> get(~p"/") |> html_response(200)
@@ -327,8 +330,10 @@ defmodule ChesstrainerWeb.PageControllerTest do
refute html =~ "puzzle-card"
assert LazyHTML.attribute(LazyHTML.query(document, ".hero-actions a"), "href") == [
"/endgames"
"/guest-train"
]
assert html =~ "Start training"
end
test "unknown routes render the branded 404 page", %{conn: conn} do
@@ -31,9 +31,9 @@ defmodule ChesstrainerWeb.UserConfirmationControllerTest do
conn = get(conn, ~p"/users/confirm/oops")
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"User not found or token is invalid."
"That confirmation link is invalid or has expired. Log in to request a new one."
assert redirected_to(conn) == ~p"/users/register"
assert redirected_to(conn) == ~p"/users/log-in"
end
test "confirms a linked mailing-list opt-in", %{conn: conn, user: user} do
@@ -21,6 +21,15 @@ defmodule ChesstrainerWeb.UserDataControllerTest do
assert redirected_to(conn) == ~p"/users/log-in"
end
test "returns the styled 404 page for an unknown format", %{conn: conn} do
conn = get(conn, ~p"/users/profile/export/xml")
html = html_response(conn, 404)
assert html =~ "This page isn&#39;t on the board"
assert html =~ "Back to home"
assert get_resp_header(conn, "content-type") == ["text/html; charset=utf-8"]
end
test "downloads the user details and attempts as CSV", %{
conn: conn,
user: user,
@@ -84,7 +84,10 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
assert html =~ "max-w-2xl"
view |> form("#theme-form", %{theme_search: "Luc"}) |> render_change()
view
|> element("#theme-picker input[name='theme_search']")
|> render_change(%{theme_search: "Luc"})
view |> element("button", "Lucena") |> render_click()
view
@@ -109,10 +112,16 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
{:ok, view, _html} = live(conn, ~p"/admin/endgames/new")
view |> form("#theme-form", %{theme_search: "Luc"}) |> render_change()
view
|> element("#theme-picker input[name='theme_search']")
|> render_change(%{theme_search: "Luc"})
view |> element("button", "Lucena") |> render_click()
view |> form("#theme-form", %{theme_search: "Phil"}) |> render_change()
view
|> element("#theme-picker input[name='theme_search']")
|> render_change(%{theme_search: "Phil"})
view |> element("button", "Philidor") |> render_click()
html = render(view)
@@ -123,7 +132,11 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
test "creates and attaches a new theme inline", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/endgames/new")
view |> form("#theme-form", %{theme_search: "Lucerne"}) |> render_submit()
view
|> element("#theme-picker input[name='theme_search']")
|> render_change(%{theme_search: "Lucerne"})
view |> element("button", ~s(Create theme "Lucerne")) |> render_click()
assert render(view) =~ "Lucerne"
assert [%{name: "Lucerne"}] = Themes.search("Lucerne", "endgame")
@@ -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
@@ -35,7 +35,10 @@ defmodule ChesstrainerWeb.EndgameLive.ImportTest do
assert html =~ "KR v K"
assert html =~ "win"
view |> form("#theme-form", %{theme_search: "Luc"}) |> render_change()
view
|> element("#theme-picker input[name='theme_search']")
|> render_change(%{theme_search: "Luc"})
view |> element("button", "Lucena") |> render_click()
view |> element("button", "Import 1 endgame(s)") |> render_click()
@@ -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,12 +291,42 @@ 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&#39;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
describe "chess_fen_invalid" do
@tag capture_log: true
test "shows a flash when the chessground hook reports an unparseable FEN", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
@@ -297,8 +340,9 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
})
html = render(view)
assert html =~ "Endgame FEN is invalid"
assert html =~ "move number must be a positive integer"
assert html =~ "The board couldn&#39;t load this position. Reset to try again."
refute html =~ "Endgame FEN is invalid"
refute html =~ "move number must be a positive integer"
end
end
@@ -88,6 +88,8 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
assert has_element?(view, "#difficulty-hard")
assert has_element?(view, "#close-difficulty[href='/']")
assert has_element?(view, "a", "Return Home")
assert has_element?(view, "#connection-actions")
assert render(view) =~ ">Reload<"
refute has_element?(view, "#puzzle-search")
assert has_element?(view, "#rating-guide")
assert render(view) =~ "Choose a difficulty"
@@ -225,6 +227,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