mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
23
Commits
202b9b1f6a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2759b34296 | ||
|
|
e6f08e0ca6 | ||
|
|
946fc38756 | ||
|
|
80cb033077 | ||
|
|
7209923de7
|
||
|
|
f4ff1e00fb
|
||
|
|
514c6ac924
|
||
|
|
e0b446bbfb | ||
|
|
fa1fef7b62 | ||
|
|
37e0ac8e56 | ||
|
|
b33c5e334a | ||
|
|
aebb2aecfb | ||
|
|
8934d191ad | ||
|
|
021e412167 | ||
|
|
0563b5aca2 | ||
|
|
0ae4c5b6fd | ||
|
|
b41c8bf1a6 | ||
|
|
69b89f68ef | ||
|
|
f27e16af1d | ||
|
|
fddb94e2bd | ||
|
|
20b53dae6f | ||
|
|
9e76045862 | ||
|
|
624ddab644 |
@@ -7,6 +7,12 @@ MAILING_LIST_ENABLED=false
|
||||
SES_REGION=eu-north-1
|
||||
SES_ACCESS_KEY_ID=AKIA...
|
||||
SES_SECRET_ACCESS_KEY=...
|
||||
SES_CONFIGURATION_SET=my-first-configuration-set
|
||||
# Optional: override the sender or send everything to one address while testing.
|
||||
# MAIL_FROM=no-reply@mail.innersquare.app
|
||||
# MAIL_REDIRECT_TO=you@example.com
|
||||
# Optional: directory of local Syzygy .rtbw/.rtbz files. Ignored by the test
|
||||
# suite, which always uses the committed 3-piece fixtures.
|
||||
TABLEBASE_PATH=
|
||||
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
|
||||
+15
-5
@@ -105,6 +105,14 @@ carries a start time and a rating baseline for the timer and rating-gain
|
||||
monitor. Ephemeral — it lives only in the running LiveView, never persisted.
|
||||
_Avoid_: Run, game, attempt
|
||||
|
||||
**Repeat window**:
|
||||
The minimum interval before the same endgame may be served to the same user
|
||||
again. Selection skips endgames attempted inside the window; only when nothing
|
||||
else is available does the least recently attempted endgame come back. It is
|
||||
independent of the rating window, which decides whether a replay may move a
|
||||
rating.
|
||||
_Avoid_: Cooldown (reserved for tablebase rate-limiting), due date
|
||||
|
||||
## Ratings
|
||||
|
||||
**Rating**:
|
||||
@@ -128,11 +136,13 @@ systems; the trainer deliberately does not track it.
|
||||
_Avoid_: Variance, inconsistency
|
||||
|
||||
**Difficulty**:
|
||||
A choice — `easy`, `medium` or `hard` — that selects which puzzles to serve
|
||||
relative to the current user's rating: `medium` is near the user's rating,
|
||||
`easy` below it, `hard` above it. The band width is a configured constant. It is
|
||||
a property of a session, not of an endgame — the same endgame is easy for one
|
||||
user and hard for another.
|
||||
A choice — `easy`, `medium` or `hard` — that biases which puzzles are served
|
||||
relative to the current user's rating: `medium` centres on the user's rating,
|
||||
`easy` below it, `hard` above it. Candidates are weighted by how close their
|
||||
rating is to that centre, so a session draws mostly from near the target but the
|
||||
whole library stays reachable. The spread is a configured constant. It is a
|
||||
property of a session, not of an endgame — the same endgame is easy for one user
|
||||
and hard for another.
|
||||
_Avoid_: Level, rank, tier
|
||||
|
||||
## Infrastructure
|
||||
|
||||
@@ -43,6 +43,10 @@
|
||||
.avatar-stack i:last-child { background: var(--color-deep); color: var(--color-on-deep); }
|
||||
.puzzle-section { width: min(1180px, calc(100% - 48px)); margin: 0 auto; padding: 110px 0 125px; }
|
||||
.puzzle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
|
||||
.puzzle-coming-soon { min-height: 285px; display: grid; place-content: center; justify-items: center; gap: 10px; padding: 46px 28px; text-align: center; border: 1px dashed var(--color-hairline); border-radius: 12px; background: var(--color-canvas-raised); }
|
||||
.puzzle-coming-soon .eyebrow { margin-bottom: 6px; }
|
||||
.puzzle-coming-soon strong { font-family: 'DM Serif Display', serif; font-size: 30px; font-weight: 400; }
|
||||
.puzzle-coming-soon p { max-width: 420px; margin: 0; color: var(--color-muted); font-size: 14px; line-height: 1.7; }
|
||||
.puzzle-card { display: block; position: relative; min-height: 285px; padding: 25px; text-align: left; text-decoration: none; color: inherit; cursor: pointer; border: 1px solid var(--color-hairline); border-radius: 12px; background: rgba(255,255,255,.28); overflow: hidden; transition: transform .25s, background .25s, box-shadow .25s; }
|
||||
.puzzle-card:hover, .puzzle-card.active { transform: translateY(-5px); background: var(--color-canvas-raised); box-shadow: 0 18px 36px rgba(23,53,45,.08); }
|
||||
.puzzle-card.active { border-color: var(--color-success-text); }
|
||||
@@ -69,6 +73,7 @@ html[data-theme="dark"] .learning-strip { box-shadow: inset 0 1px 0 var(--color-
|
||||
@media (max-width: 650px) {
|
||||
.puzzle-section { width: calc(100% - 36px); padding: 80px 0; }
|
||||
.puzzle-grid { grid-template-columns: 1fr; }
|
||||
.puzzle-coming-soon { min-height: 255px; padding: 38px 22px; }
|
||||
.puzzle-card { min-height: 255px; }
|
||||
.progress-banner { width: calc(100% - 36px); padding: 48px 28px; flex-direction: column; align-items: flex-start; gap: 34px; }
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ h1 em { color: var(--color-coral); font-weight: 400; }
|
||||
.settings-subtitle {
|
||||
font-size: 1rem;;
|
||||
color: var(--color-muted);
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
|
||||
@@ -43,6 +43,13 @@
|
||||
/* Play board */
|
||||
#endgame-board { position: relative; }
|
||||
|
||||
/* Chessground's stock stylesheet shifts the file labels 24px right of the
|
||||
board, assuming a gutter we don't have, so they land on square boundaries
|
||||
instead of under each file. Place the row on the board and right-justify
|
||||
each label within its square; the row's width already matches the board
|
||||
because the container is sized to whole squares. */
|
||||
#endgame-board coords.files { left: 0; text-align: right; }
|
||||
|
||||
/* Chessground's wrapper has no intrinsic height; let it fill the sized
|
||||
aspect-ratio container so the board scales with the viewport. */
|
||||
#endgame-board .cg-wrap { width: 100%; height: 100%; }
|
||||
@@ -1,2 +1,9 @@
|
||||
.eyebrow { display: flex; align-items: center; gap: 9px; margin-bottom: 27px; color: var(--color-coral-text); text-transform: uppercase; letter-spacing: .13em; font-size: 12px; font-weight: 700; }
|
||||
.eyebrow svg { width: 20px; height: 20px; }
|
||||
.eyebrow svg { width: 20px; height: 20px; }
|
||||
|
||||
/* Icon-only external links, e.g. the Discord invite in the navbar and footer.
|
||||
Colour is inherited so the glyph matches the surrounding link row. */
|
||||
.discord-link { display: inline-flex; align-items: center; color: inherit; transition: opacity .2s; }
|
||||
.discord-link:hover { opacity: .55; }
|
||||
.discord-link:focus-visible { outline: 2px solid var(--color-coral-control); outline-offset: 3px; border-radius: 4px; }
|
||||
.discord-link svg { width: 20px; height: 20px; }
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
display: grid; grid-template-columns: 1.5fr repeat(3, 1fr); align-items: center; background: var(--color-deep); color: var(--color-on-deep);
|
||||
}
|
||||
|
||||
.learning-strip > p { max-width: 260px; color: var(--color-on-deep-muted); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote { margin: 0; max-width: 300px; }
|
||||
.learning-quote blockquote { margin: 0; color: var(--color-on-deep); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote figcaption { margin-top: 10px; color: var(--color-on-deep-faint); font-size: 10px; text-transform: uppercase; letter-spacing: .09em; }
|
||||
|
||||
.stat { padding-left: 34px; border-left: 1px solid rgba(255,255,255,.17); }
|
||||
.stat strong { display: block; font-family: 'DM Serif Display', serif; font-size: 28px; font-weight: 400; }
|
||||
@@ -15,7 +17,7 @@
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.learning-strip { padding: 38px 24px; grid-template-columns: 1fr 1fr; gap: 30px 10px; }
|
||||
.learning-strip > p { grid-column: 1 / -1; }
|
||||
.learning-quote { grid-column: 1 / -1; }
|
||||
.stat { padding-left: 18px; }
|
||||
.stat:last-child { grid-column: 1 / -1; }
|
||||
}
|
||||
@@ -14,6 +14,9 @@
|
||||
.nav-links a { transition: opacity .2s; }
|
||||
.nav-links a:hover { opacity: .55; }
|
||||
.nav-links a.nav-cta:hover { opacity: 1; }
|
||||
/* Utilities (colour mode, Discord) sit in the bar on desktop and in the
|
||||
collapsible menu on small screens. */
|
||||
.nav-menu-tools { display: none; }
|
||||
.nav-user-menu { position: relative; }
|
||||
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
|
||||
.nav-user-menu summary::-webkit-details-marker { display: none; }
|
||||
@@ -42,6 +45,11 @@ html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0
|
||||
.nav-links.open { display: flex; }
|
||||
.nav-cta { width: 100%; }
|
||||
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||
.nav-menu-tools { display: flex; align-items: center; justify-content: space-between; gap: 18px; width: 100%; }
|
||||
/* The menu owns these on small screens; keep them in the bar only when no
|
||||
menu is rendered (prelaunch with no links). */
|
||||
.nav-wrap:has(#nav-links) .nav-right > [role="radiogroup"],
|
||||
.nav-wrap:has(#nav-links) .nav-right > .discord-link { display: none; }
|
||||
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
|
||||
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||
}
|
||||
+22
-6
@@ -15,7 +15,8 @@ config :chesstrainer, :branding,
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@innersquare.app"
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
|
||||
# Prelaunch gating. Production sets these from PRELAUNCH and
|
||||
# MAILING_LIST_ENABLED; dev and test use these defaults.
|
||||
@@ -39,6 +40,16 @@ config :chesstrainer,
|
||||
ecto_repos: [Chesstrainer.Repo],
|
||||
generators: [timestamp_type: :utc_datetime]
|
||||
|
||||
# Password-login throttle. Failures are counted in fixed windows for each
|
||||
# client address and each normalised login. The address bucket is deliberately
|
||||
# wider so one account stays protected from distributed guessing while one
|
||||
# address cannot spray many accounts.
|
||||
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||
window_ms: :timer.minutes(15),
|
||||
max_per_login: 5,
|
||||
max_per_ip: 10,
|
||||
confirmation_cooldown_ms: :timer.minutes(15)
|
||||
|
||||
# Glicko rating system.
|
||||
#
|
||||
# `system_constant` is the volatility constraint passed through to the Glicko
|
||||
@@ -51,11 +62,16 @@ config :chesstrainer, :ratings,
|
||||
window_days: 7,
|
||||
rd_inflation_c: 10.0
|
||||
|
||||
# Difficulty bands for puzzle sessions. An endgame is "medium" when its rating
|
||||
# falls within `band_width` of the user's rating, "easy" below that band and
|
||||
# "hard" above it. Tweak to widen or narrow the served difficulty (e.g. 150 or
|
||||
# 200).
|
||||
config :chesstrainer, :puzzles, band_width: 100
|
||||
# Puzzle selection. Difficulty is a weighted bias towards a target rating —
|
||||
# `medium` targets the user's rating, `easy` 200 below it and `hard` 200 above
|
||||
# it — and `spread` is how many rating points it takes for a puzzle's chance to
|
||||
# fall off by a factor of e. `repeat_window_days` is how long an attempted
|
||||
# puzzle stays out of the pool. Tweak `spread` to widen or narrow the served
|
||||
# difficulty (e.g. 100 or 250).
|
||||
config :chesstrainer, :puzzles,
|
||||
spread: 150,
|
||||
repeat_window_days: 30,
|
||||
targets: [easy: -200, medium: 0, hard: 200]
|
||||
|
||||
# Public codes of the endgames pinned to the landing-page puzzle grid, in
|
||||
# display order. When empty (or short) the grid is topped up with a date-seeded
|
||||
|
||||
+25
-3
@@ -28,11 +28,33 @@ if mailing_list_enabled = System.get_env("MAILING_LIST_ENABLED") do
|
||||
config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1)
|
||||
end
|
||||
|
||||
# Sender address override. The default lives in config/config.exs; this lets a
|
||||
# deploy try a different From address (for example a new sending subdomain)
|
||||
# without a rebuild.
|
||||
if mail_from = System.get_env("MAIL_FROM") do
|
||||
branding = Application.get_env(:chesstrainer, :branding, [])
|
||||
config :chesstrainer, :branding, Keyword.put(branding, :mail_from, mail_from)
|
||||
end
|
||||
|
||||
# SES configuration set stamped on every outgoing email. The set is what links
|
||||
# a message to its SNS bounce and complaint notifications.
|
||||
config :chesstrainer,
|
||||
:ses_configuration_set,
|
||||
System.get_env("SES_CONFIGURATION_SET", "my-first-configuration-set")
|
||||
|
||||
# Rewrite every recipient to one address while testing. Leave unset in normal
|
||||
# operation; see `mix mail.check`.
|
||||
config :chesstrainer, :mail_redirect_to, System.get_env("MAIL_REDIRECT_TO")
|
||||
|
||||
# Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the
|
||||
# .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups
|
||||
# fall back to Lichess.
|
||||
if tablebase_path = System.get_env("TABLEBASE_PATH") do
|
||||
config :chesstrainer, :tablebase_path, tablebase_path
|
||||
# fall back to Lichess. Tests are always pinned to the committed 3-piece
|
||||
# fixtures by config/test.exs, so an exported TABLEBASE_PATH cannot make them
|
||||
# depend on whatever tables the developer happens to have downloaded.
|
||||
if config_env() != :test do
|
||||
if tablebase_path = System.get_env("TABLEBASE_PATH") do
|
||||
config :chesstrainer, :tablebase_path, tablebase_path
|
||||
end
|
||||
end
|
||||
|
||||
# Tablebase cache: size and the UTC time of the daily backup. Environment
|
||||
|
||||
+27
-4
@@ -3,13 +3,36 @@
|
||||
# This file is not installed automatically. On the shared VPS, add this block
|
||||
# to the existing Caddy config by hand, then validate and reload Caddy.
|
||||
#
|
||||
# The app listens on loopback only; Caddy is the public entry point.
|
||||
# Cloudflare sits in front of Caddy. Two things matter here:
|
||||
#
|
||||
# 1. Only accept requests from Cloudflare's published edge ranges.
|
||||
# 2. Replace X-Forwarded-For with Cloudflare's single-value CF-Connecting-IP
|
||||
# header, so the app's TRUST_FORWARDED_FOR=true path sees the visitor, not a
|
||||
# Cloudflare edge address.
|
||||
#
|
||||
# The ranges live in cloudflare-ranges.caddy next to this file. A systemd
|
||||
# timer refreshes them from https://www.cloudflare.com/ips-v4 and /ips-v6;
|
||||
# see deploy/update-cloudflare-ranges.sh and deploy/README.md.
|
||||
|
||||
innersquare.app {
|
||||
encode zstd gzip
|
||||
reverse_proxy 127.0.0.1:4100
|
||||
encode zstd gzip
|
||||
|
||||
@cloudflare {
|
||||
import cloudflare-ranges.caddy
|
||||
}
|
||||
|
||||
handle @cloudflare {
|
||||
reverse_proxy 127.0.0.1:4100 {
|
||||
header_up X-Forwarded-For {http.request.header.CF-Connecting-IP}
|
||||
}
|
||||
}
|
||||
|
||||
# Direct-to-origin requests cannot spoof Cloudflare's client-IP header.
|
||||
handle {
|
||||
respond "Access Denied" 403
|
||||
}
|
||||
}
|
||||
|
||||
www.innersquare.app {
|
||||
redir https://innersquare.app{uri} permanent
|
||||
redir https://innersquare.app{uri} permanent
|
||||
}
|
||||
|
||||
+777
-43
@@ -4,9 +4,10 @@ Phoenix release on the shared Ubuntu VPS, behind Caddy, with Postgres in Docker.
|
||||
|
||||
```text
|
||||
Internet
|
||||
└─ Caddy :443
|
||||
└─ Phoenix release 127.0.0.1:4100
|
||||
└─ Postgres 127.0.0.1:5432
|
||||
└─ Cloudflare (TLS, WAF, edge rate limiting)
|
||||
└─ Caddy :443 (cloudflare ranges only)
|
||||
└─ Phoenix release 127.0.0.1:4100
|
||||
└─ Postgres 127.0.0.1:5432
|
||||
```
|
||||
|
||||
## Pinned versions
|
||||
@@ -99,9 +100,16 @@ 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`.
|
||||
|
||||
Database dumps live in `/var/backups/chesstrainer`, outside `/opt/chesstrainer`
|
||||
and `priv/static`. See §Backups.
|
||||
|
||||
## Copy the deploy artifacts
|
||||
|
||||
Run these commands from a checkout of this repo on the VPS, or copy the
|
||||
@@ -133,6 +141,7 @@ MAILING_LIST_ENABLED=false
|
||||
SES_REGION=eu-north-1
|
||||
SES_ACCESS_KEY_ID=AKIA...
|
||||
SES_SECRET_ACCESS_KEY=...
|
||||
SES_CONFIGURATION_SET=my-first-configuration-set
|
||||
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
MATOMO_SITE_ID=6
|
||||
@@ -154,6 +163,47 @@ pages and the guest trainer. Signed-in account and admin pages are excluded.
|
||||
The privacy controls, Matomo server settings, retention, and opt-out behaviour
|
||||
are documented in `docs/analytics.md`.
|
||||
|
||||
## Transactional email
|
||||
|
||||
Every outgoing email goes through `Chesstrainer.Mail`, which applies the same
|
||||
house rules everywhere:
|
||||
|
||||
- **From**: `Inner Square Chess <no-reply@mail.innersquare.app>`. The address
|
||||
lives on the `mail.` subdomain; SES verifies the parent domain, and subdomains
|
||||
inherit that verification, so the subdomain does not need its own identity.
|
||||
- **Reply-To**: `support@innersquare.app`. Replies reach a monitored inbox even
|
||||
though the sender says `no-reply`.
|
||||
- **SES configuration set**: `SES_CONFIGURATION_SET`, default
|
||||
`my-first-configuration-set`. The set is what links a message to its SNS
|
||||
bounce and complaint notifications. It must exist in `SES_REGION`.
|
||||
|
||||
Optional overrides:
|
||||
|
||||
```sh
|
||||
MAIL_FROM=no-reply@mail.innersquare.app # try another sender without a rebuild
|
||||
MAIL_REDIRECT_TO=you@example.com # rewrite every recipient (staging/smoke tests)
|
||||
```
|
||||
|
||||
`MAIL_REDIRECT_TO` rewrites `to`, `cc` and `bcc` to one address, prefixes the
|
||||
subject with the original recipients and adds an `X-Original-To` header, so a
|
||||
redirected message explains itself. Leave it unset in normal operation.
|
||||
|
||||
Check delivery from the release environment:
|
||||
|
||||
```sh
|
||||
bin/chesstrainer eval 'Mix.Task.run("mail.check", ["--to", "you@example.com"])'
|
||||
```
|
||||
|
||||
or, in a checkout configured with the production SES variables,
|
||||
`mix mail.check --to you@example.com`. The task sends to the given address plus
|
||||
the SES mailbox simulators (`success@`, `bounce@`, `complaint@simulator...
|
||||
amazonses.com`) so the configuration set's bounce and complaint path can be
|
||||
exercised without touching a real inbox. Use `--no-simulators` to skip them.
|
||||
|
||||
DNS: the apex publishes DMARC (`p=quarantine`) with aggregate reports sent to
|
||||
`dmarc@innersquare.app`, and `mail.innersquare.app` carries the custom MAIL FROM
|
||||
SPF record and the SES feedback MX.
|
||||
|
||||
Generate the two secrets:
|
||||
|
||||
```sh
|
||||
@@ -440,15 +490,34 @@ The unit includes `ConditionPathExists=/opt/chesstrainer/current/bin/server`, so
|
||||
it is safe to enable before the first release. systemd skips it until a release
|
||||
is in place.
|
||||
|
||||
The backup unit and timer are installed separately; see §Backups.
|
||||
|
||||
## Caddy
|
||||
|
||||
On the current VPS the Caddyfile is a single file with no imports. Add the block
|
||||
from `deploy/Caddyfile` by hand:
|
||||
Add the site block from `deploy/Caddyfile` by hand. It imports
|
||||
`cloudflare-ranges.caddy`, which is generated by
|
||||
`deploy/update-cloudflare-ranges.sh` and refreshed by a systemd timer.
|
||||
|
||||
Caddy must only accept Cloudflare traffic and must replace `X-Forwarded-For`
|
||||
with Cloudflare's `CF-Connecting-IP` value:
|
||||
|
||||
```caddy
|
||||
innersquare.app {
|
||||
encode zstd gzip
|
||||
reverse_proxy 127.0.0.1:4100
|
||||
|
||||
@cloudflare {
|
||||
import cloudflare-ranges.caddy
|
||||
}
|
||||
|
||||
handle @cloudflare {
|
||||
reverse_proxy 127.0.0.1:4100 {
|
||||
header_up X-Forwarded-For {http.request.header.CF-Connecting-IP}
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
respond "Access Denied" 403
|
||||
}
|
||||
}
|
||||
|
||||
www.innersquare.app {
|
||||
@@ -456,7 +525,72 @@ www.innersquare.app {
|
||||
}
|
||||
```
|
||||
|
||||
If a new VPS uses imports, put the block in its own site file instead.
|
||||
Install the range file and the hourly refresh timer:
|
||||
|
||||
```sh
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||
/etc/caddy/cloudflare-ranges.caddy
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||
```
|
||||
|
||||
The installed pieces are:
|
||||
|
||||
| Path | Mode | Purpose |
|
||||
|---|---|---|
|
||||
| `/usr/local/sbin/chesstrainer-update-cloudflare-ranges` | `0755` | fetch/validate/reload script |
|
||||
| `/etc/caddy/cloudflare-ranges.caddy` | `0644` | generated `remote_ip` list |
|
||||
| `/etc/systemd/system/chesstrainer-cloudflare-ranges.service` | `0644` | oneshot service |
|
||||
| `/etc/systemd/system/chesstrainer-cloudflare-ranges.timer` | `0644` | hourly timer |
|
||||
|
||||
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||
The timer only depends on the installed copies; it does not read the repo.
|
||||
|
||||
Run it once manually and enable the timer:
|
||||
|
||||
```sh
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||
sudo journalctl -u chesstrainer-cloudflare-ranges.service -n 50 --no-pager
|
||||
```
|
||||
|
||||
The script fetches <https://www.cloudflare.com/ips-v4> and
|
||||
<https://www.cloudflare.com/ips-v6>, validates the result, and reloads Caddy
|
||||
only when the ranges actually changed. If the download, Caddy validation or
|
||||
reload fails, it keeps or restores the previous file.
|
||||
|
||||
Check the timer and last run:
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||
systemctl status chesstrainer-cloudflare-ranges.service
|
||||
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||
```
|
||||
|
||||
Do not edit `/etc/caddy/cloudflare-ranges.caddy` by hand; the next timer run
|
||||
overwrites it.
|
||||
|
||||
To update the refresher itself, replace the installed script or unit files from
|
||||
the deploy directory, then:
|
||||
|
||||
```sh
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl restart chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||
```
|
||||
|
||||
Without this, `TRUST_FORWARDED_FOR=true` records a Cloudflare edge address
|
||||
instead of the visitor, and the login throttle and guest puzzle limit bucket
|
||||
whole Cloudflare POPs together.
|
||||
|
||||
If a new VPS uses imports, put the site block in its own file instead; keep the
|
||||
`import cloudflare-ranges.caddy` path next to the Caddyfile.
|
||||
|
||||
Do **not** switch Caddy until a release is running and verified on
|
||||
`127.0.0.1:4100`. Before that, keep the static coming-soon site live.
|
||||
@@ -468,8 +602,16 @@ sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
sudo systemctl reload caddy
|
||||
```
|
||||
|
||||
A direct request to the origin with a forged `CF-Connecting-IP` header should
|
||||
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 off (see
|
||||
#153) and the free-plan login flood rule: 10 POSTs per 10 seconds per IP,
|
||||
blocked for 10 seconds.
|
||||
|
||||
## Building a release
|
||||
|
||||
Build on a machine matching Ubuntu 24.04 / glibc 2.39, or let CI do it.
|
||||
@@ -510,12 +652,13 @@ The script:
|
||||
|
||||
1. Extracts into `/opt/chesstrainer/releases/<timestamp>`
|
||||
2. Fixes ownership
|
||||
3. Flips `/opt/chesstrainer/current`
|
||||
4. Restarts `chesstrainer.service`
|
||||
5. Migrations run via `ExecStartPre`
|
||||
6. Polls `/health`
|
||||
7. Rolls back to the previous release on failure
|
||||
8. Prunes old releases, keeping 5 by default
|
||||
3. Takes a verified pre-deploy database dump, aborting if it fails (see §Backups)
|
||||
4. Flips `/opt/chesstrainer/current`
|
||||
5. Restarts `chesstrainer.service`
|
||||
6. Migrations run via `ExecStartPre`
|
||||
7. Polls `/health`
|
||||
8. Rolls back to the previous release on failure
|
||||
9. Prunes old releases, keeping 5 by default
|
||||
|
||||
Verify locally before touching Caddy:
|
||||
|
||||
@@ -550,6 +693,10 @@ KEEP_RELEASES=5 \
|
||||
sudo -E /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
|
||||
```
|
||||
|
||||
Every activation takes a verified pre-deploy dump before migrations run. If
|
||||
Postgres is intentionally unavailable and you accept the risk, add
|
||||
`SKIP_PRE_DEPLOY_BACKUP=1` to the override list; see §Backups.
|
||||
|
||||
## GitHub Actions CD
|
||||
|
||||
Merging to `main` (or running the workflow manually) tests, builds, uploads,
|
||||
@@ -613,7 +760,8 @@ The workflow:
|
||||
1. Runs `mix precommit` against Postgres.
|
||||
2. Builds the release artifact on `ubuntu-24.04`.
|
||||
3. On `main` or `workflow_dispatch`, uploads the tarball, installs the SSH key,
|
||||
runs `sudo -n .../activate`, and performs public smoke checks.
|
||||
runs `sudo -n .../activate`, and performs public smoke checks. Activation
|
||||
takes a pre-deploy dump first and fails if it cannot.
|
||||
4. A failed activation health check rolls back to the previous release.
|
||||
|
||||
Manual dispatch is available from the Actions UI or:
|
||||
@@ -636,6 +784,10 @@ sudo /opt/chesstrainer/src/deploy/rollback 20261109120000
|
||||
|
||||
The script flips `current`, restarts the service, and checks `/health`.
|
||||
|
||||
Rollback reverts the release, not the database: migrations are not reversed. If
|
||||
a migration changed data, restore the matching pre-deploy dump instead; see
|
||||
§Backups.
|
||||
|
||||
## Logs and health
|
||||
|
||||
```sh
|
||||
@@ -646,7 +798,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
|
||||
|
||||
@@ -694,54 +848,624 @@ 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
|
||||
service and does not require direct database access:
|
||||
|
||||
```sh
|
||||
sudo /opt/chesstrainer/current/bin/chesstrainer remote
|
||||
```
|
||||
|
||||
You should get a prompt like `iex(chesstrainer@<host>)1>`. Exit with **Ctrl-C
|
||||
twice**. Never call `System.halt/0`, `:init.stop/0`, or
|
||||
`Application.stop(:chesstrainer)` from this shell — those stop production.
|
||||
|
||||
Use it for account and role management. Go through the application contexts
|
||||
(not SQL) so changesets, bcrypt hashing, timestamps, and token bookkeeping stay
|
||||
consistent:
|
||||
|
||||
```elixir
|
||||
# Look up by email or username
|
||||
u = Chesstrainer.Accounts.get_user_by_login("owen")
|
||||
|
||||
# Promote or demote
|
||||
{:ok, u} = Chesstrainer.Accounts.update_user_role(u, :super_admin)
|
||||
|
||||
# Confirm an account without sending email
|
||||
{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u))
|
||||
|
||||
# Create an account, generating its password server-side
|
||||
pw = :crypto.strong_rand_bytes(18) |> Base.url_encode64(padding: false)
|
||||
|
||||
{:ok, u} =
|
||||
Chesstrainer.Accounts.register_user(%{
|
||||
email: "you@example.com",
|
||||
username: "owen",
|
||||
password: pw
|
||||
})
|
||||
|
||||
{:ok, u} = Chesstrainer.Repo.update(Chesstrainer.Accounts.User.confirm_changeset(u))
|
||||
pw
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `register_user/1` hashes the password with bcrypt; `password` is virtual and
|
||||
is never written to the database.
|
||||
- Do not type passwords into the shell if you can avoid it — IEx may keep a
|
||||
history file — and never paste a password from shell history. Generate one as
|
||||
above and change it later at `/users/profile/settings`.
|
||||
- `mix accounts.promote` still works when a compiled source checkout is present
|
||||
on the host, but the release shell is the supported production path.
|
||||
- There is no guard against demoting the last `super_admin` outside the future
|
||||
admin UI, so check the result before demoting.
|
||||
|
||||
If `remote` fails while booting its client VM (for example
|
||||
`Kernel pid terminated (logger)` with `code_server`/`persistent_term` in the
|
||||
trace), the deployed release is stale, mixed, or missing IEx: rebuild and
|
||||
redeploy it. To attach in the meantime, use the release's own ERTS:
|
||||
|
||||
```sh
|
||||
sudo bash -c '
|
||||
COOKIE=$(cat /opt/chesstrainer/current/releases/COOKIE)
|
||||
exec /opt/chesstrainer/current/erts-*/bin/erl \
|
||||
-sname debug -setcookie "$COOKIE" -remsh chesstrainer
|
||||
'
|
||||
```
|
||||
|
||||
That shell speaks Erlang syntax, so quote Elixir module atoms, e.g.
|
||||
`'Elixir.Chesstrainer.Accounts':register_user(...)`.
|
||||
|
||||
## Backups
|
||||
|
||||
`docker exec` connects over the container's Unix socket, which the Postgres
|
||||
image trusts locally, so `pg_dump` needs no password. Run it as the owner
|
||||
(`chesstrainer`), not `chesstrainer_ro`: a full dump also needs sequence access
|
||||
and ownership information.
|
||||
Backups are produced on the VPS, encrypted there, and pulled to a workstation.
|
||||
Nothing leaves the VPS unencrypted, and the VPS never holds the key that could
|
||||
read the archives.
|
||||
|
||||
Take a compressed logical backup (custom format, restorable with `pg_restore`):
|
||||
### What runs
|
||||
|
||||
| Where | What | When | Retention |
|
||||
|---|---|---|---|
|
||||
| VPS | `chesstrainer-backup.timer` → `chesstrainer-backup.service` | daily 03:15 UTC, `Persistent=true`, 5 min jitter | 3 days plaintext, 14 days encrypted |
|
||||
| VPS | the same script, called by `deploy/activate` | before every migration | last 5 pre-deploy sets |
|
||||
| Workstation | `chesstrainer-backup-pull.timer` | daily 12:00 local, 10 min after boot | 7 daily, 4 weekly, 6 monthly |
|
||||
| Workstation | `chesstrainer-backup-drill.timer` | monthly on the 1st at 09:00 | `drills.log` is never pruned |
|
||||
|
||||
Each run writes one JSON line (`backup.completed`, `backup.failed`,
|
||||
`backup.skipped`, `pull.completed`, `pull.failed`, `pull.skipped`,
|
||||
`drill.completed`, `drill.failed`) so #140's log shipping can alert on it. A
|
||||
`skipped` line means another run held the lock; it is not an alarm.
|
||||
|
||||
### What a dump contains
|
||||
|
||||
- `<ts>.dump` — `pg_dump -Fc` of `chesstrainer_prod`
|
||||
- `<ts>.globals.sql` — `pg_dumpall --globals-only`, enough to recreate
|
||||
`chesstrainer` and `chesstrainer_ro` on a fresh cluster
|
||||
- `<ts>.counts` — row counts for `users`, `endgames`, `attempts`, used by the drill
|
||||
- `<ts>.sha256` — checksums for the three files above
|
||||
|
||||
Not backed up, by design: tablebases and the tablebase cache (both are
|
||||
re-fetchable), anything under `priv/static`, and release tarballs. Dumps contain
|
||||
user emails and bcrypt hashes: they are `0600 root` while plaintext, encrypted
|
||||
before they leave the box, and pruned aggressively.
|
||||
|
||||
### RPO and RTO
|
||||
|
||||
RPO is 24 hours on the VPS and "the age of the newest pulled archive" off-box.
|
||||
The pull runs daily, so a laptop that is off for a day leaves the newest
|
||||
off-site copy around 48 hours old; the VPS keeps 14 days of encrypted archives,
|
||||
which bounds how far behind the pull can fall. RTO is under an hour: create the
|
||||
database, restore the newest dump, activate a release (see *Disaster recovery*).
|
||||
|
||||
### One-time setup: VPS
|
||||
|
||||
Install `age`. Encryption happens on the server; only the workstation can
|
||||
decrypt.
|
||||
|
||||
```sh
|
||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
||||
pg_dump -U chesstrainer -d chesstrainer_prod -Fc \
|
||||
> /var/backups/chesstrainer-$(date -u +%Y%m%d%H%M%S).dump
|
||||
sudo apt install age
|
||||
```
|
||||
|
||||
For a plain SQL file instead (human-readable, restorable with `psql`):
|
||||
Create the configuration file. Generate `AGE_RECIPIENT` on the workstation
|
||||
first (next section) and paste the public key.
|
||||
|
||||
```sh
|
||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
||||
pg_dump -U chesstrainer -d chesstrainer_prod \
|
||||
| gzip > /var/backups/chesstrainer-$(date -u +%Y%m%d%H%M%S).sql.gz
|
||||
sudo install -m 600 /dev/null /etc/chesstrainer/backup.env
|
||||
sudoedit /etc/chesstrainer/backup.env
|
||||
```
|
||||
|
||||
Check that a custom-format dump is readable before trusting it:
|
||||
Start from `deploy/backup.env.example`. The required values are `AGE_RECIPIENT`
|
||||
and `HEALTHCHECK_URL`.
|
||||
|
||||
Create a healthchecks.io check with a period of 1 day and a grace time of 4
|
||||
hours, then paste its ping URL into `HEALTHCHECK_URL`. The script pings it after
|
||||
a good run and `<url>/fail` after a bad one, so silence means "no backup
|
||||
finished", even when the VPS itself is down.
|
||||
|
||||
Install the script and units:
|
||||
|
||||
```sh
|
||||
sudo docker exec -i chesstrainer-db pg_restore -l \
|
||||
< /var/backups/<timestamp>.dump > /dev/null
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/backup \
|
||||
/usr/local/sbin/chesstrainer-backup
|
||||
sudo install -m 0644 \
|
||||
/opt/chesstrainer/src/deploy/chesstrainer-backup.service \
|
||||
/opt/chesstrainer/src/deploy/chesstrainer-backup.timer \
|
||||
/opt/chesstrainer/src/deploy/chesstrainer-backup-failure.service \
|
||||
/etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-backup.timer
|
||||
```
|
||||
|
||||
Restore into a scratch database (do not restore over the live database without
|
||||
stopping `chesstrainer` first):
|
||||
The timer runs the installed `/usr/local/sbin/chesstrainer-backup`, not the
|
||||
copy under `/opt/chesstrainer/src`, because that tree is writable by the
|
||||
application user. When `deploy/backup` changes, copy it to both places so the
|
||||
timer and `deploy/activate` use the same script.
|
||||
|
||||
Run it once and inspect the result:
|
||||
|
||||
```sh
|
||||
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
|
||||
createdb -U chesstrainer chesstrainer_restore
|
||||
sudo docker exec -i chesstrainer-db pg_restore -U chesstrainer \
|
||||
-d chesstrainer_restore < /var/backups/<timestamp>.dump
|
||||
sudo systemctl start chesstrainer-backup
|
||||
sudo journalctl -u chesstrainer-backup -n 20 --no-pager -o cat
|
||||
sudo ls -l /var/backups/chesstrainer /var/backups/chesstrainer/offsite
|
||||
systemctl list-timers chesstrainer-backup.timer
|
||||
```
|
||||
|
||||
Example nightly entry in root's crontab (`sudo crontab -e`):
|
||||
Expect a `.dump`, `.globals.sql`, `.counts` and `.sha256` at mode `0600`, and
|
||||
one `.tar.age` in `offsite/` at mode `0644`. `offsite/` is the only thing the
|
||||
workstation reads, which is why the pull needs no `sudo`. The vault directory is
|
||||
`0711`, so the workstation user can traverse into `offsite/` but cannot list the
|
||||
plaintext dumps.
|
||||
|
||||
```cron
|
||||
15 3 * * * docker compose -f /home/<username>/docker-compose.yml exec -T chesstrainer-db pg_dump -U chesstrainer -d chesstrainer_prod -Fc > /var/backups/chesstrainer-$(date +\%Y\%m\%d).dump
|
||||
### One-time setup: workstation
|
||||
|
||||
```sh
|
||||
sudo apt install age rsync
|
||||
mkdir -p ~/.config/chesstrainer
|
||||
chmod 700 ~/.config/chesstrainer
|
||||
age-keygen -o ~/.config/chesstrainer/age.key
|
||||
chmod 600 ~/.config/chesstrainer/age.key
|
||||
grep 'public key' ~/.config/chesstrainer/age.key
|
||||
```
|
||||
|
||||
Keep `/var/backups` outside `/opt/chesstrainer/releases` and copy backups off
|
||||
the VPS regularly. A backup that is only on the VPS is not a backup.
|
||||
Copy that public key into `AGE_RECIPIENT` on the VPS. **Back up the private
|
||||
key** (password manager, printed copy, offline disk): without it every archive
|
||||
is unreadable, and the VPS deliberately cannot decrypt them.
|
||||
|
||||
Create the pull configuration:
|
||||
|
||||
```sh
|
||||
install -m 600 /dev/null ~/.config/chesstrainer/backup-pull.env
|
||||
$EDITOR ~/.config/chesstrainer/backup-pull.env
|
||||
```
|
||||
|
||||
Start from `deploy/workstation/backup-pull.env.example`. `DEST` should point at
|
||||
a real disk, for example `/mnt/Mint Data/chesstrainer-backups`. The script
|
||||
refuses to run when `DEST`'s parent is missing, so an unmounted disk cannot
|
||||
silently fill the root filesystem.
|
||||
|
||||
Set `PULL_HEALTHCHECK_URL` to a second healthchecks.io check with a long period
|
||||
(for example 72 hours) if you want to hear about it when the workstation stops
|
||||
pulling. Leave it empty for journal-only reporting.
|
||||
|
||||
Install the scripts and user units:
|
||||
|
||||
```sh
|
||||
REPO=~/Desktop/chess-trainer # wherever this repo is cloned
|
||||
|
||||
install -d ~/.local/bin
|
||||
install -m 0755 "$REPO/deploy/workstation/backup-pull" ~/.local/bin/chesstrainer-backup-pull
|
||||
install -m 0755 "$REPO/deploy/workstation/backup-drill" ~/.local/bin/chesstrainer-backup-drill
|
||||
|
||||
install -d ~/.config/systemd/user
|
||||
install -m 0644 \
|
||||
"$REPO/deploy/workstation/chesstrainer-backup-pull.service" \
|
||||
"$REPO/deploy/workstation/chesstrainer-backup-pull.timer" \
|
||||
"$REPO/deploy/workstation/chesstrainer-backup-drill.service" \
|
||||
"$REPO/deploy/workstation/chesstrainer-backup-drill.timer" \
|
||||
"$REPO/deploy/workstation/chesstrainer-backup-alert@.service" \
|
||||
~/.config/systemd/user/
|
||||
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now chesstrainer-backup-pull.timer
|
||||
systemctl --user enable --now chesstrainer-backup-drill.timer
|
||||
sudo loginctl enable-linger "$USER"
|
||||
```
|
||||
|
||||
`enable-linger` lets the user timers run while the laptop is on but you are not
|
||||
logged in. The pull also fires ten minutes after boot, and `Persistent=true`
|
||||
catches up after the machine was off. Verify lingering stuck:
|
||||
|
||||
```sh
|
||||
loginctl show-user "$USER" -p Linger # Linger=yes
|
||||
```
|
||||
|
||||
Run the first pull and drill by hand:
|
||||
|
||||
```sh
|
||||
~/.local/bin/chesstrainer-backup-pull
|
||||
ls -l "/mnt/Mint Data/chesstrainer-backups"
|
||||
~/.local/bin/chesstrainer-backup-drill
|
||||
cat "/mnt/Mint Data/chesstrainer-backups/drills.log"
|
||||
```
|
||||
|
||||
A passing drill line looks like:
|
||||
|
||||
```json
|
||||
{"timestamp":"2026-11-11T21:05:46Z","event":"drill.completed","archive":"20261111T120000Z.tar.age","result":"pass","counts":"users=3,endgames=42,attempts=900","duration_s":3}
|
||||
```
|
||||
|
||||
The drill creates a throwaway `postgres:18.6` container, applies the globals
|
||||
dump, asserts that `chesstrainer` and `chesstrainer_ro` exist, restores into
|
||||
`chesstrainer_restore`, and compares the three row counts with the `.counts`
|
||||
file from dump time. Restored counts may be higher (the counts are taken moments
|
||||
before the dump); lower counts fail the drill.
|
||||
|
||||
### Retention
|
||||
|
||||
| Location | Plaintext | Encrypted | Notes |
|
||||
|---|---|---|---|
|
||||
| VPS `/var/backups/chesstrainer` | 3 days | 14 days | pre-deploy sets: last 5 |
|
||||
| Workstation `DEST` | never | 7 daily, 4 weekly, 6 monthly | monthly copies outlive the VPS copies |
|
||||
|
||||
The VPS is a staging area for the workstation; weekly and monthly generations
|
||||
accumulate there. If the laptop is off for more than 14 days, the archives the
|
||||
VPS dropped in the meantime are gone — that is the documented off-site RPO
|
||||
trade-off. Moving to an always-on destination (a second host or object storage
|
||||
with restic) is tracked in #151.
|
||||
|
||||
### Restore a dump
|
||||
|
||||
Always restore into a scratch database first. From an archive on the
|
||||
workstation:
|
||||
|
||||
```sh
|
||||
WORK=$(mktemp -d)
|
||||
age --decrypt -i ~/.config/chesstrainer/age.key \
|
||||
-o "$WORK/dump.tar" \
|
||||
"/mnt/Mint Data/chesstrainer-backups/<timestamp>.tar.age"
|
||||
tar -xf "$WORK/dump.tar" -C "$WORK"
|
||||
(cd "$WORK" && sha256sum --check --strict <timestamp>.sha256)
|
||||
```
|
||||
|
||||
Then restore into a scratch container:
|
||||
|
||||
```sh
|
||||
docker run --rm -d --name restore-check \
|
||||
-e POSTGRES_PASSWORD=restore -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18.6
|
||||
docker exec restore-check psql -U postgres -c 'create database chesstrainer_restore'
|
||||
docker exec -i restore-check pg_restore -U postgres -d chesstrainer_restore \
|
||||
--single-transaction --exit-on-error < "$WORK/<timestamp>.dump"
|
||||
docker exec restore-check psql -U postgres -d chesstrainer_restore \
|
||||
-c 'select count(*) from users; select count(*) from attempts;'
|
||||
docker rm -f restore-check
|
||||
rm -rf "$WORK"
|
||||
```
|
||||
|
||||
### Disaster recovery
|
||||
|
||||
1. Build a new VPS following this README through *First-time setup*, without
|
||||
activating a release or switching Caddy.
|
||||
2. Decrypt and unpack the newest archive on the workstation (above).
|
||||
3. Copy the dump and globals to the new VPS:
|
||||
`scp "$WORK/<timestamp>.dump" "$WORK/<timestamp>.globals.sql" <VPS_USER>@<VPS_HOST>:/tmp/`
|
||||
4. Recreate the cluster roles. Connect as `chesstrainer`: it is the container's
|
||||
superuser (`POSTGRES_USER`), and the dump's final grants are issued
|
||||
`GRANTED BY chesstrainer`, which another role cannot replay. The line that
|
||||
recreates `chesstrainer` itself reports "already exists" and is harmless:
|
||||
`sudo docker exec -i chesstrainer-db psql -U chesstrainer < /tmp/<timestamp>.globals.sql`
|
||||
5. Create the database and restore it:
|
||||
`sudo docker exec chesstrainer-db createdb -U chesstrainer chesstrainer_prod`
|
||||
`sudo docker exec -i chesstrainer-db pg_restore -U chesstrainer -d chesstrainer_prod --single-transaction --exit-on-error < /tmp/<timestamp>.dump`
|
||||
6. Verify the row counts, activate a release, then restore the Caddy block.
|
||||
7. Take a fresh backup (`sudo systemctl start chesstrainer-backup`) and pull so
|
||||
the new VPS is covered immediately.
|
||||
|
||||
`pg_dump` and `pg_restore` must come from the container's Postgres 18, not the
|
||||
host.
|
||||
|
||||
### Pre-deploy dump
|
||||
|
||||
`deploy/activate` calls `chesstrainer-backup` with `BACKUP_TAG=predeploy` after
|
||||
extracting the release and before flipping `current`, so the state before
|
||||
`bin/migrate` runs in `ExecStartPre` is always recoverable. A failed dump aborts
|
||||
the activation. The escape hatch is deliberate and should be rare:
|
||||
|
||||
```sh
|
||||
sudo SKIP_PRE_DEPLOY_BACKUP=1 /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
|
||||
```
|
||||
|
||||
If the installed script is missing, `activate` uses the `backup` next to it; if
|
||||
neither exists it refuses to activate rather than migrate without a dump. The
|
||||
GitHub Actions deploy job inherits the same behaviour.
|
||||
|
||||
### Run it by hand
|
||||
|
||||
Every timer can be triggered directly. On the VPS:
|
||||
|
||||
```sh
|
||||
# exactly what the timer runs
|
||||
sudo systemctl start chesstrainer-backup
|
||||
sudo journalctl -u chesstrainer-backup -n 20 -o cat
|
||||
|
||||
# an ad-hoc dump with its own tag
|
||||
sudo BACKUP_TAG=manual /usr/local/sbin/chesstrainer-backup
|
||||
|
||||
# schedule, last result and last exit
|
||||
systemctl list-timers chesstrainer-backup.timer
|
||||
systemctl show chesstrainer-backup.service -p Result -p ExecMainExitTimestamp
|
||||
```
|
||||
|
||||
On the workstation:
|
||||
|
||||
```sh
|
||||
# pull now, or through the unit (same PATH and OnFailure handling)
|
||||
~/.local/bin/chesstrainer-backup-pull
|
||||
systemctl --user start chesstrainer-backup-pull.service
|
||||
|
||||
# drill the newest archive, or a named one
|
||||
~/.local/bin/chesstrainer-backup-drill
|
||||
~/.local/bin/chesstrainer-backup-drill 20261111T213734Z.tar.age
|
||||
|
||||
# results and schedule
|
||||
cat "/mnt/Mint Data/chesstrainer-backups/drills.log"
|
||||
systemctl --user list-timers 'chesstrainer-backup-*'
|
||||
```
|
||||
|
||||
A `backup.skipped` or `pull.skipped` line means another run held the lock; that
|
||||
run reports the outcome. After fixing a failure, clear the unit with
|
||||
`systemctl --user reset-failed chesstrainer-backup-pull.service` (or
|
||||
`sudo systemctl reset-failed chesstrainer-backup.service`).
|
||||
|
||||
Enabling the pull timer fires it once straight away: its `OnBootSec=10m` is
|
||||
measured from boot, so enabling it hours after boot triggers immediately. That
|
||||
is expected and harmless.
|
||||
|
||||
### Monitoring
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-backup.timer
|
||||
sudo journalctl -u chesstrainer-backup --since "2 days ago" -o cat
|
||||
sudo systemctl --failed
|
||||
systemctl --user list-timers chesstrainer-backup-pull.timer chesstrainer-backup-drill.timer
|
||||
journalctl --user -u chesstrainer-backup-pull --since "2 days ago" -o cat
|
||||
```
|
||||
|
||||
A failed run produces both `backup.failed` (from the script) and
|
||||
`backup.unit-failed` (from the `OnFailure` unit). The healthchecks.io check is
|
||||
the backstop: if the VPS dies, the ping stops and you are emailed. The pull
|
||||
fails when the newest archive is more than 48 hours old, which catches a stopped
|
||||
VPS timer the next time the workstation pulls.
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
|---|---|
|
||||
| `backup.failed: missing command: age` | `sudo apt install age` |
|
||||
| `backup.failed: only N MB free` | disk full on the VPS; prune old releases or grow the disk |
|
||||
| `backup.failed: pg_dump failed` | `chesstrainer-db` is down or restarting — check `docker ps` |
|
||||
| `backup.failed: globals dump is missing role …` | the role was renamed; update `EXPECTED_ROLES` |
|
||||
| `pull.failed: rsync … failed` | SSH key, host key, or the VPS is unreachable |
|
||||
| `pull.failed: newest archive … is Nh old` | the VPS backup timer stopped; check it before touching the workstation |
|
||||
| `drill.failed: pg_restore failed` | archive is corrupt; keep it for diagnosis and restore an earlier one |
|
||||
|
||||
Never put dumps anywhere under `priv/static` or the release directory, and never
|
||||
restore over `chesstrainer_prod` while the application is running.
|
||||
|
||||
## New VPS checklist
|
||||
|
||||
@@ -753,6 +1477,16 @@ the VPS regularly. A backup that is only on the VPS is not a backup.
|
||||
until a release exists.
|
||||
6. Release built on a matching Ubuntu runner and activated.
|
||||
7. `/health` and `/` verified on `127.0.0.1:4100`.
|
||||
8. Caddy block added, validated, reloaded.
|
||||
8. Caddy block, `cloudflare-ranges.caddy`, and the CIDR refresh timer added;
|
||||
validated and reloaded.
|
||||
9. Public `/`, `/privacy`, `/terms-conditions`, and `/health` verified.
|
||||
10. Read-only role created, tunnel verified, backups scheduled and tested.
|
||||
10. Read-only role created and tunnel verified.
|
||||
11. `age` installed, `/etc/chesstrainer/backup.env` written, backup script and
|
||||
units installed, timer enabled, and one manual run produces a dump plus a
|
||||
globals file.
|
||||
12. Workstation age key and pull configuration installed, user timers and linger
|
||||
enabled, first pull verified, first drill passes.
|
||||
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).
|
||||
|
||||
+27
-1
@@ -7,7 +7,8 @@ set -euo pipefail
|
||||
# sudo deploy/activate /tmp/chesstrainer-20261109.tar.gz
|
||||
#
|
||||
# Environment overrides:
|
||||
# APP_USER, APP_ROOT, SERVICE, HEALTH_URL, KEEP_RELEASES, RELEASE_ID
|
||||
# APP_USER, APP_ROOT, SERVICE, HEALTH_URL, KEEP_RELEASES, RELEASE_ID,
|
||||
# BACKUP_BIN, SKIP_PRE_DEPLOY_BACKUP=1
|
||||
|
||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||
echo "activate: run with sudo" >&2
|
||||
@@ -26,6 +27,8 @@ SERVICE="${SERVICE:-chesstrainer}"
|
||||
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:4100/health}"
|
||||
KEEP_RELEASES="${KEEP_RELEASES:-5}"
|
||||
RELEASE_ID="${RELEASE_ID:-$(date -u +%Y%m%d%H%M%S)}"
|
||||
BACKUP_BIN="${BACKUP_BIN:-/usr/local/sbin/chesstrainer-backup}"
|
||||
SKIP_PRE_DEPLOY_BACKUP="${SKIP_PRE_DEPLOY_BACKUP:-0}"
|
||||
|
||||
if [[ ! "$RELEASE_ID" =~ ^[A-Za-z0-9._-]+$ ]]; then
|
||||
echo "activate: RELEASE_ID may contain only letters, digits, dot, underscore and dash" >&2
|
||||
@@ -53,6 +56,29 @@ install -d -o "$APP_USER" -g "$APP_USER" "$RELEASE_DIR"
|
||||
tar -xzf "$TARBALL" -C "$RELEASE_DIR"
|
||||
chown -R "$APP_USER:$APP_USER" "$RELEASE_DIR"
|
||||
|
||||
if [[ "$SKIP_PRE_DEPLOY_BACKUP" == "1" ]]; then
|
||||
echo "activate: SKIP_PRE_DEPLOY_BACKUP=1, not taking a pre-deploy dump"
|
||||
else
|
||||
backup_script="$BACKUP_BIN"
|
||||
if [[ ! -x "$backup_script" ]]; then
|
||||
backup_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/backup"
|
||||
fi
|
||||
|
||||
if [[ ! -x "$backup_script" ]]; then
|
||||
echo "activate: no backup script at $BACKUP_BIN or next to activate" >&2
|
||||
echo "activate: install deploy/backup or set SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Migrations run in ExecStartPre after this, so the dump must exist first.
|
||||
echo "activate: taking a pre-deploy dump"
|
||||
if ! BACKUP_TAG=predeploy LOCK_WAIT=120 "$backup_script"; then
|
||||
echo "activate: pre-deploy dump failed, aborting" >&2
|
||||
echo "activate: fix the backup or re-run with SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "activate: pointing current at $RELEASE_DIR"
|
||||
ln -sfn "$RELEASE_DIR" "$APP_ROOT/current"
|
||||
|
||||
|
||||
Executable
+266
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Dump, verify, encrypt, prune and report on the production database.
|
||||
#
|
||||
# Installed as /usr/local/sbin/chesstrainer-backup (root-owned 0755) and run by
|
||||
# chesstrainer-backup.timer. deploy/activate also calls it before migrations.
|
||||
# Do not run the copy under /opt/chesstrainer/src as root: that tree belongs to
|
||||
# the application user.
|
||||
#
|
||||
# sudo systemctl start chesstrainer-backup # daily run, as the timer does
|
||||
# sudo BACKUP_TAG=manual chesstrainer-backup # ad-hoc, pruned by age
|
||||
#
|
||||
# Configuration lives in /etc/chesstrainer/backup.env (root:root 0600). See
|
||||
# deploy/README.md §Backups. Every setting can also be passed as an environment
|
||||
# variable.
|
||||
#
|
||||
# Each run prints exactly one JSON line (backup.completed or backup.failed) so
|
||||
# journald, and #140's log shipping, can pick it up.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/backup.env}"
|
||||
if [[ -r "$ENV_FILE" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
fi
|
||||
|
||||
DB_CONTAINER="${DB_CONTAINER:-chesstrainer-db}"
|
||||
PG_USER="${PG_USER:-chesstrainer}"
|
||||
PG_DB="${PG_DB:-chesstrainer_prod}"
|
||||
BACKUP_DIR="${BACKUP_DIR:-/var/backups/chesstrainer}"
|
||||
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||
AGE_RECIPIENT="${AGE_RECIPIENT:-}"
|
||||
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
|
||||
SKIP_HEARTBEAT="${SKIP_HEARTBEAT:-0}"
|
||||
MIN_FREE_MB="${MIN_FREE_MB:-2048}"
|
||||
LOCAL_PLAINTEXT_DAYS="${LOCAL_PLAINTEXT_DAYS:-3}"
|
||||
LOCAL_ENCRYPTED_DAYS="${LOCAL_ENCRYPTED_DAYS:-14}"
|
||||
PREDEPLOY_KEEP="${PREDEPLOY_KEEP:-5}"
|
||||
BACKUP_TAG="${BACKUP_TAG:-daily}"
|
||||
LOCK_WAIT="${LOCK_WAIT:-0}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s","tag":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$BACKUP_TAG" "$extra"
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
local outcome="$1"
|
||||
|
||||
[[ "$SKIP_HEARTBEAT" == "1" ]] && return 0
|
||||
[[ -n "$HEALTHCHECK_URL" ]] || return 0
|
||||
|
||||
local url="${HEALTHCHECK_URL%/}"
|
||||
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||
|
||||
if ! curl --fail --silent --show-error \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--output /dev/null "$url"; then
|
||||
echo "backup: heartbeat ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
on_exit() {
|
||||
local status=$?
|
||||
|
||||
if ((status != 0)); then
|
||||
find "$BACKUP_DIR" -maxdepth 1 -name '*.partial' -delete 2>/dev/null || true
|
||||
log_event backup.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
heartbeat fail
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap on_exit EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||
fail "run as root"
|
||||
fi
|
||||
|
||||
[[ "$BACKUP_TAG" =~ ^[a-z0-9]+$ ]] || fail "BACKUP_TAG may contain only lowercase letters and digits"
|
||||
[[ "$MIN_FREE_MB" =~ ^[0-9]+$ ]] || fail "MIN_FREE_MB must be an integer"
|
||||
[[ "$LOCAL_PLAINTEXT_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_PLAINTEXT_DAYS must be an integer"
|
||||
[[ "$LOCAL_ENCRYPTED_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_ENCRYPTED_DAYS must be an integer"
|
||||
[[ "$PREDEPLOY_KEEP" =~ ^[0-9]+$ ]] || fail "PREDEPLOY_KEEP must be an integer"
|
||||
[[ "$LOCK_WAIT" =~ ^[0-9]+$ ]] || fail "LOCK_WAIT must be an integer"
|
||||
|
||||
[[ "$AGE_RECIPIENT" == age1* ]] || fail "AGE_RECIPIENT is not set to an age public key"
|
||||
|
||||
if [[ "$SKIP_HEARTBEAT" != "1" && -z "$HEALTHCHECK_URL" ]]; then
|
||||
fail "HEALTHCHECK_URL is not set (set SKIP_HEARTBEAT=1 to skip the ping)"
|
||||
fi
|
||||
|
||||
for cmd in docker flock curl age tar sha256sum; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
install -d -m 0711 -o root -g root "$BACKUP_DIR"
|
||||
install -d -m 0755 -o root -g root "$BACKUP_DIR/offsite"
|
||||
# 0711 on the vault lets the workstation user traverse to offsite/ without
|
||||
# being able to list the plaintext dumps.
|
||||
chmod 0711 "$BACKUP_DIR"
|
||||
chmod 0755 "$BACKUP_DIR/offsite"
|
||||
|
||||
exec 9>/run/lock/chesstrainer-backup.lock
|
||||
if ! flock -w "$LOCK_WAIT" 9; then
|
||||
if [[ "$LOCK_WAIT" == "0" ]]; then
|
||||
# Overlapping timer/manual runs are not failures; the other run reports.
|
||||
log_event backup.skipped ',"reason":"another backup is running"'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
fail "another backup is still running"
|
||||
fi
|
||||
|
||||
free_mb="$(df -Pm "$BACKUP_DIR" | awk 'NR == 2 { print $4 }')"
|
||||
[[ "$free_mb" =~ ^[0-9]+$ ]] || fail "cannot read free space for $BACKUP_DIR"
|
||||
if ((free_mb < MIN_FREE_MB)); then
|
||||
fail "only ${free_mb}MB free on $BACKUP_DIR, need ${MIN_FREE_MB}MB"
|
||||
fi
|
||||
|
||||
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
if [[ "$BACKUP_TAG" == "daily" ]]; then
|
||||
prefix="$timestamp"
|
||||
else
|
||||
prefix="$timestamp-$BACKUP_TAG"
|
||||
fi
|
||||
|
||||
dump="$BACKUP_DIR/$prefix.dump"
|
||||
globals="$BACKUP_DIR/$prefix.globals.sql"
|
||||
counts="$BACKUP_DIR/$prefix.counts"
|
||||
checksums="$BACKUP_DIR/$prefix.sha256"
|
||||
archive="$BACKUP_DIR/offsite/$prefix.tar.age"
|
||||
|
||||
# Row counts first: writes between this query and the dump can only push the
|
||||
# restored counts up, so the drill treats this file as a lower bound.
|
||||
read -r -d '' counts_sql <<'SQL' || true
|
||||
select 'users=' || count(*) from users
|
||||
union all select 'endgames=' || count(*) from endgames
|
||||
union all select 'attempts=' || count(*) from attempts;
|
||||
SQL
|
||||
|
||||
docker exec "$DB_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" \
|
||||
-At -v ON_ERROR_STOP=1 -c "$counts_sql" >"$counts.partial" ||
|
||||
fail "row count query failed"
|
||||
[[ -s "$counts.partial" ]] || fail "row count query returned nothing"
|
||||
|
||||
docker exec "$DB_CONTAINER" pg_dump -U "$PG_USER" -d "$PG_DB" -Fc \
|
||||
>"$dump.partial" || fail "pg_dump failed"
|
||||
[[ -s "$dump.partial" ]] || fail "pg_dump produced an empty file"
|
||||
|
||||
# pg_restore -l reads the archive header and table of contents. It needs the
|
||||
# Postgres client matching the server, so run it inside the container.
|
||||
docker exec -i "$DB_CONTAINER" pg_restore -l \
|
||||
<"$dump.partial" >/dev/null || fail "pg_restore -l rejected the dump"
|
||||
|
||||
docker exec "$DB_CONTAINER" pg_dumpall -U "$PG_USER" --globals-only \
|
||||
>"$globals.partial" || fail "pg_dumpall --globals-only failed"
|
||||
[[ -s "$globals.partial" ]] || fail "globals dump is empty"
|
||||
|
||||
# shellcheck disable=SC2086 # EXPECTED_ROLES is a space-separated list
|
||||
for role in $EXPECTED_ROLES; do
|
||||
grep -Eq "^CREATE ROLE \"?${role}\"?( |;)" "$globals.partial" ||
|
||||
fail "globals dump is missing role $role"
|
||||
done
|
||||
|
||||
# Promote only after every check passes, so a broken dump never looks finished.
|
||||
mv "$counts.partial" "$counts"
|
||||
mv "$dump.partial" "$dump"
|
||||
mv "$globals.partial" "$globals"
|
||||
|
||||
(
|
||||
cd "$BACKUP_DIR"
|
||||
sha256sum "${dump##*/}" "${globals##*/}" "${counts##*/}" >"${checksums##*/}"
|
||||
)
|
||||
|
||||
tar -C "$BACKUP_DIR" -cf - \
|
||||
"${dump##*/}" "${globals##*/}" "${counts##*/}" "${checksums##*/}" |
|
||||
age --recipient "$AGE_RECIPIENT" --output "$archive.partial" ||
|
||||
fail "encrypting the dump failed"
|
||||
|
||||
chmod 0644 "$archive.partial"
|
||||
mv "$archive.partial" "$archive"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retention
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
aged() {
|
||||
[[ -n "$(find "$1" -maxdepth 0 -mtime +"$2" -print -quit 2>/dev/null)" ]]
|
||||
}
|
||||
|
||||
remove_plaintext_set() {
|
||||
local prefix="$1"
|
||||
|
||||
rm -f -- \
|
||||
"$BACKUP_DIR/$prefix.dump" \
|
||||
"$BACKUP_DIR/$prefix.globals.sql" \
|
||||
"$BACKUP_DIR/$prefix.counts" \
|
||||
"$BACKUP_DIR/$prefix.sha256"
|
||||
}
|
||||
|
||||
prune_plaintext_by_age() {
|
||||
local dump base prefix
|
||||
|
||||
while IFS= read -r dump; do
|
||||
base="${dump##*/}"
|
||||
prefix="${base%%.*}"
|
||||
[[ "$base" == *-predeploy.dump ]] && continue
|
||||
|
||||
if aged "$dump" "$LOCAL_PLAINTEXT_DAYS"; then
|
||||
echo "backup: pruning $prefix (plaintext older than ${LOCAL_PLAINTEXT_DAYS}d)" >&2
|
||||
remove_plaintext_set "$prefix"
|
||||
fi
|
||||
done < <(find "$BACKUP_DIR" -maxdepth 1 -type f -name '*.dump')
|
||||
}
|
||||
|
||||
prune_predeploy_plaintext() {
|
||||
local -a dumps
|
||||
local i prefix
|
||||
|
||||
mapfile -t dumps < <(
|
||||
find "$BACKUP_DIR" -maxdepth 1 -type f -name '*-predeploy.dump' -printf '%f\n' | sort -r
|
||||
)
|
||||
|
||||
for ((i = PREDEPLOY_KEEP; i < ${#dumps[@]}; i++)); do
|
||||
prefix="${dumps[i]%%.*}"
|
||||
echo "backup: pruning $prefix (keeping last ${PREDEPLOY_KEEP} pre-deploy dumps)" >&2
|
||||
remove_plaintext_set "$prefix"
|
||||
done
|
||||
}
|
||||
|
||||
prune_encrypted() {
|
||||
local archive
|
||||
|
||||
while IFS= read -r archive; do
|
||||
echo "backup: pruning ${archive##*/} (encrypted older than ${LOCAL_ENCRYPTED_DAYS}d)" >&2
|
||||
rm -f -- "$archive"
|
||||
done < <(
|
||||
find "$BACKUP_DIR/offsite" -maxdepth 1 -type f -name '*.tar.age' -mtime +"$LOCAL_ENCRYPTED_DAYS"
|
||||
)
|
||||
}
|
||||
|
||||
prune_plaintext_by_age
|
||||
prune_predeploy_plaintext
|
||||
prune_encrypted
|
||||
|
||||
dump_bytes="$(stat -c %s "$dump")"
|
||||
archive_bytes="$(stat -c %s "$archive")"
|
||||
|
||||
log_event backup.completed ",\"dump\":\"$prefix\",\"dump_bytes\":$dump_bytes,\"offsite_bytes\":$archive_bytes,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
heartbeat ok
|
||||
@@ -0,0 +1,33 @@
|
||||
# /etc/chesstrainer/backup.env -- root:root, mode 0600.
|
||||
#
|
||||
# Sourced by /usr/local/sbin/chesstrainer-backup. Every value below shows the
|
||||
# default; only AGE_RECIPIENT and HEALTHCHECK_URL must be set. Keep secrets out
|
||||
# of the repo and out of world-readable files.
|
||||
|
||||
# age public key, generated on the workstation with `age-keygen`.
|
||||
# The private key never leaves the workstation.
|
||||
AGE_RECIPIENT=age1...
|
||||
|
||||
# healthchecks.io (or compatible) ping URL. The script pings it after a good
|
||||
# run and pings <url>/fail after a bad one. Set SKIP_HEARTBEAT=1 to run without
|
||||
# monitoring (testing only).
|
||||
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# Refuse to dump when the filesystem has less than this much free space.
|
||||
MIN_FREE_MB=2048
|
||||
|
||||
# Retention. Dumps and their globals/counts/checksum siblings disappear as a
|
||||
# set; only the encrypted archives in offsite/ live for the longer window.
|
||||
LOCAL_PLAINTEXT_DAYS=3
|
||||
LOCAL_ENCRYPTED_DAYS=14
|
||||
PREDEPLOY_KEEP=5
|
||||
|
||||
# Postgres coordinates. The container trusts local Unix-socket connections, so
|
||||
# no password belongs here.
|
||||
DB_CONTAINER=chesstrainer-db
|
||||
PG_USER=chesstrainer
|
||||
PG_DB=chesstrainer_prod
|
||||
BACKUP_DIR=/var/backups/chesstrainer
|
||||
|
||||
# Roles the globals dump must be able to recreate.
|
||||
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Report a failed Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority daemon.err --stderr backup.unit-failed: chesstrainer-backup.service failed, see journalctl -u chesstrainer-backup
|
||||
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
OnFailure=chesstrainer-backup-failure.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
ExecStart=/usr/local/sbin/chesstrainer-backup
|
||||
Nice=10
|
||||
IOSchedulingClass=idle
|
||||
TimeoutStartSec=10min
|
||||
SyslogIdentifier=chesstrainer-backup
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Daily Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:15:00 UTC
|
||||
RandomizedDelaySec=5m
|
||||
AccuracySec=1m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Refresh Cloudflare CIDRs for Caddy
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/docs/security.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
TimeoutStartSec=2min
|
||||
Nice=10
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Hourly refresh of Cloudflare CIDRs for Caddy
|
||||
|
||||
[Timer]
|
||||
OnCalendar=hourly
|
||||
RandomizedDelaySec=10m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-cloudflare-ranges.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
# Generated by deploy/update-cloudflare-ranges.sh.
|
||||
# Source: https://www.cloudflare.com/ips-v4 and /ips-v6
|
||||
remote_ip 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
|
||||
Executable
+359
@@ -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
|
||||
@@ -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 |
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Refresh Caddy's Cloudflare origin allowlist from Cloudflare's published
|
||||
# ranges. Called by chesstrainer-cloudflare-ranges.timer.
|
||||
#
|
||||
# The generated file is imported by /etc/caddy/Caddyfile:
|
||||
#
|
||||
# @cloudflare {
|
||||
# import cloudflare-ranges.caddy
|
||||
# }
|
||||
#
|
||||
# The script validates the candidate Caddyfile before reloading Caddy. If the
|
||||
# download or validation fails, the previous ranges stay in place.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CADDYFILE="${CADDYFILE:-/etc/caddy/Caddyfile}"
|
||||
RANGES_FILE="${RANGES_FILE:-/etc/caddy/cloudflare-ranges.caddy}"
|
||||
CADDY_BIN="${CADDY_BIN:-caddy}"
|
||||
RELOAD_CMD="${RELOAD_CMD:-systemctl reload caddy}"
|
||||
LOCK_FILE="${LOCK_FILE:-/run/lock/chesstrainer-cloudflare-ranges.lock}"
|
||||
|
||||
tmpdir="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmpdir"' EXIT
|
||||
|
||||
exec 9>"$LOCK_FILE"
|
||||
if ! flock -n 9; then
|
||||
echo "another Cloudflare range update is already running" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
fetch() {
|
||||
local url="$1"
|
||||
local output="$2"
|
||||
|
||||
curl --fail --silent --show-error --location \
|
||||
--proto '=https' \
|
||||
--retry 3 --retry-delay 2 --connect-timeout 10 \
|
||||
"$url" --output "$output"
|
||||
}
|
||||
|
||||
validate_download() {
|
||||
local file="$1"
|
||||
|
||||
[[ -s "$file" ]] || return 1
|
||||
|
||||
# One CIDR per line. Caddy performs the real validation; this prevents
|
||||
# obviously malformed or injected content from being written.
|
||||
if grep -Evq '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' "$file"; then
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
fetch "https://www.cloudflare.com/ips-v4" "$tmpdir/ips-v4"
|
||||
fetch "https://www.cloudflare.com/ips-v6" "$tmpdir/ips-v6"
|
||||
|
||||
validate_download "$tmpdir/ips-v4"
|
||||
validate_download "$tmpdir/ips-v6"
|
||||
|
||||
ranges="$(awk 'NF { printf "%s ", $0 }' "$tmpdir/ips-v4" "$tmpdir/ips-v6" | sed -e 's/[[:space:]]*$//')"
|
||||
|
||||
if [[ -z "$ranges" ]]; then
|
||||
echo "Cloudflare returned an empty CIDR list" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
candidate="$tmpdir/cloudflare-ranges.caddy"
|
||||
|
||||
{
|
||||
echo "# Generated by deploy/update-cloudflare-ranges.sh."
|
||||
echo "# Source: https://www.cloudflare.com/ips-v4 and /ips-v6"
|
||||
echo "remote_ip $ranges"
|
||||
} >"$candidate"
|
||||
|
||||
if cmp -s "$candidate" "$RANGES_FILE"; then
|
||||
echo "Cloudflare ranges are unchanged"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
install -d -m 0755 "$(dirname "$RANGES_FILE")"
|
||||
|
||||
backup="$tmpdir/previous-ranges.caddy"
|
||||
if [[ -e "$RANGES_FILE" ]]; then
|
||||
cp -a "$RANGES_FILE" "$backup"
|
||||
fi
|
||||
|
||||
install -m 0644 "$candidate" "$RANGES_FILE"
|
||||
|
||||
if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then
|
||||
echo "Caddy rejected the new Cloudflare ranges; restoring the previous file" >&2
|
||||
|
||||
if [[ -e "$backup" ]]; then
|
||||
install -m 0644 "$backup" "$RANGES_FILE"
|
||||
else
|
||||
rm -f "$RANGES_FILE"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
read -r -a reload_command <<<"$RELOAD_CMD"
|
||||
|
||||
if ! "${reload_command[@]}"; then
|
||||
echo "Caddy reload failed; restoring the previous ranges" >&2
|
||||
|
||||
if [[ -e "$backup" ]]; then
|
||||
install -m 0644 "$backup" "$RANGES_FILE"
|
||||
else
|
||||
rm -f "$RANGES_FILE"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Cloudflare ranges updated and Caddy reloaded"
|
||||
Executable
+190
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Restore the newest (or a named) archive into a throwaway Postgres container
|
||||
# and prove that the dump, the roles and the row counts all came back.
|
||||
#
|
||||
# backup-drill # newest archive in DEST
|
||||
# backup-drill 20261111T031500Z.tar.age
|
||||
#
|
||||
# Runs on the workstation. The production database is never contacted: the
|
||||
# container is created and destroyed by this script. Results are appended to
|
||||
# $DRILL_LOG (default $DEST/drills.log).
|
||||
#
|
||||
# Configuration: same file as backup-pull,
|
||||
# ~/.config/chesstrainer/backup-pull.env.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||
if [[ -r "$CONFIG" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$CONFIG"
|
||||
fi
|
||||
|
||||
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||
DRILL_IMAGE="${DRILL_IMAGE:-postgres:18.6}"
|
||||
DRILL_DB="${DRILL_DB:-chesstrainer_restore}"
|
||||
DRILL_LOG="${DRILL_LOG:-$DEST/drills.log}"
|
||||
DRILL_CONTAINER="${DRILL_CONTAINER:-chesstrainer-drill-$$}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
TMPDIR_DRILL=""
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
record() {
|
||||
local line="$1"
|
||||
|
||||
printf '%s\n' "$line"
|
||||
printf '%s\n' "$line" >>"$DRILL_LOG"
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local status=$?
|
||||
|
||||
docker rm -f "$DRILL_CONTAINER" >/dev/null 2>&1 || true
|
||||
|
||||
if [[ -n "$TMPDIR_DRILL" ]]; then
|
||||
rm -rf "$TMPDIR_DRILL"
|
||||
fi
|
||||
|
||||
if ((status != 0)); then
|
||||
if [[ -d "$DEST" ]]; then
|
||||
record "$(log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\"")"
|
||||
else
|
||||
log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
fi
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
[[ -d "$DEST" ]] || fail "archive directory does not exist: $DEST"
|
||||
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||
|
||||
for cmd in docker age tar sha256sum; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
if [[ $# -gt 0 ]]; then
|
||||
case "$1" in
|
||||
/*) archive="$1" ;;
|
||||
*) archive="$DEST/$1" ;;
|
||||
esac
|
||||
else
|
||||
archive="$(find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%p\n' | sort | tail -n 1)"
|
||||
[[ -n "$archive" ]] || fail "no archives in $DEST"
|
||||
fi
|
||||
|
||||
[[ -f "$archive" ]] || fail "archive not found: $archive"
|
||||
|
||||
name="${archive##*/}"
|
||||
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||
fail "unexpected archive name: $name"
|
||||
|
||||
prefix="${name%%.*}"
|
||||
TMPDIR_DRILL="$(mktemp -d "${TMPDIR:-/tmp}/chesstrainer-drill.XXXXXX")"
|
||||
|
||||
echo "backup-drill: decrypting $name" >&2
|
||||
age --decrypt --identity "$AGE_KEY" --output "$TMPDIR_DRILL/$prefix.tar" "$archive" ||
|
||||
fail "could not decrypt $name"
|
||||
|
||||
tar -xf "$TMPDIR_DRILL/$prefix.tar" -C "$TMPDIR_DRILL" ||
|
||||
fail "archive does not contain a readable tar file"
|
||||
|
||||
(
|
||||
cd "$TMPDIR_DRILL"
|
||||
sha256sum --check --strict --quiet "$prefix.sha256"
|
||||
) || fail "checksum verification failed for $name"
|
||||
|
||||
echo "backup-drill: starting $DRILL_IMAGE" >&2
|
||||
docker image inspect "$DRILL_IMAGE" >/dev/null 2>&1 ||
|
||||
docker pull "$DRILL_IMAGE" >/dev/null ||
|
||||
fail "could not pull $DRILL_IMAGE"
|
||||
|
||||
docker run --rm --detach \
|
||||
--name "$DRILL_CONTAINER" \
|
||||
--env POSTGRES_USER=chesstrainer \
|
||||
--env POSTGRES_PASSWORD=drill \
|
||||
--env POSTGRES_HOST_AUTH_METHOD=trust \
|
||||
"$DRILL_IMAGE" >/dev/null || fail "could not start the drill container"
|
||||
|
||||
ready=0
|
||||
for _ in $(seq 1 60); do
|
||||
if docker exec "$DRILL_CONTAINER" pg_isready -U chesstrainer -d postgres >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
((ready == 1)) || fail "postgres did not become ready"
|
||||
|
||||
# Recreating the cluster roles is half of disaster recovery. The scratch
|
||||
# cluster uses the same superuser name as production (`chesstrainer`), because
|
||||
# the globals dump ends with grants issued "GRANTED BY chesstrainer". The dump
|
||||
# always repeats the cluster's own superuser role, so "already exists" is
|
||||
# expected; anything else is a real failure.
|
||||
echo "backup-drill: applying globals" >&2
|
||||
docker exec -i "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||
-q -v ON_ERROR_STOP=0 -f - \
|
||||
<"$TMPDIR_DRILL/$prefix.globals.sql" >/dev/null 2>"$TMPDIR_DRILL/globals.err" ||
|
||||
fail "applying the globals dump failed"
|
||||
|
||||
globals_errors="$(grep -v 'already exists' "$TMPDIR_DRILL/globals.err" | sed '/^$/d' || true)"
|
||||
if [[ -n "$globals_errors" ]]; then
|
||||
fail "globals restore reported errors: $(printf '%s' "$globals_errors" | head -n 1)"
|
||||
fi
|
||||
|
||||
for role in $EXPECTED_ROLES; do
|
||||
found="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres -Atc \
|
||||
"select 1 from pg_roles where rolname = '$role'")"
|
||||
[[ "$found" == "1" ]] || fail "globals did not recreate role $role"
|
||||
done
|
||||
|
||||
owner="${EXPECTED_ROLES%% *}"
|
||||
|
||||
docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||
-q -v ON_ERROR_STOP=1 -c "create database $DRILL_DB owner $owner" ||
|
||||
fail "could not create $DRILL_DB"
|
||||
|
||||
echo "backup-drill: restoring into $DRILL_DB" >&2
|
||||
docker exec -i "$DRILL_CONTAINER" pg_restore -U chesstrainer -d "$DRILL_DB" \
|
||||
--single-transaction --exit-on-error <"$TMPDIR_DRILL/$prefix.dump" ||
|
||||
fail "pg_restore failed"
|
||||
|
||||
restored_counts=""
|
||||
for table in users endgames attempts; do
|
||||
expected="$(awk -F= -v key="$table" '$1 == key { print $2 }' "$TMPDIR_DRILL/$prefix.counts")"
|
||||
[[ "$expected" =~ ^[0-9]+$ ]] || fail "counts file has no value for $table"
|
||||
|
||||
actual="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d "$DRILL_DB" -Atc \
|
||||
"select count(*) from $table")"
|
||||
[[ "$actual" =~ ^[0-9]+$ ]] || fail "could not count $table"
|
||||
|
||||
if ((actual < expected)); then
|
||||
fail "restored $table=$actual is below the recorded $expected"
|
||||
fi
|
||||
|
||||
echo "backup-drill: $table restored=$actual recorded=$expected drift=$((actual - expected))" >&2
|
||||
restored_counts+="${restored_counts:+,}$table=$actual"
|
||||
done
|
||||
|
||||
record "$(log_event drill.completed ",\"archive\":\"$name\",\"result\":\"pass\",\"counts\":\"$restored_counts\",\"duration_s\":$((SECONDS - START_SECONDS))")"
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Pull the encrypted database archives from the VPS, verify them end to end,
|
||||
# and apply the 7 daily / 4 weekly / 6 monthly retention policy.
|
||||
#
|
||||
# Runs on the workstation, never on the server. Install as
|
||||
# ~/.local/bin/chesstrainer-backup-pull and enable
|
||||
# chesstrainer-backup-pull.timer as a user unit.
|
||||
#
|
||||
# Configuration: ~/.config/chesstrainer/backup-pull.env (0600). See
|
||||
# deploy/README.md §Backups.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||
if [[ -r "$CONFIG" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$CONFIG"
|
||||
fi
|
||||
|
||||
VPS_HOST="${VPS_HOST:-}"
|
||||
REMOTE_DIR="${REMOTE_DIR:-/var/backups/chesstrainer/offsite}"
|
||||
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||
MAX_STALENESS_HOURS="${MAX_STALENESS_HOURS:-48}"
|
||||
KEEP_DAILY_DAYS="${KEEP_DAILY_DAYS:-7}"
|
||||
KEEP_WEEKLY_WEEKS="${KEEP_WEEKLY_WEEKS:-4}"
|
||||
KEEP_MONTHLY_MONTHS="${KEEP_MONTHLY_MONTHS:-6}"
|
||||
PULL_HEALTHCHECK_URL="${PULL_HEALTHCHECK_URL:-}"
|
||||
SSH_OPTIONS="${SSH_OPTIONS:--o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15}"
|
||||
RSYNC_ATTEMPTS="${RSYNC_ATTEMPTS:-3}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
VERIFIED=0
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
local outcome="$1"
|
||||
|
||||
[[ -n "$PULL_HEALTHCHECK_URL" ]] || return 0
|
||||
|
||||
local url="${PULL_HEALTHCHECK_URL%/}"
|
||||
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||
|
||||
if ! curl --fail --silent --show-error \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--output /dev/null "$url"; then
|
||||
echo "backup-pull: heartbeat ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local status=$?
|
||||
|
||||
if [[ -d "$DEST" ]]; then
|
||||
find "$DEST" -maxdepth 1 -name '.verify.*' -type d -exec rm -rf {} + 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if ((status != 0)); then
|
||||
log_event pull.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
heartbeat fail
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
[[ -n "$VPS_HOST" ]] || fail "VPS_HOST is not set"
|
||||
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||
[[ "$MAX_STALENESS_HOURS" =~ ^[0-9]+$ ]] || fail "MAX_STALENESS_HOURS must be an integer"
|
||||
[[ "$KEEP_DAILY_DAYS" =~ ^[0-9]+$ ]] || fail "KEEP_DAILY_DAYS must be an integer"
|
||||
[[ "$KEEP_WEEKLY_WEEKS" =~ ^[0-9]+$ ]] || fail "KEEP_WEEKLY_WEEKS must be an integer"
|
||||
[[ "$KEEP_MONTHLY_MONTHS" =~ ^[0-9]+$ ]] || fail "KEEP_MONTHLY_MONTHS must be an integer"
|
||||
[[ "$RSYNC_ATTEMPTS" =~ ^[0-9]+$ ]] || fail "RSYNC_ATTEMPTS must be an integer"
|
||||
|
||||
for cmd in rsync ssh age tar sha256sum curl flock; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
# Never create DEST on the root filesystem when the backup disk is unmounted.
|
||||
[[ -d "$(dirname "$DEST")" ]] ||
|
||||
fail "parent directory of $DEST does not exist (is the backup disk mounted?)"
|
||||
|
||||
install -d -m 0700 "$DEST"
|
||||
install -d -m 0700 "$DEST/.verified"
|
||||
|
||||
exec 9>"$DEST/.pull.lock"
|
||||
if ! flock -n 9; then
|
||||
# A manual run overlapping the timer is not an error; the other run reports.
|
||||
log_event pull.skipped ',"reason":"another pull is running"'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
archive_epoch() {
|
||||
local name="$1"
|
||||
local ts="${name:0:16}"
|
||||
|
||||
[[ "$ts" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || return 1
|
||||
|
||||
date -u -d "${ts:0:4}-${ts:4:2}-${ts:6:2} ${ts:9:2}:${ts:11:2}:${ts:13:2}Z" +%s
|
||||
}
|
||||
|
||||
verify_archive() {
|
||||
local archive="$1"
|
||||
local name="${archive##*/}"
|
||||
local marker="$DEST/.verified/$name"
|
||||
local sum tmp
|
||||
|
||||
sum="$(sha256sum "$archive" | awk '{ print $1 }')"
|
||||
|
||||
if [[ -f "$marker" && "$(cat "$marker")" == "$sum" ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
tmp="$(mktemp -d "$DEST/.verify.XXXXXX")"
|
||||
|
||||
if ! age --decrypt --identity "$AGE_KEY" --output "$tmp/$name.tar" "$archive"; then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name failed to decrypt" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! tar -xf "$tmp/$name.tar" -C "$tmp"; then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name did not contain a readable tar archive" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! (cd "$tmp" && sha256sum --check --strict --quiet ./*.sha256); then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name failed its checksum verification" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
rm -rf "$tmp"
|
||||
|
||||
printf '%s\n' "$sum" >"$marker.tmp"
|
||||
mv "$marker.tmp" "$marker"
|
||||
|
||||
VERIFIED=$((VERIFIED + 1))
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Copy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
attempt=1
|
||||
while true; do
|
||||
if rsync --archive --partial --compress --timeout=120 \
|
||||
--include='*.tar.age' --exclude='*' \
|
||||
--rsh "ssh $SSH_OPTIONS" \
|
||||
"$VPS_HOST:$REMOTE_DIR/" "$DEST/"; then
|
||||
break
|
||||
fi
|
||||
|
||||
if ((attempt >= RSYNC_ATTEMPTS)); then
|
||||
fail "rsync from $VPS_HOST failed after $attempt attempts"
|
||||
fi
|
||||
|
||||
echo "backup-pull: rsync attempt $attempt failed, retrying" >&2
|
||||
attempt=$((attempt + 1))
|
||||
sleep 20
|
||||
done
|
||||
|
||||
mapfile -t archives < <(
|
||||
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort
|
||||
)
|
||||
|
||||
((${#archives[@]} > 0)) || fail "no archives in $DEST after the pull"
|
||||
|
||||
for name in "${archives[@]}"; do
|
||||
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||
fail "unexpected file in $DEST: $name"
|
||||
done
|
||||
|
||||
newest="${archives[${#archives[@]} - 1]}"
|
||||
newest_epoch="$(archive_epoch "$newest")" || fail "cannot parse a timestamp from $newest"
|
||||
age_seconds=$(($(date -u +%s) - newest_epoch))
|
||||
|
||||
if ((age_seconds > MAX_STALENESS_HOURS * 3600)); then
|
||||
fail "newest archive $newest is $((age_seconds / 3600))h old (limit ${MAX_STALENESS_HOURS}h): VPS backups may have stopped"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Verify every archive once; unchanged ciphertext is only re-hashed.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
for name in "${archives[@]}"; do
|
||||
verify_archive "$DEST/$name" || fail "$name failed verification"
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retention: 7 daily, then one per ISO week for 4 weeks, then one per calendar
|
||||
# month for 6 months. Archives outside all three windows are deleted.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
now="$(date -u +%s)"
|
||||
pruned=0
|
||||
declare -A kept_week=()
|
||||
declare -A kept_month=()
|
||||
|
||||
mapfile -t newest_first < <(
|
||||
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort -r
|
||||
)
|
||||
|
||||
for name in "${newest_first[@]}"; do
|
||||
epoch="$(archive_epoch "$name")" || continue
|
||||
age_days=$(((now - epoch) / 86400))
|
||||
|
||||
if ((age_days < KEEP_DAILY_DAYS)); then
|
||||
continue
|
||||
fi
|
||||
|
||||
week="$(date -u -d "@$epoch" +%G-W%V)"
|
||||
if ((age_days < KEEP_WEEKLY_WEEKS * 7)) && [[ -z "${kept_week[$week]:-}" ]]; then
|
||||
kept_week[$week]=1
|
||||
continue
|
||||
fi
|
||||
|
||||
month="$(date -u -d "@$epoch" +%Y-%m)"
|
||||
if ((age_days < KEEP_MONTHLY_MONTHS * 31)) && [[ -z "${kept_month[$month]:-}" ]]; then
|
||||
kept_month[$month]=1
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "backup-pull: pruning $name" >&2
|
||||
rm -f -- "$DEST/$name" "$DEST/.verified/$name"
|
||||
pruned=$((pruned + 1))
|
||||
done
|
||||
|
||||
log_event pull.completed ",\"newest\":\"$newest\",\"archives\":$(( ${#archives[@]} - pruned )),\"verified\":$VERIFIED,\"pruned\":$pruned,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
heartbeat ok
|
||||
@@ -0,0 +1,37 @@
|
||||
# ~/.config/chesstrainer/backup-pull.env -- mode 0600.
|
||||
#
|
||||
# Sourced by ~/.local/bin/chesstrainer-backup-pull. Values below are the
|
||||
# defaults; VPS_HOST and AGE_KEY must be right. Quote anything containing
|
||||
# spaces.
|
||||
|
||||
VPS_HOST=owen@159.69.21.225
|
||||
REMOTE_DIR=/var/backups/chesstrainer/offsite
|
||||
DEST="/mnt/Mint Data/chesstrainer-backups"
|
||||
|
||||
# Private half of the age key. Back this file up somewhere safe: without it
|
||||
# every archive is unreadable.
|
||||
AGE_KEY="$HOME/.config/chesstrainer/age.key"
|
||||
|
||||
# Fail the pull when the newest archive from the VPS is older than this, which
|
||||
# means the VPS backup timer has stopped.
|
||||
MAX_STALENESS_HOURS=48
|
||||
|
||||
# Keep every archive from the last 7 days, then one per ISO week for 4 weeks,
|
||||
# then one per calendar month for 6 months.
|
||||
KEEP_DAILY_DAYS=7
|
||||
KEEP_WEEKLY_WEEKS=4
|
||||
KEEP_MONTHLY_MONTHS=6
|
||||
|
||||
# Restore drill. It runs in a throwaway container matching the production
|
||||
# Postgres major and appends results to DRILL_LOG.
|
||||
# DRILL_IMAGE=postgres:18.6
|
||||
# DRILL_DB=chesstrainer_restore
|
||||
# DRILL_LOG="$DEST/drills.log"
|
||||
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||
|
||||
# Optional second heartbeat check with a long period (for example 72h), so you
|
||||
# hear about it when the workstation stops pulling. Leave empty to disable.
|
||||
# PULL_HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# Extra ssh options, space separated.
|
||||
# SSH_OPTIONS="-o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15"
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Report a failed Inner Square Chess backup unit
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority user.err --stderr backup.unit-failed: %i failed, see journalctl --user -u %i
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Monthly restore drill for Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
OnFailure=chesstrainer-backup-alert@%N.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/bin/chesstrainer-backup-drill
|
||||
WorkingDirectory=%h
|
||||
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Nice=10
|
||||
TimeoutStartSec=20min
|
||||
SyslogIdentifier=chesstrainer-backup-drill
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Monthly restore drill for Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-01 09:00:00
|
||||
RandomizedDelaySec=30m
|
||||
AccuracySec=5m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup-drill.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=Pull encrypted Inner Square Chess backups from the VPS
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
OnFailure=chesstrainer-backup-alert@%N.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/bin/chesstrainer-backup-pull
|
||||
WorkingDirectory=%h
|
||||
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Nice=10
|
||||
TimeoutStartSec=15min
|
||||
SyslogIdentifier=chesstrainer-backup-pull
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Daily pull of encrypted Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 12:00:00
|
||||
OnBootSec=10m
|
||||
RandomizedDelaySec=10m
|
||||
AccuracySec=1m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup-pull.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -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.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Asset bundle sizes
|
||||
|
||||
What the browser downloads, measured rather than guessed. Numbers below are
|
||||
from the last production build (`mix assets.deploy`, minified and digested) and
|
||||
were read with `mix assets.sizes`.
|
||||
|
||||
Re-measure after any asset change:
|
||||
|
||||
```sh
|
||||
mix assets.deploy
|
||||
mix assets.sizes
|
||||
```
|
||||
|
||||
`mix assets.sizes` prints raw, gzip and brotli sizes for every built JS and CSS
|
||||
file. Brotli shows as `-` when the `brotli` CLI is not installed.
|
||||
|
||||
## Current bundles
|
||||
|
||||
| File | Raw | Gzip |
|
||||
| --- | ---: | ---: |
|
||||
| `assets/js/app.js` (LiveView entry) | 219.7 KB | 69.2 KB |
|
||||
| `assets/js/marketing.js` (controller pages) | 4.8 KB | 1.9 KB |
|
||||
| `assets/css/app.css` | 94.2 KB | 17.3 KB |
|
||||
|
||||
Cached font files, served only when used: DM Sans variable 62.5 KB, DM Serif
|
||||
Display 24.5 KB, DM Serif Display italic 24.4 KB, DM Sans italic 14.6 KB
|
||||
(woff2, already compressed).
|
||||
|
||||
## What is in each bundle
|
||||
|
||||
`app.js` is a single entry loaded by every LiveView page. It contains:
|
||||
|
||||
| Part | Raw | Gzip |
|
||||
| --- | ---: | ---: |
|
||||
| `phoenix`, `phoenix_live_view`, `phoenix_html` | — | ~30 KB |
|
||||
| `chessground` (`dist/chessground.min.js`) | 30.0 KB | 11.0 KB |
|
||||
| `chess.js` (`dist/esm/chess.js`) | 107.1 KB | 23.9 KB |
|
||||
| `topbar` | 4.3 KB | 1.5 KB |
|
||||
| `nav`, `analytics`, hooks | ~8 KB | ~3 KB |
|
||||
|
||||
The library figures are the packages' own builds; esbuild's minification and
|
||||
tree shaking mean the bundle total is smaller than the naive sum.
|
||||
|
||||
`marketing.js` is deliberately tiny: `phoenix_html`, the nav toggle and the
|
||||
cookieless analytics loader. It has no LiveView, socket, hooks or topbar.
|
||||
Controller pages (landing page, legal pages, 404) load it instead of `app.js`.
|
||||
|
||||
`app.css` is one Tailwind build for the whole site, including the three
|
||||
chessground stylesheets (`chessground.base.css` 3.3 KB, `chessground.brown.css`
|
||||
2.8 KB, `chessground.cburnett.css` 11.5 KB raw, ~4.7 KB gzipped together).
|
||||
|
||||
## Findings
|
||||
|
||||
1. **Board code is about half of `app.js` and most pages do not use it.**
|
||||
chessground and chess.js are ~35 KB of the 69 KB gzip payload. They are
|
||||
needed only by pages that render `ChessBoard`: guest training, play, review.
|
||||
Profile, settings, the endgame list and every admin screen pay for them and
|
||||
never instantiate a board.
|
||||
2. **The marketing/public split is already right.** Public pages do not load
|
||||
the LiveView runtime at all.
|
||||
3. **Board CSS is in the global stylesheet.** ~4.7 KB gzipped of chess piece
|
||||
and board styling reaches every page, including the landing page.
|
||||
4. **Stale digested bundles accumulate.** `priv/static/assets` currently holds
|
||||
three generations of `app-*.js` and `app-*.css`. They are not linked but do
|
||||
bloat the release. `mix phx.digest.clean --age 0` (or deploying from a clean
|
||||
build) removes them.
|
||||
|
||||
## Recommendation (not applied)
|
||||
|
||||
Split the board libraries out of the LiveView entry:
|
||||
|
||||
- Load `chessground` and `chess.js` with a dynamic `import()` inside
|
||||
`assets/js/hooks/chessBoard.js` and build with esbuild `--splitting
|
||||
--format=esm`. Pages without a board then never fetch the chunk; board pages
|
||||
fetch it once, in parallel with the hook mounting.
|
||||
- Expected result: `app.js` drops from ~69 KB to ~35 KB gzip on most
|
||||
authenticated pages, with a separate ~35 KB board chunk fetched only where
|
||||
needed.
|
||||
- Move the chessground stylesheets into the board chunk's CSS (or a second CSS
|
||||
entry loaded only on board pages) to take ~4.7 KB off every page.
|
||||
- Set a budget in CI once the split lands: `app.js` ≤ 40 KB gzip, board chunk
|
||||
≤ 40 KB gzip, `marketing.js` ≤ 2 KB gzip, `app.css` ≤ 20 KB gzip.
|
||||
|
||||
No build configuration was changed as part of this measurement.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -115,6 +115,21 @@ Prefer identifiers such as `user_id` or `table` over emails, and never log
|
||||
params or request bodies. The formatter is a safety net, not a licence to log
|
||||
PII.
|
||||
|
||||
## Authentication events
|
||||
|
||||
`ChesstrainerWeb.UserSessionController` emits warning lines consumed by
|
||||
host-level tooling such as fail2ban:
|
||||
|
||||
| Message | Metadata | Meaning |
|
||||
|---|---|---|
|
||||
| `auth.login.failed` | `reason` (`invalid_credentials` / `unconfirmed`), `ip` | A password login failed. |
|
||||
| `auth.login.throttled` | `reason` (`ip` / `login`), `ip` | The address or login bucket blocked the attempt before bcrypt. |
|
||||
|
||||
`ip` is a boot-scoped HMAC of the client address, not the address itself. The
|
||||
raw login identifier and password are never included. The login throttle is
|
||||
configured in `config/config.exs` and defaults to five failures per login and
|
||||
ten per address in a fifteen-minute window.
|
||||
|
||||
## Querying logs
|
||||
|
||||
`journalctl` prints the raw line only with `-o cat`; the default output wraps it
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# Login and edge security
|
||||
|
||||
The login surface is protected in layers. The application throttle is the
|
||||
primary control; Cloudflare is the edge backstop for volume. There is no
|
||||
origin-level fail2ban for HTTP logins, because it would require storing raw IP
|
||||
addresses and would ban Cloudflare edge addresses on this deployment.
|
||||
|
||||
## Current production configuration
|
||||
|
||||
- Caddy accepts only Cloudflare's published ranges and forwards
|
||||
`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 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.
|
||||
|
||||
The short Cloudflare block is rate smoothing, not a credential lockout. The
|
||||
application's 5-per-login and 10-per-address failures in a 15-minute window are
|
||||
the real control.
|
||||
|
||||
## 1. Application login throttle
|
||||
|
||||
`ChesstrainerWeb.LoginThrottle` counts failures in two buckets:
|
||||
|
||||
| Bucket | Limit | Window |
|
||||
|---|---|---|
|
||||
| Normalised login (email or username) | 5 failures | 15 minutes |
|
||||
| Client address | 10 failures | 15 minutes |
|
||||
|
||||
Blocked attempts are rejected before the database lookup and bcrypt, so they do
|
||||
not consume password-hashing CPU. A successful login clears the login bucket
|
||||
only, keeping the address bucket in place so one address cannot spray many
|
||||
accounts.
|
||||
|
||||
The bucket keys are boot-scoped HMACs. Raw addresses and raw login identifiers
|
||||
are never stored in ETS or written to the application logs. The login form
|
||||
returns the same generic error for unknown accounts, bad passwords and
|
||||
unconfirmed accounts.
|
||||
|
||||
Configured in `config/config.exs`:
|
||||
|
||||
```elixir
|
||||
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||
window_ms: :timer.minutes(15),
|
||||
max_per_login: 5,
|
||||
max_per_ip: 10,
|
||||
confirmation_cooldown_ms: :timer.minutes(15)
|
||||
```
|
||||
|
||||
`auth.login.failed` and `auth.login.throttled` are documented in
|
||||
`docs/logging.md`.
|
||||
|
||||
## 2. Real client IPs behind Cloudflare and Caddy
|
||||
|
||||
The production chain is:
|
||||
|
||||
```text
|
||||
Internet
|
||||
└─ Cloudflare
|
||||
└─ Caddy :443
|
||||
└─ Phoenix 127.0.0.1:4100
|
||||
```
|
||||
|
||||
Caddy ignores incoming `X-Forwarded-*` values by default and replaces them with
|
||||
the immediate peer address. Behind Cloudflare that peer is a Cloudflare edge
|
||||
node, so without configuration the app would throttle whole Cloudflare POPs
|
||||
rather than individual visitors.
|
||||
|
||||
`deploy/Caddyfile` fixes this by:
|
||||
|
||||
1. accepting only Cloudflare's published ranges, and
|
||||
2. setting `X-Forwarded-For` from Cloudflare's single-value `CF-Connecting-IP`
|
||||
header.
|
||||
|
||||
That keeps `TRUST_FORWARDED_FOR=true` safe: direct clients cannot reach the app
|
||||
through Caddy, so they cannot forge the header.
|
||||
|
||||
`deploy/Caddyfile` imports `cloudflare-ranges.caddy`. The file is generated by
|
||||
`deploy/update-cloudflare-ranges.sh`; do not edit it by hand.
|
||||
|
||||
The script is run hourly by `chesstrainer-cloudflare-ranges.timer`. It:
|
||||
|
||||
- downloads <https://www.cloudflare.com/ips-v4> and
|
||||
<https://www.cloudflare.com/ips-v6>,
|
||||
- rejects empty or malformed responses,
|
||||
- validates the candidate Caddyfile,
|
||||
- reloads Caddy only when the ranges changed.
|
||||
|
||||
If the download, validation or Caddy reload fails, the previous ranges stay in
|
||||
place.
|
||||
|
||||
Install and run it:
|
||||
|
||||
```sh
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||
/etc/caddy/cloudflare-ranges.caddy
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||
```
|
||||
|
||||
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||
The timer only uses the installed copies.
|
||||
|
||||
Check the timer and last run:
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||
systemctl status chesstrainer-cloudflare-ranges.service
|
||||
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||
```
|
||||
|
||||
Apply the site block by hand on the shared Caddy host, then validate and
|
||||
reload:
|
||||
|
||||
```sh
|
||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
sudo systemctl reload caddy
|
||||
```
|
||||
|
||||
Direct requests to the origin with a spoofed `CF-Connecting-IP` must receive
|
||||
`403 Access Denied`; only Cloudflare's ranges should reach the Phoenix app. A
|
||||
host firewall allowlist for Cloudflare on ports 80 and 443 is a useful
|
||||
defence-in-depth addition.
|
||||
|
||||
## 3. Cloudflare edge rate limiting
|
||||
|
||||
This is for connection and request floods, not credential guessing. The
|
||||
application already stops password attempts cheaply.
|
||||
|
||||
The production rule is the free-plan version:
|
||||
|
||||
| Setting | Value |
|
||||
|---|---|
|
||||
| Name | Login POST flood |
|
||||
| Expression | `(http.request.method eq "POST" and http.request.uri.path in {"/admin/log-in" "/users/log-in"})` |
|
||||
| Characteristic | IP |
|
||||
| Period | 10 seconds |
|
||||
| Requests | 10 |
|
||||
| Action | Block |
|
||||
| Duration | 10 seconds |
|
||||
|
||||
Because the free plan only offers a 10-second period and a 10-second block, this
|
||||
is a burst limiter rather than a lasting ban. An attacker can retry after ten
|
||||
seconds, but the application still stops that login after five failures and that
|
||||
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 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
|
||||
|
||||
`/users/register` is a LiveView. The form submit is a LiveView event sent over
|
||||
the shared `/live/websocket` connection, not a `POST /users/register` request.
|
||||
Cloudflare therefore cannot count account creations with a rule on the
|
||||
registration path.
|
||||
|
||||
A Cloudflare rule on `GET /users/register` only limits page opens; a bot can
|
||||
open one page and submit many registrations over the socket. If registration
|
||||
spam becomes a problem, add an application-level registration throttle keyed by
|
||||
`ChesstrainerWeb.ClientAddress.from_socket/1`, and/or add Cloudflare Turnstile
|
||||
to the form.
|
||||
|
||||
While `PRELAUNCH=true`, registration is blocked entirely by the prelaunch plug
|
||||
and LiveView mount redirect.
|
||||
|
||||
## 4. Why not fail2ban for HTTP?
|
||||
|
||||
fail2ban needs the raw client address to build a firewall rule. The application
|
||||
deliberately logs only a boot-scoped HMAC, and this deployment sits behind
|
||||
Cloudflare. Banning the address that reaches the origin would ban Cloudflare
|
||||
edges, not attackers.
|
||||
|
||||
fail2ban remains useful for services that terminate connections directly on the
|
||||
VPS, such as SSH. It is not part of the HTTP login defence.
|
||||
@@ -4,11 +4,14 @@ defmodule Chesstrainer.Accounts do
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
require Logger
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
alias Chesstrainer.Accounts.{User, UserToken, UserNotifier}
|
||||
alias Chesstrainer.Accounts.{Policy, Role, Scope, User, UserToken, UserNotifier}
|
||||
alias Chesstrainer.MailingList
|
||||
|
||||
@admin_users_per_page 25
|
||||
|
||||
## Database getters
|
||||
|
||||
@doc """
|
||||
@@ -165,6 +168,320 @@ defmodule Chesstrainer.Accounts do
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's subscription plan.
|
||||
|
||||
Plans are programmatic values; registration never casts `plan`, so a user
|
||||
cannot upgrade themselves.
|
||||
"""
|
||||
def update_user_plan(%User{} = user, plan) do
|
||||
user
|
||||
|> User.plan_changeset(%{plan: plan})
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
## Admin user management
|
||||
|
||||
@doc """
|
||||
Returns a page of users the scope may administer, newest first.
|
||||
|
||||
Options:
|
||||
|
||||
* `:search` - case-insensitive match on email or username
|
||||
* `:page` - 1-based page number (defaults to 1)
|
||||
* `:per_page` - page size (defaults to 25, capped at 100)
|
||||
|
||||
Admins only see members and moderators; super admins see every role.
|
||||
Returns `{:error, :unauthorized}` when the scope lacks user management.
|
||||
"""
|
||||
def list_users_for_admin(scope, opts \\ []) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
page = normalize_page(Keyword.get(opts, :page, 1))
|
||||
per_page = normalize_per_page(Keyword.get(opts, :per_page, @admin_users_per_page))
|
||||
offset = (page - 1) * per_page
|
||||
|
||||
users =
|
||||
scope
|
||||
|> admin_users_query(opts)
|
||||
|> order_by([u], desc: u.inserted_at, desc: u.id)
|
||||
|> limit(^per_page)
|
||||
|> offset(^offset)
|
||||
|> Repo.all()
|
||||
|
||||
{:ok, users}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Counts the users visible to the scope, using the same filters as
|
||||
`list_users_for_admin/2`.
|
||||
"""
|
||||
def count_users_for_admin(scope, opts \\ []) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
count =
|
||||
scope
|
||||
|> admin_users_query(opts)
|
||||
|> select([u], count(u.id))
|
||||
|> Repo.one()
|
||||
|
||||
{:ok, count}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Fetches a user for the admin detail page.
|
||||
|
||||
Returns `{:error, :unauthorized}` when the scope may not view the target and
|
||||
`{:error, :not_found}` for an unknown id.
|
||||
"""
|
||||
def get_user_for_admin(scope, id) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
case fetch_user(id) do
|
||||
nil ->
|
||||
{:error, :not_found}
|
||||
|
||||
%User{} = user ->
|
||||
if Policy.can_view_user?(scope, user) do
|
||||
{:ok, user}
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Ecto.Changeset{}` for the admin-editable fields (role and plan).
|
||||
"""
|
||||
def change_user_as_admin(%User{} = user, attrs \\ %{}) do
|
||||
User.admin_changeset(user, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's role and plan after enforcing the admin capability matrix.
|
||||
|
||||
The last-super-admin check runs inside the update transaction with a row lock,
|
||||
so concurrent demotions cannot remove the final super admin.
|
||||
|
||||
Returns `{:error, :unauthorized}`, `{:error, :own_role}`,
|
||||
`{:error, :last_super_admin}` or `{:error, %Ecto.Changeset{}}` instead of
|
||||
raising.
|
||||
"""
|
||||
def update_user_as_admin(scope, %User{} = user, attrs) do
|
||||
changeset = User.admin_changeset(user, attrs)
|
||||
role_change = Ecto.Changeset.get_change(changeset, :role)
|
||||
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_not_own_role_change(scope, user, role_change),
|
||||
:ok <- ensure_can_manage_user(scope, user),
|
||||
:ok <- ensure_can_assign_role(scope, role_change),
|
||||
{:ok, updated} <- persist_user_changes(user, changeset) do
|
||||
log_user_update(scope, user, changeset)
|
||||
{:ok, updated}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates an invitation and emails the recipient a link to choose a password.
|
||||
|
||||
The account is confirmed but has no password until the invitee follows the
|
||||
link. `invite_url_fun` receives the encoded token and must return a URL.
|
||||
"""
|
||||
def invite_user_as_admin(scope, attrs, invite_url_fun)
|
||||
when is_function(invite_url_fun, 1) do
|
||||
role = normalize_role(role_param(attrs) || :member)
|
||||
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_assign_role(scope, role) do
|
||||
changeset =
|
||||
%User{}
|
||||
|> User.invite_changeset(attrs)
|
||||
|> User.admin_changeset(attrs)
|
||||
|
||||
case Repo.insert(changeset) do
|
||||
{:ok, user} ->
|
||||
Logger.info("admin.user.invited",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id,
|
||||
fields: [:invite]
|
||||
)
|
||||
|
||||
case deliver_invite_instructions(user, invite_url_fun) do
|
||||
{:ok, _email} -> {:ok, user}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
|
||||
{:error, changeset} ->
|
||||
{:error, changeset}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sends a password-reset email on behalf of an administrator.
|
||||
|
||||
Uses the same policy as the editable user screen: an admin cannot trigger a
|
||||
reset for another admin or a super admin.
|
||||
"""
|
||||
def send_user_reset_password_instructions_as_admin(scope, %User{} = user, reset_url_fun)
|
||||
when is_function(reset_url_fun, 1) do
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_manage_user(scope, user) do
|
||||
case deliver_user_reset_password_instructions(user, reset_url_fun) do
|
||||
{:ok, email} ->
|
||||
Logger.info("admin.user.password_reset_sent",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id
|
||||
)
|
||||
|
||||
{:ok, email}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Resends the account-confirmation email on behalf of an administrator.
|
||||
"""
|
||||
def resend_user_confirmation_instructions_as_admin(scope, %User{} = user, confirmation_url_fun)
|
||||
when is_function(confirmation_url_fun, 1) do
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_manage_user(scope, user) do
|
||||
case deliver_user_confirmation_instructions(user, confirmation_url_fun) do
|
||||
{:ok, email} ->
|
||||
Logger.info("admin.user.confirmation_resent",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id
|
||||
)
|
||||
|
||||
{:ok, email}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp admin_users_query(scope, opts) do
|
||||
roles = Policy.visible_roles(scope)
|
||||
search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim()
|
||||
|
||||
query = from(u in User, where: u.role in ^roles)
|
||||
|
||||
if search == "" do
|
||||
query
|
||||
else
|
||||
pattern = "%#{search}%"
|
||||
|
||||
where(
|
||||
query,
|
||||
[u],
|
||||
ilike(u.email, ^pattern) or ilike(u.username, ^pattern)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defp persist_user_changes(user, changeset) do
|
||||
Repo.transact(fn ->
|
||||
with :ok <- ensure_not_last_super_admin(user, changeset),
|
||||
{:ok, updated} <- Repo.update(changeset) do
|
||||
{:ok, updated}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp ensure_not_last_super_admin(%User{role: :super_admin}, changeset) do
|
||||
case Ecto.Changeset.get_change(changeset, :role) do
|
||||
role when role in [nil, :super_admin] ->
|
||||
:ok
|
||||
|
||||
_role ->
|
||||
super_admins =
|
||||
Repo.all(from(u in User, where: u.role == :super_admin, lock: "FOR UPDATE"))
|
||||
|
||||
if length(super_admins) <= 1 do
|
||||
{:error, :last_super_admin}
|
||||
else
|
||||
:ok
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp ensure_not_last_super_admin(_user, _changeset), do: :ok
|
||||
|
||||
defp log_user_update(scope, user, changeset) do
|
||||
fields = changeset.changes |> Map.keys() |> Enum.sort()
|
||||
|
||||
if fields != [] do
|
||||
Logger.info("admin.user.updated",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id,
|
||||
fields: fields
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defp deliver_invite_instructions(user, invite_url_fun) do
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_invite_instructions(user, invite_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
defp ensure_manage_users(scope) do
|
||||
if Policy.can?(scope, :manage_users), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_can_manage_user(scope, user) do
|
||||
if Policy.can_manage_user?(scope, user), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_can_assign_role(_scope, nil), do: :ok
|
||||
|
||||
defp ensure_can_assign_role(scope, role) do
|
||||
if Policy.can_assign_role?(scope, role), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_not_own_role_change(%Scope{user: %User{id: id}}, %User{id: id}, role)
|
||||
when not is_nil(role),
|
||||
do: {:error, :own_role}
|
||||
|
||||
defp ensure_not_own_role_change(_scope, _user, _role), do: :ok
|
||||
|
||||
defp fetch_user(id) do
|
||||
Repo.get(User, id)
|
||||
rescue
|
||||
Ecto.Query.CastError -> nil
|
||||
end
|
||||
|
||||
defp role_param(attrs), do: Map.get(attrs, "role") || Map.get(attrs, :role)
|
||||
|
||||
defp normalize_role(role) do
|
||||
cond do
|
||||
role in Role.values() -> role
|
||||
is_binary(role) -> Enum.find(Role.values(), &(Atom.to_string(&1) == role))
|
||||
true -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp normalize_page(page) when is_integer(page) and page > 0, do: page
|
||||
|
||||
defp normalize_page(page) when is_binary(page) do
|
||||
case Integer.parse(page) do
|
||||
{number, ""} when number > 0 -> number
|
||||
_ -> 1
|
||||
end
|
||||
end
|
||||
|
||||
defp normalize_page(_page), do: 1
|
||||
|
||||
defp normalize_per_page(per_page) when is_integer(per_page) and per_page > 0 do
|
||||
min(per_page, 100)
|
||||
end
|
||||
|
||||
defp normalize_per_page(_per_page), do: @admin_users_per_page
|
||||
|
||||
## Settings
|
||||
|
||||
@doc """
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
defmodule Chesstrainer.Accounts.Policy do
|
||||
@moduledoc """
|
||||
The single source of truth for administrator capabilities.
|
||||
|
||||
Roles are ordered by `Chesstrainer.Accounts.Role`. An administrator may only
|
||||
manage users below their own rank; a `super_admin` may also manage admins and
|
||||
other super admins, but never changes their own role.
|
||||
|
||||
The router uses `can?/2` to gate the admin area, and every mutating admin
|
||||
LiveView calls back into this module or into the scoped `Accounts` functions
|
||||
so hidden buttons are never the only protection.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Accounts.{Role, Scope, User}
|
||||
|
||||
@capabilities %{
|
||||
manage_endgames: [:admin, :super_admin],
|
||||
manage_themes: [:admin, :super_admin],
|
||||
manage_users: [:admin, :super_admin]
|
||||
}
|
||||
|
||||
@doc "All admin capabilities."
|
||||
@spec capabilities() :: [atom()]
|
||||
def capabilities, do: Map.keys(@capabilities)
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may perform the given admin capability.
|
||||
|
||||
A nil scope or a member/moderator never satisfies an admin capability.
|
||||
"""
|
||||
@spec can?(Scope.t() | nil, atom()) :: boolean()
|
||||
def can?(%Scope{user: %User{role: role}}, capability) when is_atom(capability) do
|
||||
role in Map.get(@capabilities, capability, [])
|
||||
end
|
||||
|
||||
def can?(_scope, _capability), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may edit the target user's role and plan.
|
||||
|
||||
An actor may only modify a user whose role rank is strictly lower, except a
|
||||
`super_admin`, who may also modify admins and other super admins. Nobody may
|
||||
modify themselves through the admin area.
|
||||
"""
|
||||
@spec can_manage_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_manage_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
cond do
|
||||
not can?(scope, :manage_users) -> false
|
||||
actor.id == target.id -> false
|
||||
actor.role == :super_admin -> true
|
||||
Role.rank(actor.role) > Role.rank(target.role) -> true
|
||||
true -> false
|
||||
end
|
||||
end
|
||||
|
||||
def can_manage_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may view the target user in the admin area.
|
||||
|
||||
Admins can see themselves and lower-ranked users read-only; super admins can
|
||||
see everyone. This is deliberately wider than `can_manage_user?/2`, which
|
||||
controls the editable form.
|
||||
"""
|
||||
@spec can_view_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_view_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
can?(scope, :manage_users) and
|
||||
(actor.id == target.id or actor.role == :super_admin or
|
||||
Role.rank(actor.role) > Role.rank(target.role))
|
||||
end
|
||||
|
||||
def can_view_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may assign the given role.
|
||||
|
||||
Admins can only assign member or moderator. Super admins can assign any role.
|
||||
"""
|
||||
@spec can_assign_role?(Scope.t() | nil, Role.value()) :: boolean()
|
||||
def can_assign_role?(%Scope{user: %User{role: :super_admin}}, role) do
|
||||
role in Role.values()
|
||||
end
|
||||
|
||||
def can_assign_role?(%Scope{user: %User{role: actor_role}}, role) do
|
||||
role in Role.values() and Role.rank(actor_role) > Role.rank(role)
|
||||
end
|
||||
|
||||
def can_assign_role?(_scope, _role), do: false
|
||||
|
||||
@doc """
|
||||
Returns the roles whose users the scope may see in the admin user list.
|
||||
|
||||
Admins only see members and moderators; super admins see every role.
|
||||
"""
|
||||
@spec visible_roles(Scope.t() | nil) :: [Role.value()]
|
||||
def visible_roles(%Scope{user: %User{role: :super_admin}}), do: Role.values()
|
||||
|
||||
def visible_roles(%Scope{user: %User{role: :admin}}), do: [:member, :moderator]
|
||||
def visible_roles(_scope), do: []
|
||||
end
|
||||
@@ -6,6 +6,8 @@ defmodule Chesstrainer.Accounts.Role do
|
||||
should ask for the minimum tier they need via `at_least?/2`.
|
||||
"""
|
||||
|
||||
@type value :: :member | :moderator | :admin | :super_admin
|
||||
|
||||
@values [:member, :moderator, :admin, :super_admin]
|
||||
|
||||
@ranks %{
|
||||
|
||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.Scope do
|
||||
|
||||
defstruct user: nil
|
||||
|
||||
@type t :: %__MODULE__{user: User.t() | nil}
|
||||
|
||||
@doc """
|
||||
Creates a scope for the given user.
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.User do
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@doc """
|
||||
A user changeset for registration.
|
||||
|
||||
@@ -53,6 +55,43 @@ defmodule Chesstrainer.Accounts.User do
|
||||
|> validate_required([:role])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the plan.
|
||||
|
||||
The plan is programmatic and must never be cast from user-supplied params.
|
||||
"""
|
||||
def plan_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:plan])
|
||||
|> validate_required([:plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for an admin-created invitation.
|
||||
|
||||
The account is created without a password and marked confirmed, so the
|
||||
recipient can choose a password from the emailed invitation link and log in
|
||||
immediately afterwards. Role and plan are applied separately by
|
||||
`admin_changeset/2` after the caller has checked the policy.
|
||||
"""
|
||||
def invite_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:email, :username])
|
||||
|> validate_email([])
|
||||
|> validate_username([])
|
||||
|> put_change(:confirmed_at, DateTime.utc_now(:second))
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for the fields an administrator may edit.
|
||||
|
||||
These values are programmatic, so this changeset is only used by the scoped
|
||||
admin functions in `Chesstrainer.Accounts`.
|
||||
"""
|
||||
def admin_changeset(user, attrs) do
|
||||
cast(user, attrs, [:role, :plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for registering or changing the email.
|
||||
|
||||
|
||||
@@ -2,20 +2,15 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
# Delivers the email using the application mailer.
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({Branding.name(), Branding.mail_from()})
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|> Mail.deliver()
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -38,6 +33,31 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver an invitation to choose a password.
|
||||
|
||||
Admins create the account without a password; the invitation link uses the
|
||||
same reset-password token flow so the recipient can set one.
|
||||
"""
|
||||
def deliver_invite_instructions(user, url) do
|
||||
deliver(user.email, "You're invited to #{Branding.name()}", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.username},
|
||||
|
||||
An administrator has created an account for you on #{Branding.name()}.
|
||||
|
||||
Choose your password by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you weren't expecting this invitation, please ignore this email.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
|
||||
@@ -17,6 +17,7 @@ defmodule Chesstrainer.Application do
|
||||
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
||||
# {Chesstrainer.Worker, arg},
|
||||
Chesstrainer.GuestLimits,
|
||||
ChesstrainerWeb.LoginThrottle,
|
||||
# Start to serve requests, typically the last entry
|
||||
ChesstrainerWeb.Endpoint,
|
||||
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
||||
|
||||
@@ -106,8 +106,8 @@ defmodule Chesstrainer.Attempts do
|
||||
@doc """
|
||||
The distinct endgame ids `user_id` has attempted in the last `days` days.
|
||||
|
||||
Used by puzzle selection to prefer fresh puzzles; a retry still counts as an
|
||||
attempt, even though the rating window leaves it unrated.
|
||||
Used by puzzle selection to skip puzzles inside the repeat window; a retry
|
||||
still counts as an attempt, even though the rating window leaves it unrated.
|
||||
"""
|
||||
def recent_endgame_ids(user_id, days \\ 30) do
|
||||
cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
|
||||
|
||||
@@ -12,7 +12,8 @@ defmodule Chesstrainer.Branding do
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@innersquare.app"
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
]
|
||||
|
||||
@doc "The display name, e.g. `\"Lucid Chess\"`."
|
||||
@@ -30,6 +31,26 @@ defmodule Chesstrainer.Branding do
|
||||
@doc "The From address used for outgoing mail."
|
||||
def mail_from, do: get(:mail_from)
|
||||
|
||||
@doc """
|
||||
The Discord invite URL, or `nil` when no invite is configured.
|
||||
|
||||
Accepts either a bare invite code (`"abc123"`) or a full URL; a bare code is
|
||||
expanded to `https://discord.gg/<code>`.
|
||||
"""
|
||||
def discord_invite_url do
|
||||
case get(:discord_invite) do
|
||||
value when is_binary(value) ->
|
||||
case String.trim(value) do
|
||||
"" -> nil
|
||||
"http" <> _ = url -> url
|
||||
code -> "https://discord.gg/#{code}"
|
||||
end
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
|
||||
def home_title, do: "#{name()} — #{tagline()}"
|
||||
|
||||
|
||||
@@ -111,8 +111,13 @@ defmodule Chesstrainer.Endgames do
|
||||
@doc """
|
||||
Returns `{key, count}` groups for endgames matching the filters, sorted by key.
|
||||
|
||||
Filters is a map with optional `:themes` (a list of theme ids; an endgame must
|
||||
carry any one of them) and `:key` (an exact Key).
|
||||
Filters is a map with optional:
|
||||
|
||||
* `:themes` - a list of theme ids; an endgame must carry any one of them
|
||||
* `:key` - an exact Key
|
||||
* `:with_theme` - `{theme_id, source}`; only endgames linked to the theme
|
||||
with that source
|
||||
* `:without_theme` - a theme id; only endgames not linked to the theme at all
|
||||
"""
|
||||
def list_key_groups(filters \\ %{}) do
|
||||
Endgame
|
||||
@@ -125,20 +130,31 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns the endgames for one Key, matching the filters, with themes preloaded.
|
||||
|
||||
Accepts `:limit` and `:offset` options for paginating large Key groups.
|
||||
"""
|
||||
def list_endgames_for_key(key, filters \\ %{}) do
|
||||
def list_endgames_for_key(key, filters \\ %{}, opts \\ []) do
|
||||
skip = Keyword.get(opts, :offset, 0)
|
||||
|
||||
Endgame
|
||||
|> apply_filters(filters)
|
||||
|> where([e], e.key == ^key)
|
||||
|> preload(:themes)
|
||||
|> order_by([e], asc: e.fen)
|
||||
|> order_by([e], asc: e.fen, asc: e.id)
|
||||
|> limit_query(Keyword.get(opts, :limit))
|
||||
|> offset(^skip)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
defp limit_query(query, nil), do: query
|
||||
defp limit_query(query, limit), do: limit(query, ^limit)
|
||||
|
||||
defp apply_filters(query, filters) do
|
||||
query
|
||||
|> filter_themes(Map.get(filters, :themes, []))
|
||||
|> filter_key(Map.get(filters, :key))
|
||||
|> filter_with_theme(Map.get(filters, :with_theme))
|
||||
|> filter_without_theme(Map.get(filters, :without_theme))
|
||||
end
|
||||
|
||||
defp filter_themes(query, []), do: query
|
||||
@@ -156,6 +172,30 @@ defmodule Chesstrainer.Endgames do
|
||||
defp filter_key(query, key) when key in [nil, ""], do: query
|
||||
defp filter_key(query, key), do: where(query, [e], e.key == ^key)
|
||||
|
||||
defp filter_with_theme(query, nil), do: query
|
||||
|
||||
defp filter_with_theme(query, {theme_id, source}) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id and t.source == ^to_string(source),
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
defp filter_without_theme(query, nil), do: query
|
||||
|
||||
defp filter_without_theme(query, theme_id) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id,
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id not in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single endgame.
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
defmodule Chesstrainer.Endgames.BulkImport do
|
||||
@moduledoc """
|
||||
Classifies pasted FENs for the admin bulk importer and inserts the positions
|
||||
the local Syzygy tablebase can answer.
|
||||
|
||||
Results always come from `Chesstrainer.Endgames.Tablebase.probe_local_result/1`,
|
||||
so a bulk import never consults the remote (Lichess) backend.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.{FEN, Key, Repo}
|
||||
|
||||
@max_fens 1000
|
||||
@max_pieces 5
|
||||
@default_rating 1500.0
|
||||
|
||||
@type status ::
|
||||
:ready
|
||||
| :duplicate
|
||||
| :invalid_fen
|
||||
| :too_many_pieces
|
||||
| :illegal
|
||||
| :terminal
|
||||
| :unsupported
|
||||
|
||||
@type entry :: %{
|
||||
line: pos_integer(),
|
||||
fen: String.t(),
|
||||
key: String.t() | nil,
|
||||
color: :white | :black | nil,
|
||||
result: Tablebase.result() | nil,
|
||||
status: status(),
|
||||
reason: String.t() | nil
|
||||
}
|
||||
|
||||
@doc """
|
||||
The most FENs a single import will consider.
|
||||
"""
|
||||
@spec max_fens() :: pos_integer()
|
||||
def max_fens, do: @max_fens
|
||||
|
||||
@doc """
|
||||
Parses one FEN per line, skipping blank lines and lines beginning with `#`.
|
||||
|
||||
Returns entries with a status explaining whether the line can be imported,
|
||||
and `too_many?` when the input exceeded `max_fens/0` (only the first
|
||||
`max_fens/0` lines are considered).
|
||||
|
||||
FENs already in the database and duplicates within the batch are reported as
|
||||
duplicates without probing the tablebase.
|
||||
"""
|
||||
@spec preview(String.t()) :: %{entries: [entry()], too_many?: boolean()}
|
||||
def preview(text) when is_binary(text) do
|
||||
lines = parse_lines(text)
|
||||
{lines, rest} = Enum.split(lines, @max_fens)
|
||||
|
||||
fens = Enum.map(lines, fn {_line, fen} -> FEN.normalize(fen) end)
|
||||
existing = existing_fens(fens)
|
||||
|
||||
{entries, _seen} =
|
||||
Enum.map_reduce(lines, %{}, fn {line, raw_fen}, seen ->
|
||||
classify(line, FEN.normalize(raw_fen), seen, existing)
|
||||
end)
|
||||
|
||||
%{entries: entries, too_many?: rest != []}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inserts every `:ready` entry, attaching `themes` and `rating` to each.
|
||||
|
||||
Rows that collide with an existing FEN are skipped. Returns the number
|
||||
imported and the number of entries that were not ready or were skipped.
|
||||
"""
|
||||
@spec commit([entry()], [Chesstrainer.Themes.Theme.t()], number()) ::
|
||||
%{imported: non_neg_integer(), skipped: non_neg_integer()}
|
||||
def commit(entries, themes \\ [], rating \\ @default_rating) do
|
||||
ready = Enum.filter(entries, &(&1.status == :ready))
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
rows =
|
||||
Enum.map(ready, fn entry ->
|
||||
%{
|
||||
id: Ecto.UUID.generate(),
|
||||
public_code: Endgame.generate_public_code(),
|
||||
fen: entry.fen,
|
||||
color: entry.color,
|
||||
key: entry.key,
|
||||
result: entry.result,
|
||||
rating: (rating || @default_rating) * 1.0,
|
||||
rating_deviation: 350.0,
|
||||
times_attempted: 0,
|
||||
times_solved: 0,
|
||||
inserted_at: now,
|
||||
updated_at: now
|
||||
}
|
||||
end)
|
||||
|
||||
{imported, inserted_rows} =
|
||||
Repo.insert_all(Endgame, rows, on_conflict: :nothing, returning: [:id])
|
||||
|
||||
join_rows =
|
||||
for %Endgame{id: id} <- inserted_rows, theme <- themes do
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(id),
|
||||
theme_id: theme.id
|
||||
}
|
||||
end
|
||||
|
||||
if join_rows != [] do
|
||||
Repo.insert_all("endgames_themes", join_rows, on_conflict: :nothing)
|
||||
end
|
||||
|
||||
%{imported: imported, skipped: length(entries) - imported}
|
||||
end
|
||||
|
||||
defp parse_lines(text) do
|
||||
text
|
||||
|> String.split(~r/\r?\n/)
|
||||
|> Enum.with_index(1)
|
||||
|> Enum.reduce([], fn {raw, index}, acc ->
|
||||
trimmed = String.trim(raw)
|
||||
|
||||
if trimmed == "" or String.starts_with?(trimmed, "#") do
|
||||
acc
|
||||
else
|
||||
[{index, trimmed} | acc]
|
||||
end
|
||||
end)
|
||||
|> Enum.reverse()
|
||||
end
|
||||
|
||||
defp existing_fens(fens) do
|
||||
fens
|
||||
|> Enum.uniq()
|
||||
|> then(fn fens -> Repo.all(from e in Endgame, where: e.fen in ^fens, select: e.fen) end)
|
||||
|> Map.new(&{&1, true})
|
||||
end
|
||||
|
||||
defp classify(line, fen, seen, existing) do
|
||||
cond do
|
||||
Map.has_key?(seen, fen) ->
|
||||
{entry(line, fen, :duplicate, "Duplicate FEN in this batch"), seen}
|
||||
|
||||
Map.has_key?(existing, fen) ->
|
||||
{entry(line, fen, :duplicate, "FEN already exists"), seen}
|
||||
|
||||
true ->
|
||||
{classify_new(line, fen), Map.put(seen, fen, true)}
|
||||
end
|
||||
end
|
||||
|
||||
defp classify_new(line, fen) do
|
||||
issues = Endgame.fen_issues(fen)
|
||||
pieces = FEN.piece_count(fen)
|
||||
|
||||
cond do
|
||||
issues != [] ->
|
||||
entry(line, fen, :invalid_fen, Enum.join(issues, "; "))
|
||||
|
||||
is_integer(pieces) and pieces > @max_pieces ->
|
||||
entry(
|
||||
line,
|
||||
fen,
|
||||
:too_many_pieces,
|
||||
"Only positions with #{@max_pieces} or fewer pieces are supported"
|
||||
)
|
||||
|
||||
true ->
|
||||
classify_probe(line, fen)
|
||||
end
|
||||
end
|
||||
|
||||
defp classify_probe(line, fen) do
|
||||
case Tablebase.probe_local_result(fen) do
|
||||
{:ok, result} ->
|
||||
entry(line, fen, :ready, nil) |> Map.put(:result, result)
|
||||
|
||||
{:error, :terminal} ->
|
||||
entry(line, fen, :terminal, "Checkmate, stalemate, or no legal moves")
|
||||
|
||||
{:error, :illegal} ->
|
||||
entry(line, fen, :illegal, "The tablebase rejected this position")
|
||||
|
||||
{:error, :not_configured} ->
|
||||
entry(
|
||||
line,
|
||||
fen,
|
||||
:unsupported,
|
||||
"Local tablebase is not configured (set TABLEBASE_PATH)"
|
||||
)
|
||||
|
||||
{:error, :unsupported} ->
|
||||
entry(line, fen, :unsupported, "The local tablebase cannot answer this position")
|
||||
end
|
||||
end
|
||||
|
||||
defp entry(line, fen, status, reason) do
|
||||
%{
|
||||
line: line,
|
||||
fen: fen,
|
||||
key: key_for(fen),
|
||||
color: FEN.color_from_fen(fen),
|
||||
result: nil,
|
||||
status: status,
|
||||
reason: reason
|
||||
}
|
||||
end
|
||||
|
||||
defp key_for(fen) do
|
||||
case Key.from_fen(fen) do
|
||||
{:ok, key} -> key
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -90,10 +90,15 @@ defmodule Chesstrainer.Endgames.Endgame do
|
||||
|
||||
defp normalize_attrs(attrs), do: attrs
|
||||
|
||||
# Strict structural validation. Mirrors chess.js rules so the FEN survives
|
||||
# both the server-side parser (Chex, permissive) and the client-side parser
|
||||
# (chess.js, strict).
|
||||
defp fen_issues(fen) do
|
||||
@doc """
|
||||
Returns the structural problems with a FEN, or `[]` when it is well formed.
|
||||
|
||||
Strict structural validation. Mirrors chess.js rules so the FEN survives
|
||||
both the server-side parser (Chex, permissive) and the client-side parser
|
||||
(chess.js, strict). Used by the admin bulk importer to explain why a line
|
||||
was rejected.
|
||||
"""
|
||||
def fen_issues(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[board, active, _castling, _en_passant, halfmove, fullmove] ->
|
||||
board_valid? = valid_board?(board)
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemes do
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its canonical Key.
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes behave as a
|
||||
partition: selecting several in a filter produces their union, never an
|
||||
ambiguous intersection. A lone king against heavy or pawn material is split
|
||||
out because those positions teach a specific technique — basic mate or
|
||||
promotion — rather than a general material class.
|
||||
|
||||
Families are derived, never judged. They are stored with source `derived`, so
|
||||
a refresh replaces them without touching curated or community themes.
|
||||
Positions with no legal content (`K v K`) and rows without a Key are skipped.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@families [
|
||||
basic_mate: %{
|
||||
name: "basic mate",
|
||||
description:
|
||||
"A lone king against the queen or a rook, with no pawns: the puzzle is about delivering mate."
|
||||
},
|
||||
king_and_pawn: %{
|
||||
name: "king and pawn",
|
||||
description:
|
||||
"A lone king against king and pawns: the puzzle is about promotion, or holding the draw."
|
||||
},
|
||||
bare_king_other: %{
|
||||
name: "bare king other",
|
||||
description:
|
||||
"A lone king against minor pieces, or against pawns and pieces: usually a technique exercise with little counterplay."
|
||||
},
|
||||
queen_and_pawn: %{
|
||||
name: "queen and pawn",
|
||||
description: "Queens and pawns on the board."
|
||||
},
|
||||
queen_endgame: %{
|
||||
name: "queen endgame",
|
||||
description: "Queens on the board, with no pawns."
|
||||
},
|
||||
rook_and_pawn: %{
|
||||
name: "rook and pawn",
|
||||
description: "Rooks and pawns, with no queens."
|
||||
},
|
||||
rook_endgame: %{
|
||||
name: "rook endgame",
|
||||
description: "Rooks, with no queens and no pawns."
|
||||
},
|
||||
minor_piece_and_pawn: %{
|
||||
name: "minor piece and pawn",
|
||||
description: "Bishops and knights with pawns, with no queens or rooks."
|
||||
},
|
||||
minor_piece_endgame: %{
|
||||
name: "minor piece endgame",
|
||||
description: "Bishops and knights, with no queens, rooks or pawns."
|
||||
},
|
||||
pawn_endgame: %{
|
||||
name: "pawn endgame",
|
||||
description: "Kings and pawns only."
|
||||
}
|
||||
]
|
||||
|
||||
@type family ::
|
||||
:basic_mate
|
||||
| :king_and_pawn
|
||||
| :bare_king_other
|
||||
| :queen_and_pawn
|
||||
| :queen_endgame
|
||||
| :rook_and_pawn
|
||||
| :rook_endgame
|
||||
| :minor_piece_and_pawn
|
||||
| :minor_piece_endgame
|
||||
| :pawn_endgame
|
||||
|
||||
@doc "The material families, in a stable order."
|
||||
def families, do: @families
|
||||
|
||||
@doc """
|
||||
Returns the material family for a Key.
|
||||
|
||||
Returns `:kings_only` for `"K v K"` and `:unknown` when the Key is missing or
|
||||
not shaped like `"<side> v <side>"`.
|
||||
"""
|
||||
@spec family(String.t() | nil) :: family() | :kings_only | :unknown
|
||||
def family(key) when is_binary(key) do
|
||||
case String.split(key, " v ") do
|
||||
[a, b] ->
|
||||
cond do
|
||||
bare?(a) and bare?(b) -> :kings_only
|
||||
bare?(a) -> bare_king_family(counts(b))
|
||||
bare?(b) -> bare_king_family(counts(a))
|
||||
true -> material_family(merge(counts(a), counts(b)))
|
||||
end
|
||||
|
||||
_ ->
|
||||
:unknown
|
||||
end
|
||||
end
|
||||
|
||||
def family(_key), do: :unknown
|
||||
|
||||
@doc """
|
||||
Creates or corrects the material themes, keyed by family.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a material theme
|
||||
without losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{family() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@families, fn {family, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :material)
|
||||
{family, ensure_material_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived material theme.
|
||||
|
||||
Returns the number of endgames tagged, the number skipped (kings only or no
|
||||
Key) and the number of material themes. Re-running is idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
tagged: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
material_ids = Enum.map(themes, fn {_family, theme} -> theme.id end)
|
||||
|
||||
{links, skipped} =
|
||||
Endgame
|
||||
|> select([e], {e.id, e.key})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0}, fn {id, key}, {links, skipped} ->
|
||||
case family(key) do
|
||||
family when family in [:kings_only, :unknown] ->
|
||||
{links, skipped + 1}
|
||||
|
||||
family ->
|
||||
{[{id, Map.fetch!(themes, family).id} | links], skipped}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(material_ids, links)
|
||||
|
||||
%{tagged: length(links), skipped: skipped, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_material_theme(theme, attrs) do
|
||||
if theme.kind == :material and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :material, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp bare?(side), do: side == "K"
|
||||
|
||||
defp bare_king_family(counts) do
|
||||
cond do
|
||||
count(counts, "P") == 0 and (count(counts, "Q") > 0 or count(counts, "R") > 0) ->
|
||||
:basic_mate
|
||||
|
||||
count(counts, "P") > 0 and count(counts, "Q") == 0 and count(counts, "R") == 0 ->
|
||||
:king_and_pawn
|
||||
|
||||
true ->
|
||||
:bare_king_other
|
||||
end
|
||||
end
|
||||
|
||||
defp material_family(counts) do
|
||||
cond do
|
||||
count(counts, "Q") > 0 and count(counts, "P") > 0 ->
|
||||
:queen_and_pawn
|
||||
|
||||
count(counts, "Q") > 0 ->
|
||||
:queen_endgame
|
||||
|
||||
count(counts, "R") > 0 and count(counts, "P") > 0 ->
|
||||
:rook_and_pawn
|
||||
|
||||
count(counts, "R") > 0 ->
|
||||
:rook_endgame
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 and count(counts, "P") > 0 ->
|
||||
:minor_piece_and_pawn
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 ->
|
||||
:minor_piece_endgame
|
||||
|
||||
count(counts, "P") > 0 ->
|
||||
:pawn_endgame
|
||||
|
||||
true ->
|
||||
:kings_only
|
||||
end
|
||||
end
|
||||
|
||||
defp counts(side), do: Enum.frequencies(String.graphemes(side))
|
||||
|
||||
defp merge(left, right), do: Map.merge(left, right, fn _piece, a, b -> a + b end)
|
||||
|
||||
defp count(counts, piece), do: Map.get(counts, piece, 0)
|
||||
end
|
||||
@@ -0,0 +1,198 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemes do
|
||||
@moduledoc """
|
||||
Derives objective motif themes by probing each endgame's position.
|
||||
|
||||
Motifs describe the kind of problem, independent of the material family: an
|
||||
endgame can be a rook endgame and an only-move puzzle at the same time. Every
|
||||
motif is proved from the local Syzygy tables — one probe returns the root WDL,
|
||||
the DTZ and every legal move with its own WDL — so nothing here is a guess and
|
||||
nothing calls the remote backend.
|
||||
|
||||
Motif links are recorded as `derived` and refreshed as a whole. Material
|
||||
families, curated links and community links are untouched because the refresh
|
||||
is scoped to the motif themes.
|
||||
|
||||
Loss endgames are skipped: only-move is undefined when every move loses, and
|
||||
the library no longer contains them.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@motifs [
|
||||
only_move: %{
|
||||
name: "only move",
|
||||
description:
|
||||
"Exactly one legal move keeps the result, so the puzzle is about finding the single accurate move."
|
||||
},
|
||||
underpromotion: %{
|
||||
name: "underpromotion",
|
||||
description:
|
||||
"The result can only be preserved by promoting to a rook, bishop or knight; promoting to a queen does not work."
|
||||
},
|
||||
fifty_move_draw: %{
|
||||
name: "50-move draw",
|
||||
description:
|
||||
"The result turns on the fifty-move rule: the win needs more moves than the halfmove clock allows, so the defender can claim a draw."
|
||||
}
|
||||
]
|
||||
|
||||
@type motif :: :only_move | :underpromotion | :fifty_move_draw
|
||||
|
||||
@doc "The motif themes, in a stable order."
|
||||
def motifs, do: @motifs
|
||||
|
||||
@doc """
|
||||
Returns the motifs for one probed position.
|
||||
|
||||
`moves` are Fathom move tuples `{wdl, from, to, promotes, ep, dtz}` and carry
|
||||
the mover's perspective, so they are compared with the root WDL directly.
|
||||
`halfmove_clock` comes from the FEN; the probe itself runs with `rule50 = 0`.
|
||||
"""
|
||||
@spec motifs_for(atom(), integer() | nil, [tuple()], non_neg_integer()) :: [motif()]
|
||||
def motifs_for(wdl, dtz, moves, halfmove_clock) do
|
||||
outcome = Tablebase.normalize_wdl(wdl)
|
||||
|
||||
preserving =
|
||||
Enum.filter(moves, fn {move_wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
Tablebase.normalize_wdl(move_wdl) == outcome
|
||||
end)
|
||||
|
||||
[]
|
||||
|> maybe_only_move(outcome, moves, preserving)
|
||||
|> maybe_underpromotion(preserving)
|
||||
|> maybe_fifty_move(wdl, dtz, halfmove_clock)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates or corrects the motif themes, keyed by motif.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a motif without
|
||||
losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{motif() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@motifs, fn {motif, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :motif)
|
||||
{motif, ensure_motif_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived motif links.
|
||||
|
||||
Returns the number of links written, the number of endgames skipped because
|
||||
the local tables could not answer them, and a count per motif. Re-running is
|
||||
idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
links: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
by_motif: %{motif() => non_neg_integer()},
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
motif_ids = Enum.map(themes, fn {_motif, theme} -> theme.id end)
|
||||
|
||||
initial_counts = Map.new(@motifs, fn {motif, _attrs} -> {motif, 0} end)
|
||||
|
||||
{links, skipped, by_motif} =
|
||||
Endgame
|
||||
|> where([e], e.result in [:win, :draw])
|
||||
|> select([e], {e.id, e.fen})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0, initial_counts}, fn {id, fen}, {links, skipped, counts} ->
|
||||
case probe(fen) do
|
||||
{:ok, %{wdl: wdl, dtz: dtz, moves: moves}} ->
|
||||
motifs = motifs_for(wdl, dtz, moves, halfmove_clock(fen))
|
||||
|
||||
links =
|
||||
Enum.reduce(motifs, links, fn motif, acc ->
|
||||
[{id, Map.fetch!(themes, motif).id} | acc]
|
||||
end)
|
||||
|
||||
counts =
|
||||
Enum.reduce(motifs, counts, fn motif, acc ->
|
||||
Map.update!(acc, motif, &(&1 + 1))
|
||||
end)
|
||||
|
||||
{links, skipped, counts}
|
||||
|
||||
{:error, _reason} ->
|
||||
{links, skipped + 1, counts}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(motif_ids, links)
|
||||
|
||||
%{links: length(links), skipped: skipped, by_motif: by_motif, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_motif_theme(theme, attrs) do
|
||||
if theme.kind == :motif and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :motif, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp probe(fen), do: probe_module().probe_local_detail(fen)
|
||||
|
||||
defp probe_module do
|
||||
Application.get_env(:chesstrainer, :motif_probe, FathomBackend)
|
||||
end
|
||||
|
||||
defp maybe_only_move(acc, outcome, moves, preserving) do
|
||||
if outcome in [:win, :draw] and length(moves) > 1 and length(preserving) == 1 do
|
||||
[:only_move | acc]
|
||||
else
|
||||
acc
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_underpromotion(acc, preserving) do
|
||||
underpromotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes in [2, 3, 4]
|
||||
end)
|
||||
|
||||
queen_promotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes == 1
|
||||
end)
|
||||
|
||||
if underpromotes? and not queen_promotes?, do: [:underpromotion | acc], else: acc
|
||||
end
|
||||
|
||||
defp maybe_fifty_move(acc, wdl, dtz, halfmove_clock) do
|
||||
table_draw? = wdl in [:cursed_win, :blessed_loss]
|
||||
|
||||
clock_exhausted? =
|
||||
wdl == :win and is_integer(dtz) and dtz > 100 - halfmove_clock
|
||||
|
||||
if table_draw? or clock_exhausted?, do: [:fifty_move_draw | acc], else: acc
|
||||
end
|
||||
|
||||
defp halfmove_clock(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[_board, _active, _castling, _ep, clock, _fullmove] ->
|
||||
case Integer.parse(clock) do
|
||||
{value, _rest} -> value
|
||||
:error -> 0
|
||||
end
|
||||
|
||||
_ ->
|
||||
0
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -12,6 +12,7 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.FEN
|
||||
|
||||
@type result :: :win | :draw | :loss | :unknown
|
||||
@@ -67,6 +68,19 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
||||
def flip(:draw), do: :draw
|
||||
def flip(_outcome), do: :unknown
|
||||
|
||||
@doc """
|
||||
Probes a FEN using only the local Syzygy tablebase and returns the result
|
||||
from the side-to-move's perspective.
|
||||
|
||||
Unlike `new/1` this never falls back to the remote backend and never reads or
|
||||
writes the cache. It is the primitive behind the admin bulk importer, so an
|
||||
imported result always comes from our own tablebases.
|
||||
"""
|
||||
@spec probe_local_result(String.t()) ::
|
||||
{:ok, result()}
|
||||
| {:error, :not_configured | :illegal | :terminal | :unsupported}
|
||||
def probe_local_result(fen), do: FathomBackend.probe_result_local(fen)
|
||||
|
||||
@spec new(String.t()) ::
|
||||
{:ok, t()}
|
||||
| {:cooldown, non_neg_integer()}
|
||||
|
||||
@@ -18,6 +18,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
alias Chesstrainer.Endgames.Tablebase.Local
|
||||
alias Chesstrainer.Endgames.Tablebase.Move
|
||||
alias Chesstrainer.Endgames.Tablebase.San
|
||||
alias Chesstrainer.FEN
|
||||
|
||||
@impl true
|
||||
def probe(fen) do
|
||||
@@ -32,6 +33,85 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase without the remote fallback and returns only the
|
||||
position's result.
|
||||
|
||||
Used by the admin bulk importer, which must never import a result from
|
||||
Lichess. The result is from the side-to-move's perspective, matching the
|
||||
`category` on `Chesstrainer.Endgames.Tablebase`.
|
||||
|
||||
Returns `{:error, :terminal}` for checkmate, stalemate, and positions with no
|
||||
legal moves, because they cannot be played as puzzles.
|
||||
"""
|
||||
@spec probe_result_local(String.t()) ::
|
||||
{:ok, Tablebase.result()}
|
||||
| {:error, :not_configured | :illegal | :terminal | :unsupported}
|
||||
def probe_result_local(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed ->
|
||||
{:error, :illegal}
|
||||
|
||||
:checkmate ->
|
||||
{:error, :terminal}
|
||||
|
||||
:stalemate ->
|
||||
{:error, :terminal}
|
||||
|
||||
{wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
if moves == [] do
|
||||
{:error, :terminal}
|
||||
else
|
||||
case Tablebase.normalize_wdl(wdl) do
|
||||
:unknown -> {:error, :unsupported}
|
||||
category -> {:ok, category}
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase and returns the raw root outcome and move list.
|
||||
|
||||
Unlike `probe_result_local/1`, this keeps the per-move tuples and the raw WDL
|
||||
atom, including `:cursed_win` and `:blessed_loss`, which the motif derivation
|
||||
needs. It never falls back to the remote backend or consults the cache.
|
||||
|
||||
Returns `{:error, :unsupported}` when the local files cannot answer the
|
||||
position, including a partial tablebase set where Fathom reports `:failed`.
|
||||
"""
|
||||
@spec probe_local_detail(String.t()) ::
|
||||
{:ok, %{wdl: atom(), dtz: integer(), moves: [tuple()]}}
|
||||
| {:error, :not_configured | :terminal | :unsupported}
|
||||
def probe_local_detail(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed -> {:error, :unsupported}
|
||||
:checkmate -> {:error, :terminal}
|
||||
:stalemate -> {:error, :terminal}
|
||||
{wdl, _from, _to, _promotes, _ep, dtz} -> {:ok, %{wdl: wdl, dtz: dtz, moves: moves}}
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
defp fallback(fen) do
|
||||
(Application.get_env(:chesstrainer, :tablebase_fallback) || Lichess).probe(fen)
|
||||
end
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
defmodule Chesstrainer.Mail do
|
||||
@moduledoc """
|
||||
House rules for every outgoing email.
|
||||
|
||||
Notifiers build the message body and hand it here, so the sender identity,
|
||||
reply-to address, SES configuration set and the test redirect are applied in
|
||||
exactly one place and no sender can forget them.
|
||||
|
||||
The From address lives on the `mail.` subdomain so transactional mail is
|
||||
distinct from the addresses that receive mail on the apex domain. SES
|
||||
verification of the parent domain covers the subdomain, so no separate
|
||||
identity is required for the From header to be accepted.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
|
||||
@default_configuration_set "my-first-configuration-set"
|
||||
|
||||
@doc """
|
||||
Applies the house rules and delivers the email.
|
||||
|
||||
Returns `{:ok, email}` so notifiers can report the message they sent.
|
||||
"""
|
||||
def deliver(%Swoosh.Email{} = email) do
|
||||
email = prepare(email)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Applies the house rules without delivering.
|
||||
|
||||
Exposed so tooling (such as `mix mail.check`) can inspect or send the exact
|
||||
message the application would send.
|
||||
"""
|
||||
def prepare(%Swoosh.Email{} = email) do
|
||||
email
|
||||
|> Swoosh.Email.from({Branding.name(), Branding.mail_from()})
|
||||
|> Swoosh.Email.reply_to(Branding.support_email())
|
||||
|> Swoosh.Email.put_provider_option(:configuration_set_name, configuration_set())
|
||||
|> redirect()
|
||||
end
|
||||
|
||||
defp configuration_set do
|
||||
Application.get_env(:chesstrainer, :ses_configuration_set, @default_configuration_set)
|
||||
end
|
||||
|
||||
# Rewrites every recipient to one address so a staging or production smoke
|
||||
# test can send through real SES without reaching users. The original
|
||||
# recipients stay in the subject and in an `X-Original-To` header so the
|
||||
# redirected message explains itself.
|
||||
defp redirect(email) do
|
||||
case Application.get_env(:chesstrainer, :mail_redirect_to) do
|
||||
address when is_binary(address) and address != "" ->
|
||||
originals = recipients(email)
|
||||
|
||||
require Logger
|
||||
|
||||
Logger.warning("mail redirect: #{Enum.join(originals, ", ")} -> #{address}")
|
||||
|
||||
%{email | to: [{"", address}], cc: [], bcc: []}
|
||||
|> Swoosh.Email.header("X-Original-To", Enum.join(originals, ", "))
|
||||
|> Swoosh.Email.subject("[→ #{Enum.join(originals, ", ")}] #{email.subject}")
|
||||
|
||||
_unset ->
|
||||
email
|
||||
end
|
||||
end
|
||||
|
||||
defp recipients(email) do
|
||||
[email.to, email.cc, email.bcc]
|
||||
|> List.flatten()
|
||||
|> Enum.reject(&is_nil/1)
|
||||
|> Enum.map(fn
|
||||
{_name, address} -> address
|
||||
address when is_binary(address) -> address
|
||||
end)
|
||||
end
|
||||
end
|
||||
@@ -6,7 +6,7 @@ defmodule Chesstrainer.MailingList.Notifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mailer
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
@doc """
|
||||
Delivers the confirmation email for a mailing-list subscription.
|
||||
@@ -30,16 +30,10 @@ defmodule Chesstrainer.MailingList.Notifier do
|
||||
end
|
||||
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({Branding.name(), Branding.mail_from()})
|
||||
|> reply_to(Branding.support_email())
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|> Mail.deliver()
|
||||
end
|
||||
end
|
||||
|
||||
+85
-58
@@ -2,14 +2,21 @@ defmodule Chesstrainer.Puzzles do
|
||||
@moduledoc """
|
||||
Selects endgames to serve as puzzles.
|
||||
|
||||
A puzzle is played at one of three difficulties — `:easy`, `:medium` or
|
||||
`:hard` — defined relative to the current user's rating: `:medium` is within
|
||||
a configurable band of the user's rating, `:easy` below it and `:hard` above
|
||||
it. The same endgame is therefore easy for one player and hard for another.
|
||||
Difficulty is a bias, not a filter. Every endgame is weighted by how close its
|
||||
rating is to a target derived from the user's rating — the user's own rating
|
||||
for `:medium`, below it for `:easy` and above it for `:hard` — and one
|
||||
candidate is drawn from that weighted distribution. Nearby endgames are much
|
||||
more likely, but the whole library stays reachable, so a thin region around
|
||||
the user's rating can never leave the pool empty.
|
||||
|
||||
Selection prefers endgames the user has not attempted in the last 30 days.
|
||||
When that pool is empty it falls back to any endgame in the band; the rating
|
||||
window keeps a recent replay unrated until it expires.
|
||||
Endgames the user has attempted inside the repeat window are skipped, as is
|
||||
anything passed in `:exclude_ids` (the puzzles already served in a session).
|
||||
Only when every candidate is excluded does selection fall back to the least
|
||||
recently attempted endgame, so the repeat is the most overdue one rather than
|
||||
an arbitrary one.
|
||||
|
||||
The same endgame is therefore easy for one player and hard for another: a
|
||||
rating is what makes the two comparable.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
@@ -17,95 +24,115 @@ defmodule Chesstrainer.Puzzles do
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Accounts.User
|
||||
alias Chesstrainer.Attempts
|
||||
alias Chesstrainer.Attempts.Attempt
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
|
||||
@default_band_width 100
|
||||
@default_spread 150
|
||||
@default_repeat_window_days 30
|
||||
@default_targets [easy: -200, medium: 0, hard: 200]
|
||||
@difficulties [:easy, :medium, :hard]
|
||||
|
||||
@doc "The difficulties a session can be played at."
|
||||
def difficulties, do: @difficulties
|
||||
|
||||
@doc """
|
||||
The half-width of the medium band, in rating points.
|
||||
How far, in rating points, a puzzle's likelihood falls off from the target.
|
||||
|
||||
Configured under `:chesstrainer, :puzzles, :band_width`.
|
||||
A larger spread draws more widely around the target. Configured under
|
||||
`:chesstrainer, :puzzles, :spread`.
|
||||
"""
|
||||
def band_width do
|
||||
:chesstrainer
|
||||
|> Application.get_env(:puzzles, [])
|
||||
|> Keyword.get(:band_width, @default_band_width)
|
||||
end
|
||||
def spread, do: setting(:spread, @default_spread)
|
||||
|
||||
@doc """
|
||||
The `{min, max}` rating range for `difficulty` relative to `rating`.
|
||||
The minimum gap, in days, before the same endgame may be served again.
|
||||
|
||||
A `nil` bound is open-ended.
|
||||
Configured under `:chesstrainer, :puzzles, :repeat_window_days`.
|
||||
"""
|
||||
def difficulty_range(rating, difficulty) when difficulty in @difficulties do
|
||||
width = band_width()
|
||||
def repeat_window_days, do: setting(:repeat_window_days, @default_repeat_window_days)
|
||||
|
||||
case difficulty do
|
||||
:easy -> {nil, rating - width}
|
||||
:medium -> {rating - width, rating + width}
|
||||
:hard -> {rating + width, nil}
|
||||
end
|
||||
@doc """
|
||||
The rating `difficulty` aims at, given the player's `rating`.
|
||||
|
||||
The offsets are configured under `:chesstrainer, :puzzles, :targets`.
|
||||
"""
|
||||
def difficulty_target(rating, difficulty) when difficulty in @difficulties do
|
||||
rating + Keyword.fetch!(setting(:targets, @default_targets), difficulty)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Picks the next puzzle for `user` at `difficulty`, using `user.rating` as the
|
||||
baseline.
|
||||
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating
|
||||
the puzzle just played. Returns `nil` when no endgame exists at all.
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used for the puzzles
|
||||
already served in this session. Returns `nil` when no endgame exists at all.
|
||||
"""
|
||||
def next_endgame(%User{} = user, difficulty, opts \\ [])
|
||||
when difficulty in @difficulties do
|
||||
exclude_ids = Keyword.get(opts, :exclude_ids, [])
|
||||
band = difficulty_range(user.rating, difficulty)
|
||||
recent_ids = Attempts.recent_endgame_ids(user.id)
|
||||
recent_ids = Attempts.recent_endgame_ids(user.id, repeat_window_days())
|
||||
target = difficulty_target(user.rating, difficulty)
|
||||
|
||||
fresh =
|
||||
Endgame
|
||||
|> in_band(band)
|
||||
|> skip_ids(exclude_ids)
|
||||
|> skip_ids(recent_ids)
|
||||
|> random_one()
|
||||
|
||||
fresh || fallback(user.rating, band, exclude_ids)
|
||||
end
|
||||
|
||||
defp fallback(rating, band, exclude_ids) do
|
||||
Endgame
|
||||
|> in_band(band)
|
||||
|> skip_ids(exclude_ids)
|
||||
|> random_one()
|
||||
|> on_side_of(user.rating, difficulty)
|
||||
|> skip_ids(exclude_ids ++ recent_ids)
|
||||
|> weighted_one(target)
|
||||
|> case do
|
||||
nil -> nearest(rating, exclude_ids)
|
||||
nil -> least_recently_attempted(user.id, exclude_ids)
|
||||
endgame -> endgame
|
||||
end
|
||||
end
|
||||
|
||||
defp nearest(rating, exclude_ids) do
|
||||
# Keep the labels honest: "easy" never serves above the user's rating plus the
|
||||
# spread, and "hard" never below it minus the spread. "medium" is open, which
|
||||
# is what lets it reach the rest of the library.
|
||||
defp on_side_of(query, _rating, :medium), do: query
|
||||
|
||||
defp on_side_of(query, rating, :easy),
|
||||
do: where(query, [e], e.rating <= ^(rating + spread()))
|
||||
|
||||
defp on_side_of(query, rating, :hard),
|
||||
do: where(query, [e], e.rating >= ^(rating - spread()))
|
||||
|
||||
# Draw one row with probability proportional to
|
||||
# `exp(-|rating - target| / spread)`: an exponential race, where the row with
|
||||
# the smallest `-ln(U) / weight` wins.
|
||||
defp weighted_one(query, target) do
|
||||
spread = spread() * 1.0
|
||||
target = target * 1.0
|
||||
|
||||
query
|
||||
|> order_by(
|
||||
[e],
|
||||
fragment("-ln(1 - random()) * exp(abs(? - ?) / ?)", e.rating, ^target, ^spread)
|
||||
)
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
# Every candidate is excluded, so the repeat window is overruled: serve
|
||||
# whatever the user has waited longest to see again.
|
||||
defp least_recently_attempted(user_id, exclude_ids) do
|
||||
attempted =
|
||||
Attempt
|
||||
|> where([a], a.user_id == ^user_id)
|
||||
|> group_by([a], a.endgame_id)
|
||||
|> select([a], %{endgame_id: a.endgame_id, last_at: max(a.inserted_at)})
|
||||
|
||||
Endgame
|
||||
|> skip_ids(exclude_ids)
|
||||
|> order_by([e], asc: fragment("ABS(? - ?)", e.rating, ^rating))
|
||||
|> join(:left, [e], a in subquery(attempted), on: a.endgame_id == e.id)
|
||||
|> order_by([_e, a], asc_nulls_first: a.last_at)
|
||||
|> order_by([e], fragment("random()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp random_one(query) do
|
||||
query
|
||||
|> order_by([e], fragment("RANDOM()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp in_band(query, {nil, max}), do: where(query, [e], e.rating <= ^max)
|
||||
defp in_band(query, {min, nil}), do: where(query, [e], e.rating >= ^min)
|
||||
|
||||
defp in_band(query, {min, max}),
|
||||
do: where(query, [e], e.rating >= ^min and e.rating <= ^max)
|
||||
|
||||
defp skip_ids(query, []), do: query
|
||||
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
|
||||
|
||||
defp setting(key, default) do
|
||||
:chesstrainer
|
||||
|> Application.get_env(:puzzles, [])
|
||||
|> Keyword.get(key, default)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -18,6 +18,28 @@ defmodule Chesstrainer.Release do
|
||||
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Derives material family themes for the whole library.
|
||||
|
||||
Runs in the release without starting the web application: `with_repo/2`
|
||||
starts just the repository, which is all the derivation needs.
|
||||
"""
|
||||
def derive_material, do: with_repo(&Chesstrainer.Endgames.MaterialThemes.derive/0)
|
||||
|
||||
@doc """
|
||||
Derives motif themes from the local tablebase for the whole library.
|
||||
"""
|
||||
def derive_motifs, do: with_repo(&Chesstrainer.Endgames.MotifThemes.derive/0)
|
||||
|
||||
defp with_repo(fun) do
|
||||
load_app()
|
||||
|
||||
for repo <- repos() do
|
||||
{:ok, result, _} = Ecto.Migrator.with_repo(repo, fn _repo -> fun.() end)
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
defp repos do
|
||||
Application.fetch_env!(@app, :ecto_repos)
|
||||
end
|
||||
|
||||
+230
-3
@@ -4,6 +4,8 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
alias Chesstrainer.Themes.Theme
|
||||
@@ -21,6 +23,43 @@ defmodule Chesstrainer.Themes do
|
||||
Repo.all(Theme)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Lists themes for the admin index with their endgame usage count.
|
||||
|
||||
Options:
|
||||
|
||||
* `:search` - case-insensitive match on the theme name
|
||||
* `:category` - one of `:endgame`, `:opening`, `:tactic`, or blank for all
|
||||
|
||||
Returns `{theme, usage_count}` tuples sorted by name.
|
||||
"""
|
||||
def list_themes_for_admin(opts \\ []) do
|
||||
search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim()
|
||||
category = normalize_category(Keyword.get(opts, :category, ""))
|
||||
|
||||
query = from(t in Theme, order_by: [asc: t.name])
|
||||
|
||||
query =
|
||||
if search == "" do
|
||||
query
|
||||
else
|
||||
where(query, [t], ilike(t.name, ^"%#{search}%"))
|
||||
end
|
||||
|
||||
query =
|
||||
if category do
|
||||
where(query, [t], t.category == ^category)
|
||||
else
|
||||
query
|
||||
end
|
||||
|
||||
query
|
||||
|> join(:left, [t], j in "endgames_themes", on: j.theme_id == t.id)
|
||||
|> group_by([t], t.id)
|
||||
|> select([t, j], {t, count(j.endgame_id)})
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single theme.
|
||||
|
||||
@@ -37,9 +76,26 @@ defmodule Chesstrainer.Themes do
|
||||
"""
|
||||
def get_theme!(id), do: Repo.get!(Theme, id)
|
||||
|
||||
@doc """
|
||||
Gets a single endgame theme by its slug.
|
||||
|
||||
Returns `nil` when no endgame theme has that slug.
|
||||
"""
|
||||
def get_theme_by_slug(slug) when is_binary(slug) do
|
||||
Repo.one(
|
||||
from t in Theme,
|
||||
where: t.slug == ^slug and t.category == :endgame,
|
||||
limit: 1
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme.
|
||||
|
||||
This is the unscoped path used by internal callers such as seeds, fixtures and
|
||||
the admin picker, which are already behind an authorization check. Prefer
|
||||
`create_theme/2` wherever a scope is available.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> create_theme(%{field: value})
|
||||
@@ -55,6 +111,21 @@ defmodule Chesstrainer.Themes do
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme on behalf of an administrator.
|
||||
|
||||
Members cannot introduce new theme names; their contribution path is a
|
||||
suggestion, which a moderator reviews. Returns `{:error, :unauthorized}`
|
||||
for a scope that cannot manage themes.
|
||||
"""
|
||||
def create_theme(%Scope{} = scope, attrs) do
|
||||
if Policy.can?(scope, :manage_themes) do
|
||||
create_theme(attrs)
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a theme.
|
||||
|
||||
@@ -123,20 +194,167 @@ defmodule Chesstrainer.Themes do
|
||||
@doc """
|
||||
Finds a theme by name (trimmed and case-insensitive) for a category, creating it
|
||||
if it does not exist.
|
||||
|
||||
Options:
|
||||
|
||||
* `:kind` - the kind for a newly created theme; defaults to `:technique`
|
||||
|
||||
This is the picker's helper and is expected to run behind an admin check.
|
||||
"""
|
||||
def get_or_create(name, category) when is_binary(name) do
|
||||
def get_or_create(name, category, opts \\ []) when is_binary(name) do
|
||||
name = String.trim(name)
|
||||
|
||||
if name == "" do
|
||||
{:error, :blank_name}
|
||||
else
|
||||
case find_by_name(name, category) do
|
||||
nil -> create_theme(%{name: name, category: category})
|
||||
theme -> {:ok, theme}
|
||||
nil ->
|
||||
create_theme(%{
|
||||
name: name,
|
||||
category: category,
|
||||
kind: Keyword.get(opts, :kind, :technique)
|
||||
})
|
||||
|
||||
theme ->
|
||||
{:ok, theme}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Replaces every link to `scoped_theme_ids` with the derived links in `links`.
|
||||
|
||||
This is for themes that are objectively derived: the pass owns its themes
|
||||
entirely, so a link's previous source is irrelevant and every link is
|
||||
rewritten as `derived`. Links to themes outside `scoped_theme_ids` — curated
|
||||
or community — are untouched.
|
||||
|
||||
The operation is a full refresh for the given themes, so it can move an
|
||||
endgame between families when a rule changes. `links` is a list of
|
||||
`{endgame_id, theme_id}` pairs.
|
||||
"""
|
||||
@spec replace_theme_links([term()], [{Ecto.UUID.t(), term()}]) :: :ok
|
||||
def replace_theme_links(scoped_theme_ids, links) when is_list(links) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
if scoped_theme_ids != [] do
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.theme_id in ^scoped_theme_ids
|
||||
)
|
||||
end
|
||||
|
||||
links
|
||||
|> Enum.map(fn {endgame_id, theme_id} ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@link_sources [:curated, :community]
|
||||
|
||||
@doc """
|
||||
Links `theme` to many endgames at once with the given source.
|
||||
|
||||
Defaults to `:curated`, which is what the admin tagging workspace writes.
|
||||
Existing links are left alone, so re-applying is safe. Returns the number of
|
||||
endgames the link was attempted for.
|
||||
"""
|
||||
@spec tag_endgames(Theme.t(), [Ecto.UUID.t()], :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def tag_endgames(%Theme{id: theme_id}, endgame_ids, source \\ :curated)
|
||||
when is_list(endgame_ids) and source in @link_sources do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
endgame_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn endgame_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: to_string(source),
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|> Enum.chunk_every(5_000)
|
||||
|> Enum.each(fn rows ->
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end)
|
||||
|
||||
{:ok, length(Enum.uniq(endgame_ids))}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Removes a link from `theme` to one endgame, but only if it has the given
|
||||
source.
|
||||
|
||||
The tagging workspace removes `:curated` links only, so a derived or
|
||||
community link can never be deleted by hand. Returns the number removed.
|
||||
"""
|
||||
@spec untag_endgame(Theme.t(), Ecto.UUID.t(), :curated | :community) ::
|
||||
{:ok, non_neg_integer()}
|
||||
def untag_endgame(%Theme{id: theme_id}, endgame_id, source \\ :curated)
|
||||
when source in @link_sources do
|
||||
{count, _} =
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where:
|
||||
l.theme_id == ^theme_id and l.endgame_id == type(^endgame_id, :binary_id) and
|
||||
l.source == ^to_string(source)
|
||||
)
|
||||
|
||||
{:ok, count}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Replaces the derived theme links for one endgame.
|
||||
|
||||
Only links whose source is `derived` are removed, so curated and
|
||||
community-approved links survive every derivation pass. Links that are
|
||||
already present are left alone, which makes the operation idempotent.
|
||||
"""
|
||||
@spec sync_derived_themes(Ecto.UUID.t(), [term()]) :: :ok
|
||||
def sync_derived_themes(endgame_id, theme_ids) do
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
Repo.transaction(fn ->
|
||||
Repo.delete_all(
|
||||
from l in "endgames_themes",
|
||||
where: l.endgame_id == type(^endgame_id, :binary_id) and l.source == "derived"
|
||||
)
|
||||
|
||||
rows =
|
||||
theme_ids
|
||||
|> Enum.uniq()
|
||||
|> Enum.map(fn theme_id ->
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(endgame_id),
|
||||
theme_id: theme_id,
|
||||
source: "derived",
|
||||
inserted_at: now
|
||||
}
|
||||
end)
|
||||
|
||||
if rows != [] do
|
||||
Repo.insert_all("endgames_themes", rows, on_conflict: :nothing)
|
||||
end
|
||||
end)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp find_by_name(name, category) do
|
||||
downcased = String.downcase(name)
|
||||
|
||||
@@ -153,4 +371,13 @@ defmodule Chesstrainer.Themes do
|
||||
def names(themes) when is_list(themes) do
|
||||
themes |> Enum.map(& &1.name) |> Enum.sort()
|
||||
end
|
||||
|
||||
defp normalize_category(category) when category in [:endgame, :opening, :tactic],
|
||||
do: category
|
||||
|
||||
defp normalize_category(category) when is_binary(category) do
|
||||
Enum.find([:endgame, :opening, :tactic], &(Atom.to_string(&1) == category))
|
||||
end
|
||||
|
||||
defp normalize_category(_category), do: nil
|
||||
end
|
||||
|
||||
@@ -1,27 +1,106 @@
|
||||
defmodule Chesstrainer.Themes.Theme do
|
||||
@moduledoc """
|
||||
A label describing an endgame's technique or goal.
|
||||
|
||||
A theme has a stable `slug` for URLs, a `kind` saying where the label comes
|
||||
from — `material`, `motif` or `technique` — and an optional description. The
|
||||
slug is generated from the name when the theme is first created and is then
|
||||
left alone, so renaming a theme never breaks a link to it.
|
||||
"""
|
||||
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@kinds [material: "material", motif: "motif", technique: "technique"]
|
||||
|
||||
schema "themes" do
|
||||
field :name, :string
|
||||
field :slug, :string
|
||||
field :description, :string
|
||||
field :kind, Ecto.Enum, values: @kinds, default: :technique
|
||||
field :category, Ecto.Enum, values: [endgame: "endgame", opening: "opening", tactic: "tactic"]
|
||||
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@doc "The kinds a theme can have."
|
||||
def kinds, do: Keyword.keys(@kinds)
|
||||
|
||||
@doc """
|
||||
Turns a theme name into a URL-safe slug.
|
||||
|
||||
Lowercase letters, digits and single hyphens; accents are folded, runs of
|
||||
other characters collapse to one hyphen, and a blank result becomes
|
||||
`"theme"`.
|
||||
"""
|
||||
@spec slugify(String.t() | nil) :: String.t()
|
||||
def slugify(name) do
|
||||
slug =
|
||||
name
|
||||
|> to_string()
|
||||
|> :unicode.characters_to_nfd_binary()
|
||||
|> String.replace(~r/[\x{0300}-\x{036F}]/u, "")
|
||||
|> String.downcase()
|
||||
|> String.replace(~r/[^a-z0-9]+/u, "-")
|
||||
|> String.trim("-")
|
||||
|
||||
if slug == "", do: "theme", else: slug
|
||||
end
|
||||
|
||||
@doc false
|
||||
def changeset(theme, attrs) do
|
||||
theme
|
||||
|> cast(attrs, [:name, :category])
|
||||
|> update_change(:name, fn
|
||||
name when is_binary(name) -> String.trim(name)
|
||||
name -> name
|
||||
end)
|
||||
|> validate_required([:name, :category])
|
||||
|> cast(attrs, [:name, :slug, :description, :kind, :category])
|
||||
|> update_change(:name, &trim/1)
|
||||
|> update_change(:description, &trim/1)
|
||||
|> put_slug()
|
||||
|> validate_required([:name, :slug, :kind, :category])
|
||||
|> validate_length(:name, min: 1, max: 60)
|
||||
|> validate_length(:slug, min: 1, max: 80)
|
||||
|> validate_length(:description, max: 500)
|
||||
|> validate_format(:slug, ~r/\A[a-z0-9]+(?:-[a-z0-9]+)*\z/,
|
||||
message: "must be lowercase letters, numbers and single hyphens"
|
||||
)
|
||||
|> unique_constraint(:name,
|
||||
name: :themes_name_category_lower_index,
|
||||
message: "already exists"
|
||||
)
|
||||
|> unique_constraint(:slug, message: "is already taken")
|
||||
|> check_constraint(:kind, name: :themes_kind_in_allowed)
|
||||
end
|
||||
|
||||
defp put_slug(changeset) do
|
||||
case get_field(changeset, :slug) do
|
||||
slug when is_binary(slug) ->
|
||||
if String.trim(slug) == "" do
|
||||
generate_slug(changeset)
|
||||
else
|
||||
put_change(changeset, :slug, slugify(slug))
|
||||
end
|
||||
|
||||
nil ->
|
||||
generate_slug(changeset)
|
||||
end
|
||||
end
|
||||
|
||||
# A new theme starts without a name, so generating a slug from it would only
|
||||
# produce the fallback. Wait until there is a name to derive from.
|
||||
defp generate_slug(changeset) do
|
||||
case get_field(changeset, :name) do
|
||||
name when is_binary(name) ->
|
||||
if String.trim(name) == "" do
|
||||
changeset
|
||||
else
|
||||
put_change(changeset, :slug, slugify(name))
|
||||
end
|
||||
|
||||
_ ->
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
defp trim(value) when is_binary(value), do: String.trim(value)
|
||||
defp trim(value), do: value
|
||||
end
|
||||
|
||||
@@ -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)
|
||||
@@ -103,6 +107,7 @@ defmodule ChesstrainerWeb do
|
||||
alias Phoenix.LiveView.JS
|
||||
alias Chesstrainer.Branding
|
||||
alias ChesstrainerWeb.Layouts
|
||||
alias ChesstrainerWeb.SEO
|
||||
|
||||
# Routes generation with the ~p sigil
|
||||
unquote(verified_routes())
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
defmodule ChesstrainerWeb.ClientAddress do
|
||||
@moduledoc """
|
||||
Resolves the client's IP address from either a controller connection or a
|
||||
LiveView socket.
|
||||
|
||||
`X-Forwarded-For` is only read when
|
||||
`Chesstrainer.GuestLimits.trust_forwarded_for?/0` is enabled. In that case the
|
||||
rightmost entry is used, because that is the value our own proxy appended.
|
||||
Invalid or missing headers fall back to the peer address.
|
||||
|
||||
Production is Cloudflare -> Caddy -> Phoenix. `deploy/Caddyfile` makes Caddy
|
||||
overwrite `X-Forwarded-For` with Cloudflare's `CF-Connecting-IP` and rejects
|
||||
direct-to-origin requests, so the rightmost value is the real visitor rather
|
||||
than a Cloudflare edge address.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.GuestLimits
|
||||
|
||||
@typedoc "An IPv4/IPv6 address, or `nil` when no peer data is available."
|
||||
@type address :: :inet.ip_address() | nil
|
||||
|
||||
@doc "Returns the client address for a controller connection."
|
||||
@spec from_conn(Plug.Conn.t()) :: address()
|
||||
def from_conn(conn) do
|
||||
if GuestLimits.trust_forwarded_for?() do
|
||||
conn
|
||||
|> Plug.Conn.get_req_header("x-forwarded-for")
|
||||
|> parse_forwarded_header()
|
||||
|> fallback(conn.remote_ip)
|
||||
else
|
||||
conn.remote_ip
|
||||
end
|
||||
end
|
||||
|
||||
@doc "Returns the client address for a connected LiveView socket."
|
||||
@spec from_socket(Phoenix.LiveView.Socket.t()) :: address()
|
||||
def from_socket(socket) do
|
||||
if GuestLimits.trust_forwarded_for?() do
|
||||
socket
|
||||
|> Phoenix.LiveView.get_connect_info(:x_headers)
|
||||
|> parse_x_headers()
|
||||
|> fallback(peer_address(socket))
|
||||
else
|
||||
peer_address(socket)
|
||||
end
|
||||
end
|
||||
|
||||
defp peer_address(socket) do
|
||||
case Phoenix.LiveView.get_connect_info(socket, :peer_data) do
|
||||
%{address: address} -> address
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_forwarded_header([value | _]) when is_binary(value), do: parse_address(value)
|
||||
defp parse_forwarded_header(_headers), do: nil
|
||||
|
||||
defp parse_x_headers(headers) when is_list(headers) do
|
||||
case List.keyfind(headers, "x-forwarded-for", 0) do
|
||||
{_, value} when is_binary(value) -> parse_address(value)
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_x_headers(_headers), do: nil
|
||||
|
||||
# The rightmost entry is the one our own proxy appended.
|
||||
defp parse_address(value) do
|
||||
value
|
||||
|> String.split(",")
|
||||
|> List.last()
|
||||
|> to_string()
|
||||
|> String.trim()
|
||||
|> String.to_charlist()
|
||||
|> :inet.parse_address()
|
||||
|> case do
|
||||
{:ok, address} -> address
|
||||
{:error, _} -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp fallback(nil, fallback), do: fallback
|
||||
defp fallback(address, _fallback), do: address
|
||||
end
|
||||
@@ -65,7 +65,7 @@ defmodule ChesstrainerWeb.CoreComponents do
|
||||
attr :id, :string, doc: "the optional id of flash container"
|
||||
attr :flash, :map, default: %{}, doc: "the map of flash messages to display"
|
||||
attr :title, :string, default: nil
|
||||
attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup"
|
||||
attr :kind, :atom, values: [:info, :success, :error], doc: "used for styling and flash lookup"
|
||||
attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container"
|
||||
|
||||
slot :inner_block, doc: "the optional inner block that renders the flash message"
|
||||
@@ -86,9 +86,11 @@ defmodule ChesstrainerWeb.CoreComponents do
|
||||
<div class={[
|
||||
"flex w-full items-start gap-3 rounded-lg border px-4 py-3 text-sm text-wrap shadow-lg",
|
||||
@kind == :info && "border-info bg-info text-info-content",
|
||||
@kind == :success && "border-accent bg-accent text-accent-content",
|
||||
@kind == :error && "border-error bg-error text-error-content"
|
||||
]}>
|
||||
<.icon :if={@kind == :info} name="hero-information-circle" class="size-5 shrink-0" />
|
||||
<.icon :if={@kind == :success} name="hero-check-circle" class="size-5 shrink-0" />
|
||||
<.icon :if={@kind == :error} name="hero-exclamation-circle" class="size-5 shrink-0" />
|
||||
<div>
|
||||
<p :if={@title} class="font-semibold">{@title}</p>
|
||||
@@ -356,10 +358,10 @@ defmodule ChesstrainerWeb.CoreComponents do
|
||||
~H"""
|
||||
<header class={[@actions != [] && "flex items-center justify-between gap-6", "pb-4"]}>
|
||||
<div>
|
||||
<h1 class="text-lg font-semibold leading-8">
|
||||
<h1 class="settings-header">
|
||||
{render_slot(@inner_block)}
|
||||
</h1>
|
||||
<p :if={@subtitle != []} class="text-sm text-base-content/70 mt-4">
|
||||
<p :if={@subtitle != []} class="settings-subtitle">
|
||||
{render_slot(@subtitle)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,7 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
"""
|
||||
use ChesstrainerWeb, :html
|
||||
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Role
|
||||
alias Chesstrainer.Accounts.Scope
|
||||
|
||||
@@ -125,14 +126,57 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
Start training <.icon_arrow />
|
||||
</.pill_button>
|
||||
<% end %>
|
||||
|
||||
<div class="nav-menu-tools">
|
||||
<.colour_mode_toggle />
|
||||
<.discord_link />
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<.discord_link />
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Renders the shared sub-navigation for admin pages.
|
||||
|
||||
Items are filtered by capability, so the same component is safe to render on
|
||||
every admin screen.
|
||||
"""
|
||||
attr :current_scope, :map, default: nil
|
||||
|
||||
def admin_nav(assigns) do
|
||||
links =
|
||||
for {capability, label, href} <- [
|
||||
{:manage_endgames, "Endgames", ~p"/admin/endgames"},
|
||||
{:manage_themes, "Themes", ~p"/admin/themes"},
|
||||
{:manage_users, "Users", ~p"/admin/users"}
|
||||
],
|
||||
Policy.can?(assigns.current_scope, capability),
|
||||
do: %{label: label, href: href}
|
||||
|
||||
assigns = assign(assigns, :links, links)
|
||||
|
||||
~H"""
|
||||
<nav
|
||||
aria-label="Admin"
|
||||
class="mb-6 flex flex-wrap items-center gap-1 border-b border-base-200 pb-3 text-sm font-semibold"
|
||||
>
|
||||
<.link
|
||||
:for={link <- @links}
|
||||
navigate={link.href}
|
||||
class="rounded-md px-3 py-1.5 text-base-content/70 hover:bg-base-200 hover:text-base-content"
|
||||
>
|
||||
{link.label}
|
||||
</.link>
|
||||
</nav>
|
||||
"""
|
||||
end
|
||||
|
||||
defp nav_links(scope) do
|
||||
marketing =
|
||||
if Scope.premium?(scope) do
|
||||
@@ -187,6 +231,8 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
<a href="/privacy">Privacy Policy</a>
|
||||
<a href="/terms-conditions">Terms & Conditions</a>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
<a href="/sitemap.xml">Sitemap</a>
|
||||
<.discord_link />
|
||||
</nav>
|
||||
|
||||
<small>© {@year} {Branding.name()}</small>
|
||||
@@ -194,6 +240,35 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Renders the Discord invite as an icon-only link.
|
||||
|
||||
The glyph is decorative; the `aria-label` carries the link's purpose for
|
||||
screen readers. Renders nothing when no invite is configured, so environments
|
||||
without one never show a dead link.
|
||||
"""
|
||||
def discord_link(assigns) do
|
||||
assigns = assign(assigns, :href, Branding.discord_invite_url())
|
||||
|
||||
~H"""
|
||||
<a
|
||||
:if={@href}
|
||||
class="discord-link"
|
||||
href={@href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={"Join the #{Branding.name()} Discord"}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M20.317 4.3698a19.7913 19.7913 0 0 0-4.8851-1.5152.0741.0741 0 0 0-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 0 0-.0785-.037 19.7363 19.7363 0 0 0-4.8852 1.515.0699.0699 0 0 0-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 0 0 .0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 0 0 .0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 0 0-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 0 1-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 0 1 .0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 0 1 .0785.0105c.1202.0991.246.1971.3728.2914a.077.077 0 0 1-.0066.1277c-.5986.3428-1.2201.6447-1.8739.8923a.0766.0766 0 0 0-.0407.1057c.36.699.7715 1.3647 1.225 1.9942a.076.076 0 0 0 .0843.0276c1.9608-.6066 3.9493-1.5218 6.0021-3.0294a.077.077 0 0 0 .0322-.0561c.5008-5.1763-.8398-9.6746-3.5543-13.6607a.061.061 0 0 0-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Shows the flash group with standard titles and content.
|
||||
|
||||
@@ -209,9 +284,10 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
<div
|
||||
id={@id}
|
||||
aria-live="polite"
|
||||
class="pointer-events-none fixed right-4 top-4 z-50 flex w-80 max-w-80 flex-col gap-2 sm:w-96 sm:max-w-96"
|
||||
class="pointer-events-none fixed left-4 top-4 z-50 flex w-80 max-w-80 flex-col gap-2 sm:w-96 sm:max-w-96"
|
||||
>
|
||||
<.flash kind={:info} flash={@flash} />
|
||||
<.flash kind={:success} flash={@flash} />
|
||||
<.flash kind={:error} flash={@flash} />
|
||||
|
||||
<.flash
|
||||
@@ -243,6 +319,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
|
||||
@@ -318,7 +405,8 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
matomo_url: url,
|
||||
matomo_site_id: site_id && to_string(site_id),
|
||||
analytics_enabled:
|
||||
is_binary(url) and url != "" and site_id not in [nil, ""] and is_nil(user)
|
||||
is_binary(url) and byte_size(url) > 0 and is_binary(site_id) and byte_size(site_id) > 0 and
|
||||
is_nil(user)
|
||||
)
|
||||
|
||||
~H"""
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<html lang={assigns[:lang] || "en"}>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta :if={assigns[:noindex]} name="robots" content="noindex" />
|
||||
<meta :if={assigns[:noindex]} name="robots" content="noindex, nofollow" />
|
||||
|
||||
<meta name="csrf-token" content={get_csrf_token()} />
|
||||
<.live_title
|
||||
@@ -30,7 +30,24 @@
|
||||
content={assigns[:meta_description]}
|
||||
/>
|
||||
<meta :if={assigns[:canonical_url]} property="og:url" content={assigns[:canonical_url]} />
|
||||
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
property="og:image"
|
||||
content={assigns[:og_image_url] || SEO.og_image_url()}
|
||||
/>
|
||||
<meta :if={assigns[:meta_description]} property="og:image:width" content="1200" />
|
||||
<meta :if={assigns[:meta_description]} property="og:image:height" content="630" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
property="og:image:alt"
|
||||
content={"#{Branding.name()} — #{Branding.tagline()}"}
|
||||
/>
|
||||
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary_large_image" />
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
name="twitter:image"
|
||||
content={assigns[:og_image_url] || SEO.og_image_url()}
|
||||
/>
|
||||
<meta
|
||||
:if={assigns[:meta_description]}
|
||||
name="twitter:title"
|
||||
@@ -41,6 +58,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"
|
||||
@@ -65,6 +90,9 @@
|
||||
>
|
||||
</script>
|
||||
<Layouts.theme_script />
|
||||
<script :if={assigns[:json_ld]} type="application/ld+json">
|
||||
<%= raw(assigns[:json_ld]) %>
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<a
|
||||
|
||||
@@ -65,7 +65,10 @@
|
||||
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
|
||||
|
||||
event.preventDefault();
|
||||
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"));
|
||||
// Each breakpoint renders its own copy of the switch, so only the visible
|
||||
// group takes part in arrow-key navigation.
|
||||
const buttons = Array.from(document.querySelectorAll("[data-phx-theme]"))
|
||||
.filter((button) => button.offsetParent !== null);
|
||||
const offset = event.key === "ArrowRight" ? 1 : -1;
|
||||
const index = (buttons.indexOf(button) + offset + buttons.length) % buttons.length;
|
||||
const next = buttons[index];
|
||||
|
||||
@@ -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
|
||||
@@ -30,6 +30,8 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
attr :move_input_error, :string, default: nil
|
||||
attr :last_check, :boolean, default: false
|
||||
attr :last_checkmate, :boolean, default: false
|
||||
attr :rating, :any, default: nil
|
||||
attr :rating_delta, :any, default: nil
|
||||
|
||||
def play_surface(assigns) do
|
||||
assigns =
|
||||
@@ -167,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>
|
||||
@@ -192,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>
|
||||
@@ -209,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!"}
|
||||
@@ -250,9 +268,17 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
<p class="text-muted font-bold">Make a move.</p>
|
||||
<p class="text-muted">You play {colour_name(@endgame.color)}</p>
|
||||
<% end %>
|
||||
<p :if={@status in [:solved, :failed]} class="mt-1 text-xs text-muted">
|
||||
Puzzle rating: {round(@endgame.rating)}
|
||||
</p>
|
||||
<div
|
||||
:if={@status in [:solved, :failed]}
|
||||
class="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs"
|
||||
>
|
||||
<span class="text-muted">Puzzle rating: {round(@endgame.rating)}</span>
|
||||
<span :if={@rating} id="your-rating" class="flex items-center gap-1.5 text-muted">
|
||||
Your rating
|
||||
<span class="font-mono font-semibold text-base-content">{round(@rating)}</span>
|
||||
<.rating_change :if={@rating_delta} id="rating-change" delta={@rating_delta} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -411,8 +437,7 @@ defmodule ChesstrainerWeb.PlayComponents do
|
||||
|> Enum.with_index(1)
|
||||
end
|
||||
|
||||
defp display_plies(true, line, _plies), do: line
|
||||
defp display_plies(false, _line, plies), do: plies
|
||||
defp display_plies(reviewing, line, plies), do: if(reviewing, do: line, else: plies)
|
||||
|
||||
defp colour_name(:white), do: "White"
|
||||
defp colour_name(:black), do: "Black"
|
||||
@@ -450,8 +475,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."
|
||||
@@ -478,7 +502,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)
|
||||
|
||||
@@ -10,6 +10,8 @@ defmodule ChesstrainerWeb.RatingComponents do
|
||||
|
||||
use Phoenix.Component
|
||||
|
||||
import ChesstrainerWeb.CoreComponents, only: [icon: 1]
|
||||
|
||||
# Glicko ratings are conventionally shown on a 0–3000 scale. The default
|
||||
# rating is 1500 and the deviation is capped at 350, so 500–3000 keeps the
|
||||
# useful range readable without letting a stray value push the marker off.
|
||||
@@ -78,6 +80,56 @@ defmodule ChesstrainerWeb.RatingComponents do
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Renders a signed rating change as a compact, colour-coded pill.
|
||||
|
||||
A gain is green with an upward trend, a loss is red with a downward trend,
|
||||
and no change is neutral.
|
||||
"""
|
||||
attr :delta, :any, required: true
|
||||
attr :id, :string, default: nil
|
||||
attr :class, :any, default: nil
|
||||
|
||||
def rating_change(assigns) do
|
||||
~H"""
|
||||
<span
|
||||
id={@id}
|
||||
class={[
|
||||
"inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 font-mono text-xs font-semibold",
|
||||
change_class(@delta),
|
||||
@class
|
||||
]}
|
||||
>
|
||||
<.icon name={change_icon(@delta)} class="size-3.5" />
|
||||
{format_delta(@delta)}
|
||||
</span>
|
||||
"""
|
||||
end
|
||||
|
||||
@doc "Formats a rating change with an explicit sign, e.g. `+12`, `-8` or `0`."
|
||||
def format_delta(nil), do: "—"
|
||||
|
||||
def format_delta(delta) when is_number(delta) do
|
||||
rounded = round(delta)
|
||||
|
||||
cond do
|
||||
rounded > 0 -> "+#{rounded}"
|
||||
true -> Integer.to_string(rounded)
|
||||
end
|
||||
end
|
||||
|
||||
defp change_class(delta) when is_number(delta) and delta > 0,
|
||||
do: "bg-success/15 text-success-text"
|
||||
|
||||
defp change_class(delta) when is_number(delta) and delta < 0,
|
||||
do: "bg-error/15 text-error-text"
|
||||
|
||||
defp change_class(_delta), do: "bg-base-200 text-muted"
|
||||
|
||||
defp change_icon(delta) when is_number(delta) and delta > 0, do: "hero-arrow-trending-up"
|
||||
defp change_icon(delta) when is_number(delta) and delta < 0, do: "hero-arrow-trending-down"
|
||||
defp change_icon(_delta), do: "hero-minus"
|
||||
|
||||
# Position on the gauge as a percentage, clamped to the drawn scale.
|
||||
defp pct(value) do
|
||||
clamped = value |> max(@scale_min) |> min(@scale_max)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
defmodule ChesstrainerWeb.ThemePicker do
|
||||
@moduledoc """
|
||||
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` 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
|
||||
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
attr :selected_themes, :list, required: true
|
||||
attr :theme_query, :string, required: true
|
||||
attr :theme_results, :list, required: true
|
||||
attr :can_create, :boolean, required: true
|
||||
|
||||
def theme_picker(assigns) do
|
||||
~H"""
|
||||
<div class="mb-6">
|
||||
<span class="mb-1 block text-sm font-medium text-base-content">Themes</span>
|
||||
|
||||
<div class="flex flex-wrap gap-2 mb-2">
|
||||
<.badge :for={theme <- @selected_themes} color="primary">
|
||||
{theme.name}
|
||||
<button
|
||||
type="button"
|
||||
phx-click="remove_theme"
|
||||
phx-value-id={theme.id}
|
||||
aria-label={"Remove #{theme.name}"}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</.badge>
|
||||
</div>
|
||||
|
||||
<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…"
|
||||
/>
|
||||
|
||||
<ul>
|
||||
<li :for={theme <- @theme_results}>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="add_theme"
|
||||
phx-value-id={theme.id}
|
||||
class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-base-200"
|
||||
>
|
||||
{theme.name}
|
||||
</button>
|
||||
</li>
|
||||
|
||||
<li :if={@can_create}>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="create_theme"
|
||||
phx-value-name={@theme_query}
|
||||
class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-base-200"
|
||||
>
|
||||
Create theme "{String.trim(@theme_query)}"
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the search query, matching endgame themes and whether the query can be
|
||||
created as a new theme.
|
||||
"""
|
||||
def assign_search(socket, query) do
|
||||
trimmed = String.trim(query)
|
||||
results = Themes.search(query, "endgame")
|
||||
|
||||
can_create =
|
||||
trimmed != "" and
|
||||
not Enum.any?(results, &(String.downcase(&1.name) == String.downcase(trimmed)))
|
||||
|
||||
socket
|
||||
|> assign(:theme_query, query)
|
||||
|> assign(:theme_results, results)
|
||||
|> assign(:can_create, can_create)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a theme from the search box (or selects the existing match) and adds
|
||||
it to the selected themes.
|
||||
"""
|
||||
def create_theme(socket, name) do
|
||||
if String.trim(name) == "" do
|
||||
socket
|
||||
else
|
||||
case Themes.get_or_create(name, "endgame") do
|
||||
{:ok, theme} ->
|
||||
socket |> add_selected_theme(theme) |> clear_search()
|
||||
|
||||
{:error, _reason} ->
|
||||
Phoenix.LiveView.put_flash(socket, :error, "Could not create that theme.")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Clears the theme search results.
|
||||
"""
|
||||
def clear_search(socket) do
|
||||
socket
|
||||
|> assign(:theme_query, "")
|
||||
|> assign(:theme_results, [])
|
||||
|> assign(:can_create, false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a theme to the selected themes, ignoring duplicates.
|
||||
"""
|
||||
def add_selected_theme(socket, theme) do
|
||||
if Enum.any?(socket.assigns.selected_themes, &(&1.id == theme.id)) do
|
||||
socket
|
||||
else
|
||||
assign(socket, :selected_themes, socket.assigns.selected_themes ++ [theme])
|
||||
end
|
||||
end
|
||||
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"
|
||||
|
||||
@@ -10,7 +10,7 @@ defmodule ChesstrainerWeb.HealthController do
|
||||
status = if health.status == "down", do: :service_unavailable, else: :ok
|
||||
|
||||
conn
|
||||
|> put_resp_header("x-robots-tag", "noindex")
|
||||
|> put_resp_header("x-robots-tag", "noindex, nofollow")
|
||||
|> put_status(status)
|
||||
|> json(health)
|
||||
end
|
||||
|
||||
@@ -6,6 +6,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.DailyPuzzles
|
||||
alias Chesstrainer.Endgames
|
||||
alias ChesstrainerWeb.SEO
|
||||
|
||||
@description "Short, focused endgame puzzles against tablebase-perfect defence. " <>
|
||||
"Learn to see the winning move and make the endgame your strongest phase."
|
||||
@@ -15,13 +16,15 @@ defmodule ChesstrainerWeb.PageController do
|
||||
render_coming_soon(conn)
|
||||
else
|
||||
endgames = Endgames.curated_endgames()
|
||||
canonical_url = SEO.canonical_url(conn)
|
||||
|
||||
conn
|
||||
|> assign(:js_entry, ~p"/assets/js/marketing.js")
|
||||
|> assign(:page_title, Branding.home_title())
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, @description)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, canonical_url)
|
||||
|> assign(:json_ld, SEO.json_ld(canonical_url))
|
||||
|> assign(:mailing_list_enabled, mailing_list_enabled?())
|
||||
|> render(:home,
|
||||
endgames: endgames,
|
||||
@@ -43,7 +46,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
:meta_description,
|
||||
"How #{Branding.name()} collects, uses, and protects your personal data."
|
||||
)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> render(:privacy)
|
||||
end
|
||||
|
||||
@@ -53,7 +56,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|> assign(:page_title, Branding.title("Terms & Conditions"))
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, "The terms that apply when you use #{Branding.name()}.")
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> render(:terms_conditions)
|
||||
end
|
||||
|
||||
@@ -66,7 +69,8 @@ defmodule ChesstrainerWeb.PageController do
|
||||
:meta_description,
|
||||
"Éditeur, hébergeur et informations légales de #{Branding.name()}."
|
||||
)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> assign(:lang, "fr")
|
||||
|> render(:mentions_legales)
|
||||
end
|
||||
|
||||
@@ -86,7 +90,7 @@ defmodule ChesstrainerWeb.PageController do
|
||||
|> assign(:page_title, Branding.home_title())
|
||||
|> assign(:title_suffix, "")
|
||||
|> assign(:meta_description, @description)
|
||||
|> assign(:canonical_url, current_url(conn))
|
||||
|> assign(:canonical_url, SEO.canonical_url(conn))
|
||||
|> assign(:noindex, true)
|
||||
|> assign(:mailing_list_enabled, mailing_list_enabled?())
|
||||
|> render(:coming_soon)
|
||||
|
||||
@@ -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>
|
||||
@@ -34,8 +40,11 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<%!-- <section class="learning-strip" id="method">
|
||||
<p>Built for the part of chess that decides everything.</p>
|
||||
<section class="learning-strip" id="method">
|
||||
<figure class="learning-quote">
|
||||
<blockquote>“The hardest game to win is a won game.”</blockquote>
|
||||
<figcaption>— Emmanuel Lasker</figcaption>
|
||||
</figure>
|
||||
<div class="stat">
|
||||
<strong>{count_label(@puzzle_count)}</strong>
|
||||
<span>puzzles</span>
|
||||
@@ -44,9 +53,9 @@
|
||||
<strong>{@user_count}</strong>
|
||||
<span>Players improving their endgame</span>
|
||||
</div>
|
||||
</section> --%>
|
||||
</section>
|
||||
|
||||
<%!-- <section class="puzzle-section" id="puzzles">
|
||||
<section class="puzzle-section" id="puzzles">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<span class="section-kicker">Choose your lesson</span>
|
||||
@@ -59,16 +68,16 @@
|
||||
that you’ll recognise over the board.
|
||||
</p>
|
||||
</div>
|
||||
<div class="puzzle-grid">
|
||||
<%= for {endgame, index} <- Enum.with_index(@endgames) do %>
|
||||
<.puzzle_card
|
||||
endgame={endgame}
|
||||
index={index}
|
||||
active={@active_endgame && endgame.id == @active_endgame.id}
|
||||
/>
|
||||
<% end %>
|
||||
<div class="puzzle-coming-soon">
|
||||
<div class="eyebrow">
|
||||
<.icon_spark /> Coming soon
|
||||
</div>
|
||||
<strong>The lesson library is on its way.</strong>
|
||||
<p>
|
||||
A growing set of positions, each teaching one idea. Today’s puzzle is already live.
|
||||
</p>
|
||||
</div>
|
||||
</section> --%>
|
||||
</section>
|
||||
|
||||
<.mailing_list_signup :if={@mailing_list_enabled} />
|
||||
|
||||
|
||||
@@ -6,12 +6,16 @@ defmodule ChesstrainerWeb.SitemapController do
|
||||
them and they render the same interactive surface with only the position
|
||||
differing, so listing them all would be index bloat. Revisit that if public
|
||||
browse pages (by Key or theme) exist and are worth ranking.
|
||||
|
||||
No `<lastmod>` is emitted: none of these pages has a stored modification time,
|
||||
and an invented date (such as "today" on every request) teaches crawlers to
|
||||
distrust the sitemap.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
def index(conn, _params) do
|
||||
urls = [
|
||||
entries = [
|
||||
url(conn, ~p"/"),
|
||||
url(conn, ~p"/privacy"),
|
||||
url(conn, ~p"/terms-conditions"),
|
||||
@@ -20,16 +24,19 @@ defmodule ChesstrainerWeb.SitemapController do
|
||||
|
||||
conn
|
||||
|> put_resp_content_type("application/xml")
|
||||
|> send_resp(200, render_sitemap(urls))
|
||||
|> send_resp(200, render_sitemap(entries))
|
||||
end
|
||||
|
||||
defp render_sitemap(urls) do
|
||||
entries = Enum.map_join(urls, &" <url><loc>#{escape(&1)}</loc></url>\n")
|
||||
defp render_sitemap(entries) do
|
||||
urls =
|
||||
Enum.map_join(entries, fn loc ->
|
||||
" <url><loc>#{escape(loc)}</loc></url>\n"
|
||||
end)
|
||||
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
#{entries}</urlset>
|
||||
#{urls}</urlset>
|
||||
"""
|
||||
end
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -1,48 +1,90 @@
|
||||
defmodule ChesstrainerWeb.UserSessionController do
|
||||
use ChesstrainerWeb, :controller
|
||||
|
||||
require Logger
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
alias ChesstrainerWeb.ClientAddress
|
||||
alias ChesstrainerWeb.LoginThrottle
|
||||
alias ChesstrainerWeb.UserAuth
|
||||
|
||||
def create(conn, %{"user" => user_params}) do
|
||||
authenticate(conn, user_params, ~p"/users/log-in", nil)
|
||||
end
|
||||
|
||||
def create_admin(conn, %{"user" => user_params}) do
|
||||
if ChesstrainerWeb.prelaunch?() do
|
||||
authenticate(conn, user_params, ~p"/admin/log-in", ~p"/admin/endgames")
|
||||
else
|
||||
authenticate(conn, user_params, ~p"/users/log-in", nil)
|
||||
defp authenticate(conn, user_params, failure_path, success_path) do
|
||||
%{"email" => login} = user_params
|
||||
address = ClientAddress.from_conn(conn)
|
||||
|
||||
case LoginThrottle.check(address, login) do
|
||||
:ok ->
|
||||
attempt_login(conn, address, user_params, failure_path, success_path)
|
||||
|
||||
{:throttled, bucket, retry_in_ms} ->
|
||||
log_auth_event("auth.login.throttled", address, reason: bucket)
|
||||
|
||||
conn
|
||||
|> put_flash(:error, throttle_message(retry_in_ms))
|
||||
|> redirect(to: failure_path)
|
||||
end
|
||||
end
|
||||
|
||||
defp authenticate(conn, user_params, failure_path, success_path) do
|
||||
defp attempt_login(conn, address, user_params, failure_path, success_path) do
|
||||
%{"email" => login, "password" => password} = user_params
|
||||
|
||||
case Accounts.get_user_by_login_and_password(login, password) do
|
||||
nil ->
|
||||
invalid_credentials(conn, login, failure_path)
|
||||
authentication_failed(conn, address, login, :invalid_credentials, failure_path)
|
||||
|
||||
user ->
|
||||
if user.confirmed_at do
|
||||
LoginThrottle.record_success(login)
|
||||
|
||||
conn
|
||||
|> maybe_put_return_to(success_path)
|
||||
|> put_flash(:info, "Welcome back!")
|
||||
|> UserAuth.log_in_user(user, user_params)
|
||||
else
|
||||
{:ok, _} =
|
||||
Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&url(~p"/users/confirm/#{&1}")
|
||||
)
|
||||
|
||||
# In order to prevent user enumeration attacks, report the same error
|
||||
# as invalid credentials.
|
||||
invalid_credentials(conn, login, failure_path)
|
||||
maybe_resend_confirmation(user, login)
|
||||
authentication_failed(conn, address, login, :unconfirmed, failure_path)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_resend_confirmation(user, login) do
|
||||
if LoginThrottle.claim_confirmation_resend(login) do
|
||||
case Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&url(~p"/users/confirm/#{&1}")
|
||||
) do
|
||||
{:ok, _email} -> :ok
|
||||
{:error, _reason} -> Logger.warning("auth.confirmation.resend_failed")
|
||||
end
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp authentication_failed(conn, address, login, reason, failure_path) do
|
||||
LoginThrottle.record_failure(address, login)
|
||||
log_auth_event("auth.login.failed", address, reason: reason)
|
||||
|
||||
# In order to prevent user enumeration attacks, report the same error as
|
||||
# invalid credentials.
|
||||
invalid_credentials(conn, login, failure_path)
|
||||
end
|
||||
|
||||
defp log_auth_event(message, address, metadata) do
|
||||
Logger.warning(message, Keyword.put(metadata, :ip, LoginThrottle.fingerprint(address)))
|
||||
end
|
||||
|
||||
defp throttle_message(retry_in_ms) do
|
||||
minutes = max(div(retry_in_ms + 59_999, 60_000), 1)
|
||||
unit = if minutes == 1, do: "minute", else: "minutes"
|
||||
|
||||
"Too many attempts. Try again in #{minutes} #{unit}."
|
||||
end
|
||||
|
||||
defp invalid_credentials(conn, login, path) do
|
||||
conn
|
||||
|> put_flash(:error, "Invalid email, username or password")
|
||||
|
||||
@@ -19,12 +19,18 @@ defmodule ChesstrainerWeb.Endpoint do
|
||||
#
|
||||
# When code reloading is disabled (e.g., in production),
|
||||
# the `gzip` option is enabled to serve compressed
|
||||
# static files generated by running `phx.digest`.
|
||||
# static files generated by running `phx.digest`, and the cache headers promise
|
||||
# a year. Build output is digested, and the stable-name assets (fonts, piece
|
||||
# art, icons) only change when the file is renamed, so a long max-age is safe
|
||||
# and keeps browsers and the CDN off the origin. Dev keeps plain `public` so
|
||||
# edits show up immediately.
|
||||
plug Plug.Static,
|
||||
at: "/",
|
||||
from: :chesstrainer,
|
||||
gzip: not code_reloading?,
|
||||
only: ChesstrainerWeb.static_paths(),
|
||||
cache_control_for_etags:
|
||||
if(code_reloading?, do: "public", else: "public, max-age=31536000, immutable"),
|
||||
raise_on_missing_only: code_reloading?
|
||||
|
||||
# Code reloading can be explicitly enabled under the
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Themes
|
||||
alias Chesstrainer.Themes.Theme
|
||||
|
||||
@category_options [
|
||||
{"Endgame", "endgame"},
|
||||
{"Opening", "opening"},
|
||||
{"Tactic", "tactic"}
|
||||
]
|
||||
|
||||
@kind_options [
|
||||
{"Technique", "technique"},
|
||||
{"Motif", "motif"},
|
||||
{"Material", "material"}
|
||||
]
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
{@page_title}
|
||||
<:subtitle>
|
||||
Themes group endgames for filtering. Names must be unique within a category,
|
||||
ignoring case. The slug is generated from the name and stays fixed afterwards,
|
||||
so links to a theme keep working when it is renamed.
|
||||
</:subtitle>
|
||||
</.header>
|
||||
|
||||
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save">
|
||||
<.input field={@form[:name]} type="text" label="Name" autocomplete="off" required />
|
||||
<.input
|
||||
field={@form[:kind]}
|
||||
type="select"
|
||||
label="Kind"
|
||||
options={@kind_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:category]}
|
||||
type="select"
|
||||
label="Category"
|
||||
options={@category_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:description]}
|
||||
type="textarea"
|
||||
label="Description"
|
||||
rows="3"
|
||||
/>
|
||||
|
||||
<footer>
|
||||
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
|
||||
<.button navigate={~p"/admin/themes"}>Cancel</.button>
|
||||
</footer>
|
||||
</.form>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(params, _session, socket) do
|
||||
{:ok, apply_action(socket, socket.assigns.live_action, params)}
|
||||
end
|
||||
|
||||
defp apply_action(socket, :new, _params) do
|
||||
theme = %Theme{}
|
||||
|
||||
socket
|
||||
|> assign(:page_title, "New theme")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:kind_options, @kind_options)
|
||||
|> assign(:category_options, @category_options)
|
||||
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||
end
|
||||
|
||||
defp apply_action(socket, :edit, %{"id" => id}) do
|
||||
theme = Themes.get_theme!(id)
|
||||
|
||||
socket
|
||||
|> assign(:page_title, "Edit theme")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:kind_options, @kind_options)
|
||||
|> assign(:category_options, @category_options)
|
||||
|> assign(:form, to_form(Themes.change_theme(theme)))
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("validate", %{"theme" => theme_params}, socket) do
|
||||
changeset =
|
||||
socket.assigns.theme
|
||||
|> Themes.change_theme(theme_params)
|
||||
|> Map.put(:action, :validate)
|
||||
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||
end
|
||||
|
||||
def handle_event("save", %{"theme" => theme_params}, socket) do
|
||||
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
|
||||
save_theme(socket, socket.assigns.live_action, theme_params)
|
||||
else
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||
end
|
||||
end
|
||||
|
||||
defp save_theme(socket, :new, theme_params) do
|
||||
case Themes.create_theme(socket.assigns.current_scope, theme_params) do
|
||||
{:ok, _theme} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Theme created successfully.")
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||
end
|
||||
end
|
||||
|
||||
defp save_theme(socket, :edit, theme_params) do
|
||||
case Themes.update_theme(socket.assigns.theme, theme_params) do
|
||||
{:ok, _theme} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Theme updated successfully.")
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,173 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@category_options [
|
||||
{"All categories", ""},
|
||||
{"Endgame", "endgame"},
|
||||
{"Opening", "opening"},
|
||||
{"Tactic", "tactic"}
|
||||
]
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Themes
|
||||
<:subtitle>
|
||||
Themes group endgames for filtering and puzzle selection. Coverage shows how
|
||||
many endgames carry a theme out of the whole library. Deleting a theme detaches
|
||||
it from every endgame and leaves the endgames intact.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button variant="primary" navigate={~p"/admin/themes/new"}>
|
||||
<.icon name="hero-plus" /> New theme
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.form
|
||||
for={@filter_form}
|
||||
id="theme-admin-filter-form"
|
||||
phx-change="filter"
|
||||
class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end"
|
||||
>
|
||||
<div class="flex-1 [&>div]:mb-0">
|
||||
<.input
|
||||
field={@filter_form[:search]}
|
||||
type="text"
|
||||
label="Search by name"
|
||||
autocomplete="off"
|
||||
phx-debounce="200"
|
||||
placeholder="Theme name…"
|
||||
/>
|
||||
</div>
|
||||
<div class="[&>div]:mb-0 sm:w-56">
|
||||
<.input
|
||||
field={@filter_form[:category]}
|
||||
type="select"
|
||||
label="Category"
|
||||
options={@category_options}
|
||||
/>
|
||||
</div>
|
||||
</.form>
|
||||
|
||||
<p :if={@themes == []} class="text-base-content/70">
|
||||
<%= if @has_filters do %>
|
||||
No themes match these filters.
|
||||
<% else %>
|
||||
No themes yet. Themes power endgame filtering and puzzle selection, so start by
|
||||
creating one and attaching it to an endgame.
|
||||
<% end %>
|
||||
</p>
|
||||
|
||||
<table :if={@themes != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kind</th>
|
||||
<th>Category</th>
|
||||
<th>Coverage</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="themes">
|
||||
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
|
||||
<td>{theme.name}</td>
|
||||
<td>{theme.kind}</td>
|
||||
<td>{theme.category}</td>
|
||||
<td>
|
||||
<span id={"theme-usage-#{theme.id}"}>
|
||||
{coverage_label(usage_count, @total_endgames)}
|
||||
</span>
|
||||
</td>
|
||||
<td class="w-0 font-semibold">
|
||||
<div class="flex gap-4">
|
||||
<.link
|
||||
:if={theme.category == :endgame and theme.kind == :technique}
|
||||
navigate={~p"/admin/themes/#{theme.id}/tag"}
|
||||
>
|
||||
Tag
|
||||
</.link>
|
||||
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
|
||||
<.link
|
||||
phx-click="delete"
|
||||
phx-value-id={theme.id}
|
||||
data-confirm={
|
||||
"Delete #{theme.name}? Used by #{coverage_label(usage_count, @total_endgames)}. " <>
|
||||
"The endgames will be kept and simply detached."
|
||||
}
|
||||
>
|
||||
Delete
|
||||
</.link>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Themes")
|
||||
|> assign(:search, "")
|
||||
|> assign(:category, "")
|
||||
|> assign(:has_filters, false)
|
||||
|> assign(:category_options, @category_options)
|
||||
|> assign(:filter_form, to_form(%{"search" => "", "category" => ""}))
|
||||
|> load_themes()}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("filter", params, socket) do
|
||||
search = Map.get(params, "search", socket.assigns.search)
|
||||
category = Map.get(params, "category", socket.assigns.category)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:search, search)
|
||||
|> assign(:category, category)
|
||||
|> assign(:has_filters, String.trim(search) != "" or category != "")
|
||||
|> load_themes()}
|
||||
end
|
||||
|
||||
def handle_event("delete", %{"id" => id}, socket) do
|
||||
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
|
||||
theme = Themes.get_theme!(id)
|
||||
{:ok, _theme} = Themes.delete_theme(theme)
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> put_flash(:info, "Theme deleted. Attached endgames were kept.")
|
||||
|> load_themes()
|
||||
|
||||
{:noreply, socket}
|
||||
else
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
|
||||
end
|
||||
end
|
||||
|
||||
defp load_themes(socket) do
|
||||
themes =
|
||||
Themes.list_themes_for_admin(
|
||||
search: socket.assigns.search,
|
||||
category: socket.assigns.category
|
||||
)
|
||||
|
||||
assign(socket, themes: themes, total_endgames: Endgames.count_endgames())
|
||||
end
|
||||
|
||||
defp coverage_label(count, total) do
|
||||
"#{count} of #{total} #{if total == 1, do: "endgame", else: "endgames"}"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,460 @@
|
||||
defmodule ChesstrainerWeb.Admin.ThemeLive.Tag do
|
||||
@moduledoc """
|
||||
Workspace for applying a technique theme to endgames by family.
|
||||
|
||||
Candidates are grouped by Key so an admin tags a whole family rather than
|
||||
individual rows. Boards are previews only; nothing here starts a puzzle.
|
||||
Only technique themes can be tagged, because material themes are derived and
|
||||
a hand-made link would be erased by the next refresh.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Game
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
import ChesstrainerWeb.Board.BoardComponent
|
||||
|
||||
@page_size 24
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Tag “{@theme.name}”
|
||||
<:subtitle>
|
||||
Pick a family, preview the positions and apply the theme in bulk. The links are
|
||||
recorded as curated, so derivation never overwrites them.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/themes"}>
|
||||
<.icon name="hero-arrow-left" /> All themes
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.form
|
||||
for={@theme_form}
|
||||
id="theme-workspace-form"
|
||||
phx-change="select_theme"
|
||||
class="mb-6 max-w-md"
|
||||
>
|
||||
<.input
|
||||
field={@theme_form[:theme_id]}
|
||||
type="select"
|
||||
label="Technique theme"
|
||||
options={@theme_options}
|
||||
/>
|
||||
</.form>
|
||||
|
||||
<div class="mb-6 flex flex-wrap gap-6 text-sm">
|
||||
<span>
|
||||
<span class="font-semibold" id="tagged-count">{@tagged_count}</span> tagged
|
||||
</span>
|
||||
<span>
|
||||
<span class="font-semibold" id="candidate-count">{@candidate_count}</span> candidates
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
:if={MapSet.size(@selected) > 0}
|
||||
id="selection-bar"
|
||||
class="sticky top-0 z-10 mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-primary/30 bg-base-100 p-3 text-sm"
|
||||
>
|
||||
<span class="font-semibold">{MapSet.size(@selected)} selected</span>
|
||||
<button
|
||||
type="button"
|
||||
id="apply-theme"
|
||||
phx-click="apply"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Apply “{@theme.name}”
|
||||
</button>
|
||||
<button type="button" phx-click="clear_selection" class="text-base-content/70">
|
||||
Clear selection
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section class="mb-12">
|
||||
<h2 class="mb-3 text-lg font-semibold">Candidates</h2>
|
||||
<p :if={@candidate_groups == []} class="text-base-content/70">
|
||||
Every endgame already carries this theme.
|
||||
</p>
|
||||
|
||||
<table :if={@candidate_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @candidate_groups} id={"candidates-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-candidates-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="candidates"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "candidates")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "candidates"}
|
||||
view="candidates"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 class="mb-3 text-lg font-semibold">Curated links</h2>
|
||||
<p :if={@tagged_groups == []} class="text-base-content/70">
|
||||
No endgame carries this theme yet.
|
||||
</p>
|
||||
|
||||
<table :if={@tagged_groups != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Key</th>
|
||||
<th>Endgames</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={{key, count} <- @tagged_groups} id={"tagged-#{group_id(key)}"}>
|
||||
<td class="font-mono">{key}</td>
|
||||
<td>{count}</td>
|
||||
<td class="w-0">
|
||||
<button
|
||||
type="button"
|
||||
id={"toggle-tagged-#{group_id(key)}"}
|
||||
phx-click="toggle_group"
|
||||
phx-value-key={key}
|
||||
phx-value-view="tagged"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
{open_label(@open, key, "tagged")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<.group_panel
|
||||
:if={@open && @open.view == "tagged"}
|
||||
view="tagged"
|
||||
group={@open.key}
|
||||
items={@items}
|
||||
selected={@selected}
|
||||
page={@page}
|
||||
pages={@pages}
|
||||
/>
|
||||
</section>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
attr :view, :string, required: true
|
||||
attr :group, :string, required: true
|
||||
attr :items, :list, required: true
|
||||
attr :selected, :any, required: true
|
||||
attr :page, :integer, required: true
|
||||
attr :pages, :integer, required: true
|
||||
|
||||
defp group_panel(assigns) do
|
||||
~H"""
|
||||
<div id="group-panel" class="mt-4">
|
||||
<div :if={@view == "candidates"} class="mb-3 flex gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
id="select-page"
|
||||
phx-click="select_page"
|
||||
class="font-semibold text-primary-text"
|
||||
>
|
||||
Select this page
|
||||
</button>
|
||||
<span class="text-base-content/60">{@group}</span>
|
||||
</div>
|
||||
|
||||
<p :if={@items == []} class="text-base-content/70">No endgames on this page.</p>
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div
|
||||
:for={endgame <- @items}
|
||||
id={"endgame-#{endgame.id}"}
|
||||
class="rounded-lg border border-base-300 p-3"
|
||||
>
|
||||
<.board
|
||||
game={endgame.game}
|
||||
myself={nil}
|
||||
interactive={false}
|
||||
class="mb-2 w-full max-w-[240px]"
|
||||
/>
|
||||
<p class="break-all font-mono text-xs text-base-content/60">{endgame.fen}</p>
|
||||
|
||||
<label :if={@view == "candidates"} class="mt-2 flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={"select-#{endgame.id}"}
|
||||
checked={MapSet.member?(@selected, endgame.id)}
|
||||
phx-click="toggle_select"
|
||||
phx-value-id={endgame.id}
|
||||
/> Select
|
||||
</label>
|
||||
|
||||
<button
|
||||
:if={@view == "tagged"}
|
||||
type="button"
|
||||
id={"remove-#{endgame.id}"}
|
||||
phx-click="remove"
|
||||
phx-value-id={endgame.id}
|
||||
class="mt-2 text-sm font-semibold text-error"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div :if={@pages > 1} class="mt-4 flex items-center gap-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page - 1}
|
||||
disabled={@page <= 1}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span>Page {@page} of {@pages}</span>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="page"
|
||||
phx-value-page={@page + 1}
|
||||
disabled={@page >= @pages}
|
||||
class="font-semibold disabled:opacity-40"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(%{"id" => id}, _session, socket) do
|
||||
theme = Themes.get_theme!(id)
|
||||
|
||||
if theme.category == :endgame and theme.kind == :technique do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Tag #{theme.name}")
|
||||
|> assign(:theme, theme)
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(:open, nil)
|
||||
|> assign(:items, [])
|
||||
|> assign(:page, 1)
|
||||
|> assign(:pages, 1)
|
||||
|> assign_theme_options()
|
||||
|> load_counts()}
|
||||
else
|
||||
{:ok,
|
||||
socket
|
||||
|> put_flash(
|
||||
:error,
|
||||
"Only technique themes can be tagged by hand; material themes are derived."
|
||||
)
|
||||
|> push_navigate(to: ~p"/admin/themes")}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("select_theme", %{"theme_id" => id}, socket) do
|
||||
if to_string(socket.assigns.theme.id) == id do
|
||||
{:noreply, socket}
|
||||
else
|
||||
{:noreply, push_navigate(socket, to: ~p"/admin/themes/#{id}/tag")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_group", %{"key" => key, "view" => view}, socket) do
|
||||
case socket.assigns.open do
|
||||
%{key: ^key, view: ^view} ->
|
||||
{:noreply, assign(socket, open: nil, items: [], page: 1, pages: 1)}
|
||||
|
||||
_ ->
|
||||
{:noreply, open_group(socket, key, view, 1)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("page", %{"page" => page}, socket) do
|
||||
case socket.assigns.open do
|
||||
nil ->
|
||||
{:noreply, socket}
|
||||
|
||||
%{key: key, view: view} ->
|
||||
{:noreply, open_group(socket, key, view, parse_page(page))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_select", %{"id" => id}, socket) do
|
||||
selected =
|
||||
if MapSet.member?(socket.assigns.selected, id) do
|
||||
MapSet.delete(socket.assigns.selected, id)
|
||||
else
|
||||
MapSet.put(socket.assigns.selected, id)
|
||||
end
|
||||
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("select_page", _params, socket) do
|
||||
page_ids = Enum.map(socket.assigns.items, & &1.id)
|
||||
selected = Enum.reduce(page_ids, socket.assigns.selected, &MapSet.put(&2, &1))
|
||||
{:noreply, assign(socket, :selected, selected)}
|
||||
end
|
||||
|
||||
def handle_event("clear_selection", _params, socket) do
|
||||
{:noreply, assign(socket, :selected, MapSet.new())}
|
||||
end
|
||||
|
||||
def handle_event("apply", _params, socket) do
|
||||
selected = MapSet.to_list(socket.assigns.selected)
|
||||
|
||||
if selected == [] do
|
||||
{:noreply, put_flash(socket, :error, "Select at least one endgame.")}
|
||||
else
|
||||
{:ok, count} = Themes.tag_endgames(socket.assigns.theme, selected, :curated)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Tagged #{count} endgame(s) with “#{socket.assigns.theme.name}”.")
|
||||
|> assign(:selected, MapSet.new())
|
||||
|> assign(open: nil, items: [], page: 1, pages: 1)
|
||||
|> load_counts()}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("remove", %{"id" => id}, socket) do
|
||||
{:ok, removed} = Themes.untag_endgame(socket.assigns.theme, id, :curated)
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> put_flash(:info, removal_message(removed, socket.assigns.theme))
|
||||
|> load_counts()
|
||||
|> refresh_open()
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
defp removal_message(0, theme), do: "That endgame had no curated “#{theme.name}” link."
|
||||
defp removal_message(_, theme), do: "Removed “#{theme.name}” from the endgame."
|
||||
|
||||
defp refresh_open(%{assigns: %{open: nil}} = socket), do: socket
|
||||
|
||||
defp refresh_open(%{assigns: %{open: %{key: key, view: view}, page: page}} = socket) do
|
||||
open_group(socket, key, view, page)
|
||||
end
|
||||
|
||||
defp open_group(socket, key, view, page) do
|
||||
count = group_count(socket, key, view)
|
||||
pages = max(ceil_div(count, @page_size), 1)
|
||||
page = page |> max(1) |> min(pages)
|
||||
|
||||
endgames =
|
||||
Endgames.list_endgames_for_key(key, filters_for(socket.assigns.theme, view),
|
||||
limit: @page_size,
|
||||
offset: (page - 1) * @page_size
|
||||
)
|
||||
|> Enum.map(&Map.put(&1, :game, board_game(&1.fen)))
|
||||
|
||||
assign(socket,
|
||||
open: %{key: key, view: view},
|
||||
items: endgames,
|
||||
page: page,
|
||||
pages: pages
|
||||
)
|
||||
end
|
||||
|
||||
defp filters_for(%{id: theme_id}, "tagged"), do: %{with_theme: {theme_id, :curated}}
|
||||
defp filters_for(%{id: theme_id}, "candidates"), do: %{without_theme: theme_id}
|
||||
|
||||
defp group_count(socket, key, view) do
|
||||
groups =
|
||||
if view == "tagged", do: socket.assigns.tagged_groups, else: socket.assigns.candidate_groups
|
||||
|
||||
Enum.find_value(groups, 0, fn
|
||||
{^key, count} -> count
|
||||
_ -> nil
|
||||
end)
|
||||
end
|
||||
|
||||
defp parse_page(page) when is_integer(page), do: page
|
||||
|
||||
defp parse_page(page) when is_binary(page) do
|
||||
case Integer.parse(page) do
|
||||
{value, _} -> value
|
||||
:error -> 1
|
||||
end
|
||||
end
|
||||
|
||||
defp ceil_div(0, _), do: 0
|
||||
defp ceil_div(count, size), do: div(count + size - 1, size)
|
||||
|
||||
defp load_counts(socket) do
|
||||
theme = socket.assigns.theme
|
||||
tagged = Endgames.list_key_groups(%{with_theme: {theme.id, :curated}})
|
||||
candidates = Endgames.list_key_groups(%{without_theme: theme.id})
|
||||
|
||||
assign(socket,
|
||||
tagged_groups: tagged,
|
||||
candidate_groups: candidates,
|
||||
tagged_count: total(tagged),
|
||||
candidate_count: total(candidates)
|
||||
)
|
||||
end
|
||||
|
||||
defp total(groups), do: Enum.reduce(groups, 0, fn {_key, count}, acc -> acc + count end)
|
||||
|
||||
defp assign_theme_options(socket) do
|
||||
options =
|
||||
Themes.list_themes()
|
||||
|> Enum.filter(&(&1.category == :endgame and &1.kind == :technique))
|
||||
|> Enum.sort_by(& &1.name)
|
||||
|> Enum.map(&{&1.name, &1.id})
|
||||
|
||||
assign(socket,
|
||||
theme_options: options,
|
||||
theme_form: to_form(%{"theme_id" => to_string(socket.assigns.theme.id)})
|
||||
)
|
||||
end
|
||||
|
||||
defp board_game(fen) do
|
||||
case Game.game_from_fen(fen, :endgame) do
|
||||
{:ok, game} -> game
|
||||
{:error, :invalid_fen, game} -> game
|
||||
end
|
||||
end
|
||||
|
||||
defp open_label(%{key: key, view: view}, key, view), do: "Hide"
|
||||
defp open_label(_open, _key, _view), do: "Show"
|
||||
|
||||
defp group_id(key), do: String.replace(key, ~r/[^A-Za-z0-9]+/, "-")
|
||||
end
|
||||
@@ -0,0 +1,177 @@
|
||||
defmodule ChesstrainerWeb.Admin.UserLive.Index do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
|
||||
@per_page 25
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Users
|
||||
<:subtitle>
|
||||
Search accounts, review their roles and plans, and open a user to edit them.
|
||||
Admins only see members and moderators.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button variant="primary" navigate={~p"/admin/users/new"}>
|
||||
<.icon name="hero-plus" /> Invite user
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.form for={@filter_form} id="admin-user-search-form" phx-change="search" class="mb-6">
|
||||
<.input
|
||||
field={@filter_form[:search]}
|
||||
type="search"
|
||||
label="Search by email or username"
|
||||
autocomplete="off"
|
||||
phx-debounce="200"
|
||||
placeholder="email or username…"
|
||||
/>
|
||||
</.form>
|
||||
|
||||
<p :if={@users == []} class="text-base-content/70">
|
||||
<%= if @search == "" do %>
|
||||
No users are visible to you yet.
|
||||
<% else %>
|
||||
No users match “{@search}”.
|
||||
<% end %>
|
||||
</p>
|
||||
|
||||
<table :if={@users != []} class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Plan</th>
|
||||
<th>Confirmed</th>
|
||||
<th>Created</th>
|
||||
<th><span class="sr-only">Actions</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="admin-users">
|
||||
<tr :for={user <- @users} id={"user-" <> user.id}>
|
||||
<td>{user.username}</td>
|
||||
<td>{user.email}</td>
|
||||
<td>{user.role}</td>
|
||||
<td>{user.plan}</td>
|
||||
<td>{confirmed_label(user)}</td>
|
||||
<td>{format_date(user.inserted_at)}</td>
|
||||
<td class="w-0 font-semibold">
|
||||
<.link navigate={~p"/admin/users/#{user.id}"}>View</.link>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="mt-4 flex flex-wrap items-center justify-between gap-3 text-sm text-base-content/70">
|
||||
<p>
|
||||
Page {@page} of {@total_pages} · {@count} {if @count == 1, do: "user", else: "users"}
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<.button
|
||||
:if={@page > 1}
|
||||
variant="secondary"
|
||||
phx-click="previous_page"
|
||||
id="previous-page"
|
||||
>
|
||||
Previous
|
||||
</.button>
|
||||
<.button
|
||||
:if={@page < @total_pages}
|
||||
variant="secondary"
|
||||
phx-click="next_page"
|
||||
id="next-page"
|
||||
>
|
||||
Next
|
||||
</.button>
|
||||
</div>
|
||||
</div>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
socket =
|
||||
socket
|
||||
|> assign(:page_title, "Users")
|
||||
|> assign(:search, "")
|
||||
|> assign(:page, 1)
|
||||
|> assign(:users, [])
|
||||
|> assign(:count, 0)
|
||||
|> assign(:total_pages, 1)
|
||||
|> assign(:filter_form, to_form(%{"search" => ""}))
|
||||
|
||||
case load_users(socket) do
|
||||
{:ok, socket} -> {:ok, socket}
|
||||
{:error, :unauthorized} -> {:ok, redirect_unauthorized(socket)}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("search", %{"search" => search}, socket) do
|
||||
case load_users(assign(socket, search: search, page: 1)) do
|
||||
{:ok, socket} -> {:noreply, socket}
|
||||
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("previous_page", _params, socket) do
|
||||
case load_users(assign(socket, :page, max(socket.assigns.page - 1, 1))) do
|
||||
{:ok, socket} -> {:noreply, socket}
|
||||
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("next_page", _params, socket) do
|
||||
case load_users(assign(socket, :page, socket.assigns.page + 1)) do
|
||||
{:ok, socket} -> {:noreply, socket}
|
||||
{:error, :unauthorized} -> {:noreply, redirect_unauthorized(socket)}
|
||||
end
|
||||
end
|
||||
|
||||
defp load_users(socket) do
|
||||
scope = socket.assigns.current_scope
|
||||
search = socket.assigns.search
|
||||
|
||||
case Accounts.count_users_for_admin(scope, search: search) do
|
||||
{:ok, count} ->
|
||||
total_pages = max(div(count + @per_page - 1, @per_page), 1)
|
||||
page = min(socket.assigns.page, total_pages)
|
||||
|
||||
case Accounts.list_users_for_admin(scope, search: search, page: page) do
|
||||
{:ok, users} ->
|
||||
{:ok,
|
||||
assign(socket, users: users, count: count, total_pages: total_pages, page: page)}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
|
||||
defp redirect_unauthorized(socket) do
|
||||
socket
|
||||
|> put_flash(:error, "You are not authorized to manage users.")
|
||||
|> push_navigate(to: ~p"/")
|
||||
end
|
||||
|
||||
defp confirmed_label(%{confirmed_at: nil}), do: "No"
|
||||
defp confirmed_label(_user), do: "Yes"
|
||||
|
||||
defp format_date(nil), do: ""
|
||||
|
||||
defp format_date(%DateTime{} = datetime) do
|
||||
Calendar.strftime(datetime, "%Y-%m-%d")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
defmodule ChesstrainerWeb.Admin.UserLive.New do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Role
|
||||
alias Chesstrainer.Accounts.User
|
||||
|
||||
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Invite user
|
||||
<:subtitle>
|
||||
We create the account and email a link so the recipient can choose a password.
|
||||
The invite is confirmed immediately, so no separate confirmation step is needed.
|
||||
</:subtitle>
|
||||
</.header>
|
||||
|
||||
<.form for={@form} id="invite-user-form" phx-change="validate" phx-submit="save">
|
||||
<.input
|
||||
field={@form[:email]}
|
||||
type="email"
|
||||
label="Email"
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
<.input
|
||||
field={@form[:username]}
|
||||
type="text"
|
||||
label="Username"
|
||||
autocomplete="off"
|
||||
required
|
||||
/>
|
||||
<.input
|
||||
field={@form[:role]}
|
||||
type="select"
|
||||
label="Role"
|
||||
options={@role_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:plan]}
|
||||
type="select"
|
||||
label="Plan"
|
||||
options={@plan_options}
|
||||
/>
|
||||
|
||||
<footer>
|
||||
<.button phx-disable-with="Sending..." variant="primary">Send invitation</.button>
|
||||
<.button navigate={~p"/admin/users"}>Cancel</.button>
|
||||
</footer>
|
||||
</.form>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Invite user")
|
||||
|> assign(:role_options, role_options(socket.assigns.current_scope))
|
||||
|> assign(:plan_options, @plan_options)
|
||||
|> assign(
|
||||
:form,
|
||||
to_form(%{"email" => "", "username" => "", "role" => "member", "plan" => "free"},
|
||||
as: :user
|
||||
)
|
||||
)}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("validate", %{"user" => user_params}, socket) do
|
||||
changeset =
|
||||
%User{}
|
||||
|> User.invite_changeset(user_params)
|
||||
|> User.admin_changeset(user_params)
|
||||
|> Map.put(:action, :validate)
|
||||
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||
end
|
||||
|
||||
def handle_event("save", %{"user" => user_params}, socket) do
|
||||
case Accounts.invite_user_as_admin(
|
||||
socket.assigns.current_scope,
|
||||
user_params,
|
||||
&url(~p"/users/reset-password/#{&1}")
|
||||
) do
|
||||
{:ok, user} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Invitation sent to #{user.email}.")
|
||||
|> push_navigate(to: ~p"/admin/users")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to assign that role.")}
|
||||
|
||||
{:error, _reason} ->
|
||||
{:noreply,
|
||||
put_flash(socket, :error, "The invitation could not be sent. Please try again.")}
|
||||
end
|
||||
end
|
||||
|
||||
defp role_options(scope) do
|
||||
for role <- Role.values(),
|
||||
Policy.can_assign_role?(scope, role),
|
||||
do: {role_label(role), role}
|
||||
end
|
||||
|
||||
defp role_label(:super_admin), do: "Super admin"
|
||||
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
|
||||
end
|
||||
@@ -0,0 +1,228 @@
|
||||
defmodule ChesstrainerWeb.Admin.UserLive.Show do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Accounts
|
||||
alias Chesstrainer.Accounts.Policy
|
||||
alias Chesstrainer.Accounts.Role
|
||||
|
||||
@plan_options [{"Free", "free"}, {"Premium", "premium"}]
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<div id="admin-user-page">
|
||||
<.header>
|
||||
{@user.username}
|
||||
<:subtitle>Account details and administrator controls.</:subtitle>
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/users"}>
|
||||
<.icon name="hero-arrow-left" /> All users
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<.list>
|
||||
<:item title="Email">{@user.email}</:item>
|
||||
<:item title="Username">{@user.username}</:item>
|
||||
<:item title="Role">{@user.role}</:item>
|
||||
<:item title="Plan">{@user.plan}</:item>
|
||||
<:item title="Confirmed">{confirmed_label(@user)}</:item>
|
||||
<:item title="Rating">{round(@user.rating)}</:item>
|
||||
<:item title="Created">{format_datetime(@user.inserted_at)}</:item>
|
||||
<:item title="Last updated">{format_datetime(@user.updated_at)}</:item>
|
||||
</.list>
|
||||
|
||||
<section class="mt-8">
|
||||
<h2 class="text-lg font-semibold">Role and plan</h2>
|
||||
|
||||
<.form
|
||||
:if={@can_manage}
|
||||
for={@form}
|
||||
id="admin-user-form"
|
||||
phx-change="validate"
|
||||
phx-submit="save"
|
||||
class="mt-4"
|
||||
>
|
||||
<.input
|
||||
field={@form[:role]}
|
||||
type="select"
|
||||
label="Role"
|
||||
options={@role_options}
|
||||
/>
|
||||
<.input
|
||||
field={@form[:plan]}
|
||||
type="select"
|
||||
label="Plan"
|
||||
options={@plan_options}
|
||||
/>
|
||||
|
||||
<footer>
|
||||
<.button phx-disable-with="Saving..." variant="primary">Save changes</.button>
|
||||
</footer>
|
||||
</.form>
|
||||
|
||||
<p :if={!@can_manage} class="mt-4 text-sm text-base-content/70">
|
||||
You can view this account but not change its role or plan.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section :if={@can_manage} class="mt-8 border-t border-base-200 pt-6">
|
||||
<h2 class="text-lg font-semibold">Account emails</h2>
|
||||
<p class="mt-1 text-sm text-base-content/70">
|
||||
These actions send email through the configured mailer. In development the messages
|
||||
appear in the Swoosh mailbox at <code>/dev/mailbox</code>.
|
||||
</p>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button
|
||||
:if={is_nil(@user.confirmed_at)}
|
||||
variant="secondary"
|
||||
phx-click="resend_confirmation"
|
||||
id="resend-confirmation"
|
||||
>
|
||||
Resend confirmation email
|
||||
</.button>
|
||||
<.button
|
||||
variant="secondary"
|
||||
phx-click="send_password_reset"
|
||||
id="send-password-reset"
|
||||
>
|
||||
Send password reset email
|
||||
</.button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(%{"id" => id}, _session, socket) do
|
||||
case Accounts.get_user_for_admin(socket.assigns.current_scope, id) do
|
||||
{:ok, user} ->
|
||||
{:ok, assign_user(socket, user)}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:ok,
|
||||
socket
|
||||
|> put_flash(:error, "You are not authorized to view that user.")
|
||||
|> push_navigate(to: ~p"/admin/users")}
|
||||
|
||||
{:error, :not_found} ->
|
||||
{:ok,
|
||||
socket
|
||||
|> put_flash(:error, "User not found.")
|
||||
|> push_navigate(to: ~p"/admin/users")}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("validate", %{"user" => user_params}, socket) do
|
||||
if socket.assigns.can_manage do
|
||||
changeset =
|
||||
socket.assigns.user
|
||||
|> Accounts.change_user_as_admin(user_params)
|
||||
|> Map.put(:action, :validate)
|
||||
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
|
||||
else
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("save", %{"user" => user_params}, socket) do
|
||||
case Accounts.update_user_as_admin(
|
||||
socket.assigns.current_scope,
|
||||
socket.assigns.user,
|
||||
user_params
|
||||
) do
|
||||
{:ok, user} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign_user(user)
|
||||
|> put_flash(:info, "User updated successfully.")}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to modify this user.")}
|
||||
|
||||
{:error, :own_role} ->
|
||||
{:noreply, put_flash(socket, :error, "You cannot change your own role.")}
|
||||
|
||||
{:error, :last_super_admin} ->
|
||||
{:noreply, put_flash(socket, :error, "You cannot demote the last super admin.")}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("resend_confirmation", _params, socket) do
|
||||
case Accounts.resend_user_confirmation_instructions_as_admin(
|
||||
socket.assigns.current_scope,
|
||||
socket.assigns.user,
|
||||
&url(~p"/users/confirm/#{&1}")
|
||||
) do
|
||||
{:ok, _email} ->
|
||||
{:noreply, put_flash(socket, :info, "Confirmation email sent.")}
|
||||
|
||||
{:error, :already_confirmed} ->
|
||||
{:noreply, put_flash(socket, :error, "That account is already confirmed.")}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
|
||||
|
||||
{:error, _reason} ->
|
||||
{:noreply, put_flash(socket, :error, "The confirmation email could not be sent.")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("send_password_reset", _params, socket) do
|
||||
case Accounts.send_user_reset_password_instructions_as_admin(
|
||||
socket.assigns.current_scope,
|
||||
socket.assigns.user,
|
||||
&url(~p"/users/reset-password/#{&1}")
|
||||
) do
|
||||
{:ok, _email} ->
|
||||
{:noreply, put_flash(socket, :info, "Password reset email sent.")}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:noreply, put_flash(socket, :error, "You are not authorized to email this user.")}
|
||||
|
||||
{:error, _reason} ->
|
||||
{:noreply, put_flash(socket, :error, "The password reset email could not be sent.")}
|
||||
end
|
||||
end
|
||||
|
||||
defp assign_user(socket, user) do
|
||||
can_manage = Policy.can_manage_user?(socket.assigns.current_scope, user)
|
||||
|
||||
socket
|
||||
|> assign(:page_title, user.username)
|
||||
|> assign(:user, user)
|
||||
|> assign(:can_manage, can_manage)
|
||||
|> assign(:plan_options, @plan_options)
|
||||
|> assign(:role_options, role_options(socket.assigns.current_scope))
|
||||
|> assign(:form, to_form(Accounts.change_user_as_admin(user)))
|
||||
end
|
||||
|
||||
defp role_options(scope) do
|
||||
for role <- Role.values(),
|
||||
Policy.can_assign_role?(scope, role),
|
||||
do: {role_label(role), role}
|
||||
end
|
||||
|
||||
defp role_label(:super_admin), do: "Super admin"
|
||||
defp role_label(role), do: role |> Atom.to_string() |> String.capitalize()
|
||||
|
||||
defp confirmed_label(%{confirmed_at: nil}), do: "No"
|
||||
defp confirmed_label(_user), do: "Yes"
|
||||
|
||||
defp format_datetime(nil), do: "—"
|
||||
|
||||
defp format_datetime(%DateTime{} = datetime) do
|
||||
Calendar.strftime(datetime, "%Y-%m-%d %H:%M UTC")
|
||||
end
|
||||
end
|
||||
@@ -8,72 +8,19 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
|
||||
import ChesstrainerWeb.Board.BoardComponent
|
||||
import ChesstrainerWeb.ThemePicker
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
{@page_title}
|
||||
<:subtitle>Use this form to manage endgame records in your database.</:subtitle>
|
||||
</.header>
|
||||
|
||||
<div class="mb-6">
|
||||
<span class="mb-1 block text-sm font-medium text-base-content">Themes</span>
|
||||
|
||||
<div class="flex flex-wrap gap-2 mb-2">
|
||||
<.badge :for={theme <- @selected_themes} color="primary">
|
||||
{theme.name}
|
||||
<button
|
||||
type="button"
|
||||
phx-click="remove_theme"
|
||||
phx-value-id={theme.id}
|
||||
aria-label={"Remove #{theme.name}"}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</.badge>
|
||||
</div>
|
||||
|
||||
<form
|
||||
id="theme-form"
|
||||
phx-change="search_themes"
|
||||
phx-submit="create_theme_from_search"
|
||||
>
|
||||
<.input
|
||||
name="theme_search"
|
||||
value={@theme_query}
|
||||
phx-debounce="200"
|
||||
autocomplete="off"
|
||||
placeholder="Search or create a theme…"
|
||||
/>
|
||||
|
||||
<ul class="mt-2 w-full rounded-md border border-base-300 bg-base-100 p-1 shadow-sm">
|
||||
<li :for={theme <- @theme_results}>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="add_theme"
|
||||
phx-value-id={theme.id}
|
||||
class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-base-200"
|
||||
>
|
||||
{theme.name}
|
||||
</button>
|
||||
</li>
|
||||
|
||||
<li :if={@can_create}>
|
||||
<button
|
||||
type="button"
|
||||
phx-click="create_theme"
|
||||
phx-value-name={@theme_query}
|
||||
class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-base-200"
|
||||
>
|
||||
Create theme "{String.trim(@theme_query)}"
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<.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">
|
||||
@@ -85,6 +32,14 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
value={rating_display(@form[:rating])}
|
||||
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
|
||||
@@ -167,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)}
|
||||
@@ -229,46 +180,6 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
end
|
||||
end
|
||||
|
||||
defp assign_search(socket, query) do
|
||||
trimmed = String.trim(query)
|
||||
results = Themes.search(query, "endgame")
|
||||
|
||||
can_create =
|
||||
trimmed != "" and
|
||||
not Enum.any?(results, &(String.downcase(&1.name) == String.downcase(trimmed)))
|
||||
|
||||
socket
|
||||
|> assign(:theme_query, query)
|
||||
|> assign(:theme_results, results)
|
||||
|> assign(:can_create, can_create)
|
||||
end
|
||||
|
||||
defp create_theme(socket, name) do
|
||||
if String.trim(name) == "" do
|
||||
socket
|
||||
else
|
||||
case Themes.get_or_create(name, "endgame") do
|
||||
{:ok, theme} -> socket |> add_selected_theme(theme) |> clear_search()
|
||||
{:error, _reason} -> put_flash(socket, :error, "Could not create that theme.")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp clear_search(socket) do
|
||||
socket
|
||||
|> assign(:theme_query, "")
|
||||
|> assign(:theme_results, [])
|
||||
|> assign(:can_create, false)
|
||||
end
|
||||
|
||||
defp add_selected_theme(socket, theme) do
|
||||
if Enum.any?(socket.assigns.selected_themes, &(&1.id == theme.id)) do
|
||||
socket
|
||||
else
|
||||
assign(socket, :selected_themes, socket.assigns.selected_themes ++ [theme])
|
||||
end
|
||||
end
|
||||
|
||||
# Ratings are stored as floats (Glicko); the admin form presents them as whole numbers.
|
||||
defp rating_display(%Phoenix.HTML.FormField{value: value}) when is_float(value),
|
||||
do: round(value)
|
||||
@@ -278,13 +189,8 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
|
||||
# Shows the position as the admin types a FEN; hidden while the FEN is invalid or blank.
|
||||
# Parses directly rather than through Game.game_from_fen/2 so keystrokes never probe a tablebase.
|
||||
defp preview_game(fen) when is_binary(fen) do
|
||||
case Chex.Parser.FEN.parse(fen) do
|
||||
{:ok, game} ->
|
||||
%{board: game.board, orientation: game.active_color, move_from_square: nil}
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
{:ok, game} = Chex.Parser.FEN.parse(fen)
|
||||
%{board: game.board, orientation: game.active_color, move_from_square: nil}
|
||||
rescue
|
||||
MatchError -> nil
|
||||
end
|
||||
|
||||
@@ -14,6 +14,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.GuestLimits
|
||||
alias ChesstrainerWeb.ClientAddress
|
||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||
alias ChesstrainerWeb.PlayComponents
|
||||
|
||||
@@ -69,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}
|
||||
@@ -93,32 +94,65 @@ 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
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
socket = assign(socket, :limit, GuestLimits.limit())
|
||||
socket =
|
||||
socket
|
||||
|> assign(:limit, GuestLimits.limit())
|
||||
|> assign(:served_ids, [])
|
||||
|
||||
cond do
|
||||
signed_in?(socket) ->
|
||||
{:ok, redirect(socket, to: ~p"/train")}
|
||||
|
||||
connected?(socket) ->
|
||||
take_puzzle(socket, client_address(socket))
|
||||
take_puzzle(socket, ClientAddress.from_socket(socket))
|
||||
|
||||
true ->
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:loading, true)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:guest_address, nil)}
|
||||
@@ -126,29 +160,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
|
||||
|
||||
@@ -192,74 +211,78 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
|
||||
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
|
||||
|
||||
defp next_puzzle(socket) do
|
||||
case GuestLimits.remaining(socket.assigns.guest_address) do
|
||||
{:limit_reached, retry_ms} ->
|
||||
socket
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:limit_reached, retry_ms)
|
||||
|
||||
{:ok, _remaining} ->
|
||||
case random_unserved(socket) do
|
||||
nil -> assign(socket, :empty, :exhausted)
|
||||
endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
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 random_unserved(socket) do
|
||||
nil -> {:ok, empty_pool(socket, address)}
|
||||
endgame -> {:ok, start_guest_puzzle(socket, address, endgame)}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Prefer an endgame this visitor has not seen in this session. Once the whole
|
||||
# pool is served — only possible on a very long guest session — start over
|
||||
# rather than dead-end.
|
||||
defp random_unserved(socket) do
|
||||
Endgames.random_endgame(exclude_ids: socket.assigns.served_ids) ||
|
||||
Endgames.random_endgame()
|
||||
end
|
||||
|
||||
defp start_guest_puzzle(socket, address, endgame) 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)}
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:empty, nil)
|
||||
|> assign(:served_ids, [endgame.id | socket.assigns.served_ids])
|
||||
|> PlayCore.init(endgame, page_title: "Train")
|
||||
|
||||
{: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)}
|
||||
limit_wall(socket, address, retry_ms)
|
||||
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")
|
||||
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 client_address(socket) do
|
||||
if GuestLimits.trust_forwarded_for?() do
|
||||
forwarded_address(socket) || peer_address(socket)
|
||||
else
|
||||
peer_address(socket)
|
||||
end
|
||||
end
|
||||
|
||||
defp peer_address(socket) do
|
||||
case get_connect_info(socket, :peer_data) do
|
||||
%{address: address} -> address
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp forwarded_address(socket) do
|
||||
with headers when is_list(headers) <- get_connect_info(socket, :x_headers),
|
||||
{_, value} <- List.keyfind(headers, "x-forwarded-for", 0),
|
||||
address when address != nil <- parse_address(value) do
|
||||
address
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
# The rightmost entry is the one our own proxy appended.
|
||||
defp parse_address(value) do
|
||||
value
|
||||
|> String.split(",")
|
||||
|> List.last()
|
||||
|> to_string()
|
||||
|> String.trim()
|
||||
|> String.to_charlist()
|
||||
|> :inet.parse_address()
|
||||
|> case do
|
||||
{:ok, address} -> address
|
||||
{:error, _} -> 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
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
defmodule ChesstrainerWeb.EndgameLive.Import do
|
||||
@moduledoc """
|
||||
Bulk FEN importer for the admin endgame section.
|
||||
|
||||
Pasted FENs are validated and probed against the local Syzygy tablebase only;
|
||||
the remote (Lichess) fallback is deliberately not used here.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
require Logger
|
||||
|
||||
alias Chesstrainer.Endgames.BulkImport
|
||||
alias Chesstrainer.Endgames.Tablebase.Local
|
||||
|
||||
import ChesstrainerWeb.ThemePicker
|
||||
|
||||
@default_rating 1500
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Import endgames
|
||||
<:subtitle>
|
||||
Paste one FEN per line. Results are read from the local Syzygy tablebase,
|
||||
so positions must have five pieces or fewer.
|
||||
</:subtitle>
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/endgames"}>
|
||||
<.icon name="hero-arrow-left" /> All endgames
|
||||
</.button>
|
||||
</:actions>
|
||||
</.header>
|
||||
|
||||
<p
|
||||
id="tablebase-status"
|
||||
class={[
|
||||
"mb-6 rounded-md border px-4 py-3 text-sm",
|
||||
match?({:ok, _}, @tablebase_status) && "border-success/30 bg-success/10 text-success-text",
|
||||
match?({:error, _}, @tablebase_status) &&
|
||||
"border-warning/30 bg-warning/10 text-warning-text"
|
||||
]}
|
||||
>
|
||||
{elem(@tablebase_status, 1)}
|
||||
</p>
|
||||
|
||||
<form id="endgame-import-form" phx-submit="lookup" class="space-y-4">
|
||||
<.input
|
||||
id="import-fens"
|
||||
name="fens"
|
||||
type="textarea"
|
||||
label="FENs"
|
||||
value={@fen_text}
|
||||
rows="10"
|
||||
class="font-mono"
|
||||
placeholder="8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||
autocomplete="off"
|
||||
/>
|
||||
|
||||
<div class="sm:w-56">
|
||||
<.input
|
||||
id="import-rating"
|
||||
name="rating"
|
||||
type="number"
|
||||
label="Rating for all imported endgames"
|
||||
value={@rating}
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<.button type="submit" variant="primary" phx-disable-with="Looking up…">
|
||||
Look up results
|
||||
</.button>
|
||||
</form>
|
||||
|
||||
<.theme_picker
|
||||
selected_themes={@selected_themes}
|
||||
theme_query={@theme_query}
|
||||
theme_results={@theme_results}
|
||||
can_create={@can_create}
|
||||
/>
|
||||
|
||||
<section :if={@entries != nil} id="import-preview" class="mt-10">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="text-sm text-base-content/70">
|
||||
{summary(@entries)}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<.button type="button" phx-click="toggle_all" phx-value-selected="true">
|
||||
Select ready
|
||||
</.button>
|
||||
<.button type="button" phx-click="toggle_all" phx-value-selected="false">
|
||||
Clear
|
||||
</.button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p
|
||||
:if={@too_many?}
|
||||
class="mb-4 rounded-md border border-warning/30 bg-warning/10 px-4 py-3 text-sm text-warning-text"
|
||||
>
|
||||
Only the first {BulkImport.max_fens()} FENs were considered.
|
||||
</p>
|
||||
|
||||
<table class={table_class()}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="w-10"><span class="sr-only">Include</span></th>
|
||||
<th class="w-12">Line</th>
|
||||
<th>FEN</th>
|
||||
<th>Key</th>
|
||||
<th>Color</th>
|
||||
<th>Result</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr :for={entry <- @entries} id={"import-row-#{entry.line}"}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
id={"import-include-#{entry.line}"}
|
||||
checked={entry.selected}
|
||||
disabled={entry.status != :ready}
|
||||
phx-click="toggle_entry"
|
||||
phx-value-line={entry.line}
|
||||
/>
|
||||
</td>
|
||||
<td>{entry.line}</td>
|
||||
<td class="break-all font-mono text-xs">{entry.fen}</td>
|
||||
<td>{entry.key || "—"}</td>
|
||||
<td>{entry.color || "—"}</td>
|
||||
<td>{entry.result || "—"}</td>
|
||||
<td>
|
||||
<.badge color={status_color(entry.status)}>{status_label(entry.status)}</.badge>
|
||||
<span :if={entry.reason} class="mt-1 block text-xs text-base-content/60">
|
||||
{entry.reason}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<footer class="mt-6 flex items-center gap-3">
|
||||
<.button
|
||||
type="button"
|
||||
variant="primary"
|
||||
phx-click="import"
|
||||
disabled={selected_count(@entries) == 0}
|
||||
phx-disable-with="Importing…"
|
||||
>
|
||||
Import {selected_count(@entries)} endgame(s)
|
||||
</.button>
|
||||
|
||||
<span class="text-sm text-base-content/70">
|
||||
{selected_count(@entries)} of {count(@entries, :ready)} ready line(s) selected.
|
||||
</span>
|
||||
</footer>
|
||||
</section>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:page_title, "Import endgames")
|
||||
|> assign(:tablebase_status, tablebase_status())
|
||||
|> assign(:fen_text, "")
|
||||
|> assign(:rating, @default_rating)
|
||||
|> assign(:entries, nil)
|
||||
|> assign(:too_many?, false)
|
||||
|> assign(:selected_themes, [])
|
||||
|> assign(:theme_query, "")
|
||||
|> assign(:theme_results, [])
|
||||
|> assign(:can_create, false)}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("search_themes", %{"theme_search" => query}, socket) do
|
||||
{:noreply, assign_search(socket, query)}
|
||||
end
|
||||
|
||||
def handle_event("add_theme", %{"id" => id}, socket) do
|
||||
theme = Chesstrainer.Themes.get_theme!(id)
|
||||
{:noreply, socket |> add_selected_theme(theme) |> clear_search()}
|
||||
end
|
||||
|
||||
def handle_event("create_theme", %{"name" => 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)}
|
||||
end
|
||||
|
||||
def handle_event("lookup", %{"fens" => fens} = params, socket) do
|
||||
rating = parse_rating(params["rating"])
|
||||
|
||||
socket =
|
||||
assign(socket,
|
||||
fen_text: fens,
|
||||
rating: rating,
|
||||
entries: nil,
|
||||
too_many?: false
|
||||
)
|
||||
|
||||
if String.trim(fens) == "" do
|
||||
{:noreply, put_flash(socket, :error, "Paste at least one FEN.")}
|
||||
else
|
||||
{:noreply, start_async(socket, :lookup, fn -> BulkImport.preview(fens) end)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("toggle_entry", %{"line" => line}, socket) do
|
||||
line = String.to_integer(line)
|
||||
|
||||
entries =
|
||||
Enum.map(socket.assigns.entries, fn entry ->
|
||||
if entry.line == line, do: %{entry | selected: not entry.selected}, else: entry
|
||||
end)
|
||||
|
||||
{:noreply, assign(socket, :entries, entries)}
|
||||
end
|
||||
|
||||
def handle_event("toggle_all", %{"selected" => selected}, socket) do
|
||||
selected? = selected == "true"
|
||||
|
||||
entries =
|
||||
Enum.map(socket.assigns.entries, fn entry ->
|
||||
if entry.status == :ready, do: %{entry | selected: selected?}, else: entry
|
||||
end)
|
||||
|
||||
{:noreply, assign(socket, :entries, entries)}
|
||||
end
|
||||
|
||||
def handle_event("import", _params, socket) do
|
||||
entries =
|
||||
Enum.filter(socket.assigns.entries || [], &(&1.status == :ready and &1.selected))
|
||||
|
||||
if entries == [] do
|
||||
{:noreply, put_flash(socket, :error, "Select at least one ready endgame to import.")}
|
||||
else
|
||||
%{imported: imported, skipped: skipped} =
|
||||
BulkImport.commit(entries, socket.assigns.selected_themes, socket.assigns.rating)
|
||||
|
||||
message =
|
||||
"Imported #{imported} endgame(s)." <>
|
||||
if(skipped > 0, do: " #{skipped} skipped.", else: "")
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:info, message)
|
||||
|> push_navigate(to: ~p"/admin/endgames")}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_async(:lookup, {:ok, %{entries: entries, too_many?: too_many?}}, socket) do
|
||||
entries = Enum.map(entries, &Map.put(&1, :selected, &1.status == :ready))
|
||||
|
||||
{:noreply, assign(socket, entries: entries, too_many?: too_many?)}
|
||||
end
|
||||
|
||||
def handle_async(:lookup, {:exit, reason}, socket) do
|
||||
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
|
||||
case Local.check() do
|
||||
{:ok, 0} ->
|
||||
{:error,
|
||||
"The local Syzygy tablebase directory contains no files, so imports are disabled."}
|
||||
|
||||
{:ok, largest} ->
|
||||
{:ok, "Local Syzygy tablebase ready (up to #{largest} pieces)."}
|
||||
|
||||
{:error, :not_configured} ->
|
||||
{:error, "Local tablebase is not configured. Set TABLEBASE_PATH to enable imports."}
|
||||
|
||||
{:error, 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
|
||||
|
||||
defp parse_rating(rating) when is_integer(rating) and rating > 0, do: rating
|
||||
|
||||
defp parse_rating(rating) when is_binary(rating) do
|
||||
case Integer.parse(String.trim(rating)) do
|
||||
{value, ""} when value > 0 -> value
|
||||
_ -> @default_rating
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_rating(_rating), do: @default_rating
|
||||
|
||||
defp count(entries, status), do: Enum.count(entries, &(&1.status == status))
|
||||
|
||||
defp summary(entries) do
|
||||
"#{length(entries)} line(s): " <>
|
||||
"#{count(entries, :ready)} ready, " <>
|
||||
"#{count(entries, :duplicate)} duplicate(s), " <>
|
||||
"#{count(entries, :invalid_fen)} invalid, " <>
|
||||
"#{count(entries, :too_many_pieces)} too many pieces, " <>
|
||||
"#{count(entries, :terminal)} terminal, " <>
|
||||
"#{count(entries, :illegal)} illegal, " <>
|
||||
"#{count(entries, :unsupported)} unsupported."
|
||||
end
|
||||
|
||||
defp selected_count(entries) do
|
||||
Enum.count(entries, &(&1.status == :ready and &1.selected))
|
||||
end
|
||||
|
||||
defp status_label(:ready), do: "Ready"
|
||||
defp status_label(:duplicate), do: "Duplicate"
|
||||
defp status_label(:invalid_fen), do: "Invalid FEN"
|
||||
defp status_label(:too_many_pieces), do: "Too many pieces"
|
||||
defp status_label(:illegal), do: "Illegal"
|
||||
defp status_label(:terminal), do: "Terminal"
|
||||
defp status_label(:unsupported), do: "Unsupported"
|
||||
|
||||
defp status_color(:ready), do: "primary"
|
||||
defp status_color(_status), do: "warning"
|
||||
end
|
||||
@@ -9,9 +9,14 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Listing Endgames
|
||||
<:actions>
|
||||
<.button navigate={~p"/admin/endgames/import"}>
|
||||
<.icon name="hero-arrow-up-tray" /> Bulk import
|
||||
</.button>
|
||||
<.button variant="primary" navigate={~p"/admin/endgames/new"}>
|
||||
<.icon name="hero-plus" /> New Endgame
|
||||
</.button>
|
||||
|
||||
@@ -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}
|
||||
@@ -63,6 +63,8 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
||||
move_input_error={@move_input_error}
|
||||
last_check={@last_check}
|
||||
last_checkmate={@last_checkmate}
|
||||
rating={@user_rating}
|
||||
rating_delta={@last_rating_delta}
|
||||
/>
|
||||
|
||||
<div :if={@user_rating} class="mb-4">
|
||||
|
||||
@@ -19,9 +19,25 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
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.
|
||||
|
||||
@@ -38,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)
|
||||
@@ -163,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", %{})}
|
||||
|
||||
@@ -172,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
|
||||
@@ -181,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
|
||||
@@ -358,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
|
||||
@@ -382,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
|
||||
@@ -463,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
|
||||
|
||||
@@ -517,6 +560,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
|> assign(:user_rating, user.rating)
|
||||
|> assign(:user_deviation, user.rating_deviation)
|
||||
|> assign(:last_rating_delta, delta)
|
||||
|> put_rating_flash(outcome, user.rating, delta)
|
||||
|
||||
{:skipped, _attempt} ->
|
||||
socket
|
||||
@@ -532,6 +576,24 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|
||||
end
|
||||
end
|
||||
|
||||
# A finished rating change is shown as a flash so the player sees it
|
||||
# immediately, whether they are in a session or playing a single endgame.
|
||||
defp put_rating_flash(socket, outcome, rating, delta) do
|
||||
kind = if outcome == :solved, do: :success, else: :error
|
||||
put_flash(socket, kind, rating_change_message(socket, outcome, rating, delta))
|
||||
end
|
||||
|
||||
defp rating_change_message(socket, :solved, rating, delta) do
|
||||
result = if socket.assigns.endgame.result == :draw, do: "Draw held", else: "Solved"
|
||||
|
||||
"#{result}! Your rating is now #{round(rating)} " <>
|
||||
"(#{RatingComponents.format_delta(delta)})."
|
||||
end
|
||||
|
||||
defp rating_change_message(_socket, :failed, rating, delta) do
|
||||
"Failed. Your rating is now #{round(rating)} (#{RatingComponents.format_delta(delta)})."
|
||||
end
|
||||
|
||||
defp user_rating(%{user: %{rating: rating}}), do: rating
|
||||
defp user_rating(_), do: nil
|
||||
|
||||
@@ -707,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
|
||||
|
||||
@@ -26,6 +26,8 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
|
||||
|
||||
~H"""
|
||||
<Layouts.app flash={@flash} wide>
|
||||
<Layouts.admin_nav current_scope={@current_scope} />
|
||||
|
||||
<.header>
|
||||
Endgame {@endgame.id}
|
||||
<:subtitle>This is a endgame record from your database.</:subtitle>
|
||||
|
||||
@@ -65,26 +65,24 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
<span class="text-muted">Avg/puzzle</span>
|
||||
<span class="font-mono">{format_duration(avg_ms(@session))}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="flex items-center gap-2">
|
||||
<span class="text-muted">Rating</span>
|
||||
<span class={["font-mono", gain_class(net_gain(@session, @user_rating))]}>
|
||||
{format_delta(net_gain(@session, @user_rating))}
|
||||
</span>
|
||||
</span>
|
||||
<span :if={@last_rating_delta}>
|
||||
<span class="text-muted">Last</span>
|
||||
<span class={["font-mono", gain_class(@last_rating_delta)]}>
|
||||
{format_delta(@last_rating_delta)}
|
||||
</span>
|
||||
<span id="session-rating" class="font-mono font-semibold">{round(@user_rating)}</span>
|
||||
<.rating_change
|
||||
:if={@session.count > 0}
|
||||
id="session-rating-change"
|
||||
delta={net_gain(@session, @user_rating)}
|
||||
/>
|
||||
</span>
|
||||
</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,7 +97,29 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
move_input_error={@move_input_error}
|
||||
last_check={@last_check}
|
||||
last_checkmate={@last_checkmate}
|
||||
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 played every puzzle available right now</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">
|
||||
@@ -126,11 +146,13 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
<span class="text-muted">Avg/puzzle</span>
|
||||
<span class="font-mono">{format_duration(@last_session.avg_ms)}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="flex items-center gap-2">
|
||||
<span class="text-muted">Rating</span>
|
||||
<span class={["font-mono", gain_class(@last_session.gain)]}>
|
||||
{format_delta(@last_session.gain)}
|
||||
</span>
|
||||
<span class="font-mono font-semibold">{round(@last_session.rating)}</span>
|
||||
<.rating_change
|
||||
:if={@last_session.count > 0}
|
||||
delta={@last_session.gain}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -139,7 +161,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold">Choose a difficulty</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Difficulty bands are ±{Puzzles.band_width()} around your rating.
|
||||
Easy draws easier endgames, hard draws harder ones — your rating sets the centre.
|
||||
</p>
|
||||
</div>
|
||||
<.link
|
||||
@@ -154,8 +176,21 @@ 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 %>
|
||||
<%= for {difficulty, label, description} <- difficulty_options() do %>
|
||||
<.button
|
||||
id={"difficulty-#{difficulty}"}
|
||||
phx-click="start_session"
|
||||
@@ -187,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
|
||||
@@ -252,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
|
||||
@@ -299,6 +304,57 @@ 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,
|
||||
served_ids: [endgame.id]
|
||||
}
|
||||
|
||||
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: session.served_ids
|
||||
) do
|
||||
nil ->
|
||||
assign(socket, :pool, %{difficulty: session.difficulty})
|
||||
|
||||
endgame ->
|
||||
session = %{session | served_ids: [endgame.id | session.served_ids]}
|
||||
|
||||
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
|
||||
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
|
||||
@@ -333,7 +389,8 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
duration_ms: elapsed_ms(session),
|
||||
count: session.count,
|
||||
avg_ms: avg_ms(session),
|
||||
gain: net_gain(session, rating)
|
||||
gain: net_gain(session, rating),
|
||||
rating: rating
|
||||
}
|
||||
end
|
||||
|
||||
@@ -342,13 +399,11 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
|
||||
defp parse_difficulty(_value), do: :medium
|
||||
|
||||
defp difficulty_options(rating) do
|
||||
width = Puzzles.band_width()
|
||||
|
||||
defp difficulty_options do
|
||||
[
|
||||
{:easy, "Easy", "below #{round(rating - width)}"},
|
||||
{:medium, "Medium", "#{round(rating - width)}–#{round(rating + width)}"},
|
||||
{:hard, "Hard", "above #{round(rating + width)}"}
|
||||
{:easy, "Easy", "easier than your rating"},
|
||||
{:medium, "Medium", "around your rating"},
|
||||
{:hard, "Hard", "harder than your rating"}
|
||||
]
|
||||
end
|
||||
|
||||
@@ -373,19 +428,4 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|
||||
seconds = String.pad_leading(Integer.to_string(rem(total, 60)), 2, "0")
|
||||
"#{minutes}:#{seconds}"
|
||||
end
|
||||
|
||||
defp format_delta(nil), do: "—"
|
||||
|
||||
defp format_delta(delta) when is_number(delta) do
|
||||
rounded = round(delta)
|
||||
|
||||
cond do
|
||||
rounded > 0 -> "+#{rounded}"
|
||||
true -> Integer.to_string(rounded)
|
||||
end
|
||||
end
|
||||
|
||||
defp gain_class(delta) when is_number(delta) and delta > 0, do: "text-success-text"
|
||||
defp gain_class(delta) when is_number(delta) and delta < 0, do: "text-error-text"
|
||||
defp gain_class(_delta), do: "text-muted"
|
||||
end
|
||||
|
||||
@@ -7,25 +7,27 @@ defmodule ChesstrainerWeb.UserLive.Login do
|
||||
<Layouts.app flash={@flash} current_scope={@current_scope}>
|
||||
<div class="mx-auto max-w-sm space-y-4">
|
||||
<div class="text-center">
|
||||
<h1 class="settings-header">Log in</h1>
|
||||
<%= if @current_scope do %>
|
||||
You need to reauthenticate to perform sensitive actions on your account.
|
||||
<% else %>
|
||||
<p :if={!@prelaunch} class="settings-subtitle my-4">
|
||||
Don't have an account? <.link
|
||||
navigate={~p"/users/register"}
|
||||
class="font-semibold text-primary-text hover:underline"
|
||||
phx-no-format
|
||||
>Sign up</.link> for an account now.
|
||||
</p>
|
||||
<% end %>
|
||||
<.header>
|
||||
Log in
|
||||
<:subtitle :if={@current_scope || !@prelaunch}>
|
||||
<%= if @current_scope do %>
|
||||
You need to reauthenticate to perform sensitive actions on your account.
|
||||
<% else %>
|
||||
Don't have an account? <.link
|
||||
navigate={~p"/users/register"}
|
||||
class="font-semibold text-primary-text hover:underline"
|
||||
phx-no-format
|
||||
>Sign up</.link> for an account now.
|
||||
<% end %>
|
||||
</:subtitle>
|
||||
</.header>
|
||||
</div>
|
||||
|
||||
<.form
|
||||
:let={f}
|
||||
for={@form}
|
||||
id="login_form_password"
|
||||
action={@login_action}
|
||||
action={~p"/users/log-in"}
|
||||
phx-submit="submit_password"
|
||||
phx-trigger-action={@trigger_submit}
|
||||
>
|
||||
@@ -73,17 +75,12 @@ defmodule ChesstrainerWeb.UserLive.Login do
|
||||
get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
|
||||
|
||||
form = to_form(%{"email" => email}, as: "user")
|
||||
prelaunch = ChesstrainerWeb.prelaunch?()
|
||||
|
||||
login_action =
|
||||
if prelaunch, do: ~p"/admin/log-in", else: ~p"/users/log-in"
|
||||
|
||||
{:ok,
|
||||
assign(socket,
|
||||
form: form,
|
||||
trigger_submit: false,
|
||||
prelaunch: prelaunch,
|
||||
login_action: login_action
|
||||
prelaunch: ChesstrainerWeb.prelaunch?()
|
||||
)}
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
defmodule ChesstrainerWeb.LoginThrottle do
|
||||
@moduledoc """
|
||||
In-memory failure throttle for password logins.
|
||||
|
||||
Failures are counted in two independent fixed windows: one per client address
|
||||
and one per normalised login (email or username). A successful login clears
|
||||
the login bucket only, so one account stays protected from distributed
|
||||
guessing while one address stays protected from spraying many accounts.
|
||||
|
||||
Addresses and logins are HMACed with a per-boot secret before they reach ETS;
|
||||
raw values are never stored or logged. The table is per node and is cleared on
|
||||
restart, which is acceptable for the current single-node deployment.
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
|
||||
@table :login_throttle
|
||||
@sweep_interval :timer.minutes(1)
|
||||
@default_window_ms :timer.minutes(15)
|
||||
@default_max_per_ip 10
|
||||
@default_max_per_login 5
|
||||
|
||||
@typedoc "An IPv4/IPv6 address, or `nil` when the socket has no peer data."
|
||||
@type address :: :inet.ip_address() | nil
|
||||
|
||||
@typedoc "Which bucket blocked the attempt."
|
||||
@type bucket :: :ip | :login
|
||||
|
||||
@doc "Starts the throttle."
|
||||
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
||||
|
||||
@doc """
|
||||
Checks both buckets without recording anything.
|
||||
|
||||
Returns `:ok`, or `{:throttled, bucket, retry_in_ms}` when that bucket is
|
||||
already at its limit.
|
||||
"""
|
||||
@spec check(address, String.t() | nil) :: :ok | {:throttled, bucket(), non_neg_integer()}
|
||||
def check(address, login), do: GenServer.call(__MODULE__, {:check, address, login})
|
||||
|
||||
@doc "Records one failed authentication in both buckets."
|
||||
@spec record_failure(address, String.t() | nil) :: :ok
|
||||
def record_failure(address, login) do
|
||||
GenServer.call(__MODULE__, {:record_failure, address, login})
|
||||
end
|
||||
|
||||
@doc "Clears the login bucket. The address bucket deliberately stays."
|
||||
@spec record_success(String.t() | nil) :: :ok
|
||||
def record_success(login), do: GenServer.call(__MODULE__, {:record_success, login})
|
||||
|
||||
@doc """
|
||||
Claims a confirmation-email resend for `login`.
|
||||
|
||||
Returns true at most once per cooldown window, so repeated unconfirmed login
|
||||
attempts cannot send a fresh confirmation email on every try.
|
||||
"""
|
||||
@spec claim_confirmation_resend(String.t() | nil) :: boolean()
|
||||
def claim_confirmation_resend(login) do
|
||||
GenServer.call(__MODULE__, {:claim_confirmation_resend, login})
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a stable, non-reversible fingerprint of an address for log metadata.
|
||||
|
||||
The digest is scoped to this boot, matching the throttle keys.
|
||||
"""
|
||||
@spec fingerprint(address) :: String.t() | nil
|
||||
def fingerprint(address), do: GenServer.call(__MODULE__, {:fingerprint, address})
|
||||
|
||||
@doc "Clears every bucket. Intended for tests."
|
||||
def reset, do: GenServer.call(__MODULE__, :reset)
|
||||
|
||||
@doc "Failures allowed per address before the next attempt is blocked."
|
||||
def max_per_ip, do: config() |> Keyword.get(:max_per_ip, @default_max_per_ip)
|
||||
|
||||
@doc "Failures allowed per login before the next attempt is blocked."
|
||||
def max_per_login, do: config() |> Keyword.get(:max_per_login, @default_max_per_login)
|
||||
|
||||
@doc "How long a bucket stays active, in milliseconds."
|
||||
def window_ms, do: config() |> Keyword.get(:window_ms, @default_window_ms)
|
||||
|
||||
defp config, do: Application.get_env(:chesstrainer, __MODULE__, [])
|
||||
|
||||
@impl true
|
||||
def init(opts) do
|
||||
:ets.new(@table, [:named_table, :set])
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
secret: :crypto.strong_rand_bytes(32),
|
||||
window_ms: Keyword.get(opts, :window_ms, window_ms()),
|
||||
max_per_ip: Keyword.get(opts, :max_per_ip, max_per_ip()),
|
||||
max_per_login: Keyword.get(opts, :max_per_login, max_per_login()),
|
||||
confirmation_cooldown_ms: Keyword.get(opts, :confirmation_cooldown_ms, window_ms())
|
||||
}}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:check, address, login}, _from, state) do
|
||||
now = now_ms()
|
||||
|
||||
result =
|
||||
case blocked(:ip, address, state, now) do
|
||||
nil -> blocked(:login, normalize_login(login), state, now) || :ok
|
||||
blocked -> blocked
|
||||
end
|
||||
|
||||
{:reply, result, state}
|
||||
end
|
||||
|
||||
def handle_call({:record_failure, address, login}, _from, state) do
|
||||
now = now_ms()
|
||||
bump(:ip, address, state, now)
|
||||
bump(:login, normalize_login(login), state, now)
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
def handle_call({:record_success, login}, _from, state) do
|
||||
case normalize_login(login) do
|
||||
nil -> :ok
|
||||
login -> :ets.delete(@table, key(state.secret, :login, login))
|
||||
end
|
||||
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
def handle_call({:claim_confirmation_resend, login}, _from, state) do
|
||||
normalized = normalize_login(login)
|
||||
now = now_ms()
|
||||
|
||||
case normalized do
|
||||
nil ->
|
||||
{:reply, true, state}
|
||||
|
||||
login ->
|
||||
key = key(state.secret, :confirmation, login)
|
||||
|
||||
case count(key, now) do
|
||||
nil ->
|
||||
:ets.insert(@table, {key, now + state.confirmation_cooldown_ms, 1})
|
||||
{:reply, true, state}
|
||||
|
||||
_active ->
|
||||
{:reply, false, state}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:fingerprint, nil}, _from, state), do: {:reply, nil, state}
|
||||
|
||||
def handle_call({:fingerprint, address}, _from, state) do
|
||||
fingerprint =
|
||||
state.secret
|
||||
|> key(:ip, address)
|
||||
|> Base.encode16(case: :lower)
|
||||
|
||||
{:reply, fingerprint, state}
|
||||
end
|
||||
|
||||
def handle_call(:reset, _from, state) do
|
||||
:ets.delete_all_objects(@table)
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info(:sweep, state) do
|
||||
:ets.select_delete(@table, [{{:_, :"$1", :_}, [{:"=<", :"$1", now_ms()}], [true]}])
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
defp blocked(_bucket, nil, _state, _now), do: nil
|
||||
|
||||
defp blocked(bucket, value, state, now) do
|
||||
key = key(state.secret, bucket, value)
|
||||
limit = limit(bucket, state)
|
||||
|
||||
case count(key, now) do
|
||||
{count, expires_at} when count >= limit ->
|
||||
{:throttled, bucket, max(expires_at - now, 0)}
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp bump(_bucket, nil, _state, _now), do: :ok
|
||||
|
||||
defp bump(bucket, value, state, now) do
|
||||
key = key(state.secret, bucket, value)
|
||||
|
||||
case count(key, now) do
|
||||
{count, expires_at} ->
|
||||
:ets.insert(@table, {key, expires_at, count + 1})
|
||||
|
||||
nil ->
|
||||
:ets.insert(@table, {key, now + state.window_ms, 1})
|
||||
end
|
||||
end
|
||||
|
||||
defp count(key, now) do
|
||||
case :ets.lookup(@table, key) do
|
||||
[{^key, expires_at, count}] when expires_at > now ->
|
||||
{count, expires_at}
|
||||
|
||||
[{^key, _expires_at, _count}] ->
|
||||
:ets.delete(@table, key)
|
||||
nil
|
||||
|
||||
[] ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp limit(:ip, state), do: state.max_per_ip
|
||||
defp limit(:login, state), do: state.max_per_login
|
||||
|
||||
defp key(secret, bucket, value) do
|
||||
:crypto.mac(:hmac, :sha256, secret, [Atom.to_string(bucket), "|", value_binary(value)])
|
||||
end
|
||||
|
||||
defp value_binary(value) when is_binary(value), do: value
|
||||
defp value_binary(value) when is_tuple(value), do: :erlang.term_to_binary(value)
|
||||
|
||||
defp normalize_login(login) when is_binary(login) do
|
||||
case login |> String.trim() |> String.downcase() do
|
||||
"" -> nil
|
||||
login -> login
|
||||
end
|
||||
end
|
||||
|
||||
defp normalize_login(_login), do: nil
|
||||
|
||||
defp now_ms, do: System.system_time(:millisecond)
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user