Compare commits
144 Commits
9d85090075
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 24017bcb7f | |||
| 40d8f06588 | |||
| c59e522732 | |||
| 8d45ae6e3b | |||
| 2c4f4b10dc | |||
| 520a9092fe | |||
| 9f970495ee | |||
| 3d9ba3ac3d | |||
| 171b71b7e0 | |||
| 2b399d0838 | |||
| f5f45e7afb | |||
| b54cb8878d | |||
| e336638ca8 | |||
| 62f42ed102 | |||
| ecb21bd218 | |||
| e2771826fd | |||
| dec6fac013 | |||
| c494da553a | |||
| fa8abf22db | |||
| 1ba789a1f1 | |||
| bdd1cc7d85 | |||
| 0ab1719ee9 | |||
| 380f82438c | |||
| a404513037 | |||
| b22b624d28 | |||
| e71e40eef5 | |||
| 41d21f3f6f | |||
| 9642cafc1f | |||
| ba6ee90278 | |||
| e79c1ea891 | |||
| cf9fa75d62 | |||
| 81b44c2b02 | |||
| 041106d623 | |||
| 3fffee7817 | |||
| 860cfeb30f | |||
| 6aeb529f13 | |||
| 2a8717c930 | |||
| 264097bbf6 | |||
| 9824214fd7 | |||
| c72adddb91 | |||
| 95f5703372 | |||
| d40fe1edec | |||
| a5db10c46e | |||
| c739f12d3d | |||
| 483e945209 | |||
| a21ba23e5e | |||
| 57c778f9b2 | |||
| 1933849dba | |||
| e06c6ff67f | |||
| caefc8f579 | |||
| 76d4610e6f | |||
| c9a5ca3ed7 | |||
| 9644bd6e5e | |||
| c127bc9f0e | |||
| 9ded5d3d86 | |||
| 6e77de4c1e | |||
| c67a5d51f1 | |||
| f3768d20f2 | |||
| 0eb1e0ef47 | |||
| d0681c5efe | |||
| 0dd4099d68 | |||
| b65a3ecc9c | |||
| b156d3403c | |||
| 4adb608ad1 | |||
| b5688d4848 | |||
| ab1ad998aa | |||
| 1c87313a78 | |||
| 64be0572b3 | |||
| 81b9e1529e | |||
| 9074417762 | |||
| 9d52885a6e | |||
| 8793bd34f2 | |||
| 5a3f0951ae | |||
| fb0ddab0f1 | |||
| e850ecd83b | |||
| 2c24d54047 | |||
| 2f4aa1b75b | |||
| 712ef205c1 | |||
| 7cd4474945 | |||
| 236152ea7b | |||
| c3b3cafcdd | |||
| b71f006ddf | |||
| 20f2a5a011 | |||
| a7f3df9346 | |||
| aaac816dc2 | |||
| d53ff18a67 | |||
| 63ab85a5e5 | |||
| 05d83ced86 | |||
| 2a034ff9be | |||
| 12d128f1cc | |||
| e9dfa4ccb8 | |||
| 9c30bdf8e7 | |||
| 51d7c4e005 | |||
| 14b5f61af9 | |||
| 6d66545062 | |||
| 183e08ec80 | |||
| ac1c89c0ee | |||
| 52f2caae51 | |||
| 27871f2a1d | |||
| dd45af20ef | |||
| 115c92b39a | |||
| 9f83962bf7 | |||
| dc582e9f73 | |||
| 5fb0daa746 | |||
| 3b20abe0bd | |||
| 9e72e2c799 | |||
| 53c6e34c13 | |||
| cb4a31a860 | |||
| a5f066224c | |||
| 00a33c227b | |||
| 0946a3f66c | |||
| f59c8dcd43 | |||
| 3bceafbc12 | |||
| 9e6899bb7d | |||
| d2a9441287 | |||
| aa765a0c06 | |||
| 91d5c341ef | |||
| bd0482c376 | |||
| 8e0d7f9e17 | |||
| 4d6df4bd8b | |||
| 4b454db219 | |||
| 8073971fca | |||
| 00129414e5 | |||
| 853730823b | |||
| 01d2d1f368 | |||
| 03eb8044ff | |||
| 6679260d0a | |||
| 800a692766 | |||
| 30a7c24140 | |||
| 711fe6e594 | |||
| 277954c47f | |||
| 55ed87fb11 | |||
| 49b67a0354 | |||
| 2a4ce319d9 | |||
| 1ae43080ec | |||
| 5287794a72 | |||
| 419ea11b14 | |||
| fc848157d6 | |||
| 192e4a2433 | |||
| d3bedbb5b6 | |||
| ac62d29ef7 | |||
| a80952a835 | |||
| 290874720f | |||
| d1ba666495 |
+58
-32
@@ -26,6 +26,13 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: [development]
|
branches: [development]
|
||||||
|
|
||||||
|
# The dictionary release the test suite validates against — the current
|
||||||
|
# scrabble-dictionary release. Centralised here so a release bump is one edit; the
|
||||||
|
# unit/integration jobs inherit it. The deploy job overrides it per contour with
|
||||||
|
# vars.TEST_DICT_VERSION (the seed for a fresh volume), see deploy/README.md.
|
||||||
|
env:
|
||||||
|
DICT_VERSION: v1.2.1
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# changes detects which areas a PR/push touched, so the test jobs can skip when
|
# changes detects which areas a PR/push touched, so the test jobs can skip when
|
||||||
# irrelevant. It defaults to running everything when the diff cannot be computed.
|
# irrelevant. It defaults to running everything when the diff cannot be computed.
|
||||||
@@ -86,7 +93,6 @@ jobs:
|
|||||||
# The engine consumes the published scrabble-solver module from this Gitea;
|
# The engine consumes the published scrabble-solver module from this Gitea;
|
||||||
# GOPRIVATE makes go fetch it directly (skipping the public proxy/checksum DB).
|
# GOPRIVATE makes go fetch it directly (skipping the public proxy/checksum DB).
|
||||||
GOPRIVATE: gitea.iliadenisov.ru/*
|
GOPRIVATE: gitea.iliadenisov.ru/*
|
||||||
DICT_VERSION: v1.0.0
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -134,7 +140,6 @@ jobs:
|
|||||||
# suite's TestMain terminates its own container, so disable it.
|
# suite's TestMain terminates its own container, so disable it.
|
||||||
TESTCONTAINERS_RYUK_DISABLED: "true"
|
TESTCONTAINERS_RYUK_DISABLED: "true"
|
||||||
GOPRIVATE: gitea.iliadenisov.ru/*
|
GOPRIVATE: gitea.iliadenisov.ru/*
|
||||||
DICT_VERSION: v1.0.0
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -254,23 +259,24 @@ jobs:
|
|||||||
AWG_CONF: ${{ secrets.TEST_AWG_CONF }}
|
AWG_CONF: ${{ secrets.TEST_AWG_CONF }}
|
||||||
GM_BASICAUTH_HASH: ${{ secrets.TEST_GM_BASICAUTH_HASH }}
|
GM_BASICAUTH_HASH: ${{ secrets.TEST_GM_BASICAUTH_HASH }}
|
||||||
GRAFANA_ADMIN_PASSWORD: ${{ secrets.TEST_GRAFANA_ADMIN_PASSWORD }}
|
GRAFANA_ADMIN_PASSWORD: ${{ secrets.TEST_GRAFANA_ADMIN_PASSWORD }}
|
||||||
TELEGRAM_BOT_TOKEN_EN: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN_EN }}
|
TELEGRAM_BOT_TOKEN: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN }}
|
||||||
TELEGRAM_BOT_TOKEN_RU: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN_RU }}
|
TELEGRAM_PROMO_BOT_TOKEN: ${{ secrets.TEST_TELEGRAM_PROMO_BOT_TOKEN }}
|
||||||
GM_BASICAUTH_USER: ${{ vars.TEST_GM_BASICAUTH_USER }}
|
GM_BASICAUTH_USER: ${{ vars.TEST_GM_BASICAUTH_USER }}
|
||||||
GRAFANA_ROOT_URL: ${{ vars.TEST_GRAFANA_ROOT_URL }}
|
GRAFANA_ROOT_URL: ${{ vars.TEST_GRAFANA_ROOT_URL }}
|
||||||
CADDY_SITE_ADDRESS: ${{ vars.TEST_CADDY_SITE_ADDRESS }}
|
CADDY_SITE_ADDRESS: ${{ vars.TEST_CADDY_SITE_ADDRESS }}
|
||||||
TELEGRAM_MINIAPP_URL: ${{ vars.TEST_TELEGRAM_MINIAPP_URL }}
|
TELEGRAM_MINIAPP_URL: ${{ vars.TEST_TELEGRAM_MINIAPP_URL }}
|
||||||
TELEGRAM_GAME_CHANNEL_ID_EN: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID_EN }}
|
TELEGRAM_GAME_CHANNEL_ID: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID }}
|
||||||
TELEGRAM_GAME_CHANNEL_ID_RU: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID_RU }}
|
TELEGRAM_CHAT_ID: ${{ vars.TEST_TELEGRAM_CHAT_ID }}
|
||||||
|
TELEGRAM_BOT_USERNAME: ${{ vars.TEST_TELEGRAM_BOT_USERNAME }}
|
||||||
|
# The promo button reuses the UI's Mini App link variable.
|
||||||
|
TELEGRAM_BOT_LINK: ${{ vars.TEST_VITE_TELEGRAM_LINK }}
|
||||||
# The test contour always uses Telegram's test environment — pinned here,
|
# The test contour always uses Telegram's test environment — pinned here,
|
||||||
# not an operator variable. The prod workflow leaves it false.
|
# not an operator variable. The prod workflow leaves it false.
|
||||||
TELEGRAM_TEST_ENV: "true"
|
TELEGRAM_TEST_ENV: "true"
|
||||||
VITE_TELEGRAM_BOT_ID: ${{ vars.TEST_VITE_TELEGRAM_BOT_ID }}
|
VITE_TELEGRAM_BOT_ID: ${{ vars.TEST_VITE_TELEGRAM_BOT_ID }}
|
||||||
VITE_TELEGRAM_LINK: ${{ vars.TEST_VITE_TELEGRAM_LINK }}
|
VITE_TELEGRAM_LINK: ${{ vars.TEST_VITE_TELEGRAM_LINK }}
|
||||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_EN: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME_EN }}
|
VITE_TELEGRAM_GAME_CHANNEL_NAME: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME }}
|
||||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_RU: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME_RU }}
|
|
||||||
VITE_GATEWAY_URL: ${{ vars.TEST_VITE_GATEWAY_URL }}
|
VITE_GATEWAY_URL: ${{ vars.TEST_VITE_GATEWAY_URL }}
|
||||||
GATEWAY_DEFAULT_SUPPORTED_LANGUAGES: ${{ vars.TEST_GATEWAY_DEFAULT_SUPPORTED_LANGUAGES }}
|
|
||||||
# Unset vars render empty -> the compose ":-" defaults apply.
|
# Unset vars render empty -> the compose ":-" defaults apply.
|
||||||
POSTGRES_DB: ${{ vars.TEST_POSTGRES_DB }}
|
POSTGRES_DB: ${{ vars.TEST_POSTGRES_DB }}
|
||||||
POSTGRES_USER: ${{ vars.TEST_POSTGRES_USER }}
|
POSTGRES_USER: ${{ vars.TEST_POSTGRES_USER }}
|
||||||
@@ -287,62 +293,82 @@ jobs:
|
|||||||
mkdir -p "$conf"
|
mkdir -p "$conf"
|
||||||
cp -r caddy otelcol prometheus tempo grafana "$conf"/
|
cp -r caddy otelcol prometheus tempo grafana "$conf"/
|
||||||
export SCRABBLE_CONFIG_DIR="$conf"
|
export SCRABBLE_CONFIG_DIR="$conf"
|
||||||
|
# Bot-link mTLS material for the test contour: a private CA + gateway/bot
|
||||||
|
# leaves (CN=gateway, the service name the bot dials). Prod supplies these
|
||||||
|
# from PROD_ secrets instead. Regenerated each deploy; both ends redeploy
|
||||||
|
# together so they always share the fresh CA (see deploy/gen-certs.sh).
|
||||||
|
bash "$GITHUB_WORKSPACE/deploy/gen-certs.sh" "$conf/certs"
|
||||||
# App version for the About screen: the git tag if present, else the short SHA
|
# App version for the About screen: the git tag if present, else the short SHA
|
||||||
# (the test checkout is shallow/untagged, so this is the SHA here — fine).
|
# (the test checkout is shallow/untagged, so this is the SHA here — fine).
|
||||||
export APP_VERSION="$(git -C "$GITHUB_WORKSPACE" describe --tags --always 2>/dev/null || echo dev)"
|
export APP_VERSION="$(git -C "$GITHUB_WORKSPACE" describe --tags --always 2>/dev/null || echo dev)"
|
||||||
docker compose --ansi never build --progress plain
|
# The telegram-local profile brings the bot + its VPN sidecar; prod runs the
|
||||||
docker compose --ansi never up -d --remove-orphans
|
# bot on its own host instead (deploy/docker-compose.bot.yml), and the prod
|
||||||
|
# main host omits both. Without the profile they would not start here.
|
||||||
|
docker compose --ansi never --profile telegram-local build --progress plain
|
||||||
|
docker compose --ansi never --profile telegram-local up -d --remove-orphans
|
||||||
# The config-only services bind-mount the reseeded config dir. A plain `up -d`
|
# The config-only services bind-mount the reseeded config dir. A plain `up -d`
|
||||||
# leaves them on the previous bind mount (the dir was rm'd + recreated), so a
|
# leaves them on the previous bind mount (the dir was rm'd + recreated), so a
|
||||||
# changed Caddyfile or Grafana dashboard is ignored — force-recreate them to
|
# changed Caddyfile or Grafana dashboard is ignored — force-recreate them to
|
||||||
# pick up the fresh config.
|
# pick up the fresh config.
|
||||||
docker compose --ansi never up -d --force-recreate --no-deps caddy otelcol prometheus tempo grafana
|
docker compose --ansi never up -d --force-recreate --no-deps caddy otelcol prometheus tempo grafana
|
||||||
|
|
||||||
- name: Probe the landing and the gateway through caddy
|
- name: Probe the landing, gateway and backend
|
||||||
run: |
|
run: |
|
||||||
set -u
|
set -u
|
||||||
# Two probes through the contour caddy: "/" is the static
|
# Three probes. "/" is the static landing container and "/app/" the
|
||||||
# landing container, "/app/" is the gateway-served SPA shell.
|
# gateway-served SPA shell (both through the contour caddy on the edge net).
|
||||||
|
# The backend /readyz is probed on the internal net as well: the caddy probes
|
||||||
|
# are blind to a crash-looping backend (the landing is static and the SPA
|
||||||
|
# shell is served without it), which let a bad deploy go green while the
|
||||||
|
# backend was down — so check it directly here.
|
||||||
for i in $(seq 1 20); do
|
for i in $(seq 1 20); do
|
||||||
if docker run --rm --network edge alpine:3.20 wget -q -T 5 -O /dev/null http://scrabble/ &&
|
if docker run --rm --network edge alpine:3.20 wget -q -T 5 -O /dev/null http://scrabble/ &&
|
||||||
docker run --rm --network edge alpine:3.20 wget -q -T 5 -O /dev/null http://scrabble/app/; then
|
docker run --rm --network edge alpine:3.20 wget -q -T 5 -O /dev/null http://scrabble/app/ &&
|
||||||
echo "healthy: GET http://scrabble/ (landing) + /app/ (gateway)"
|
docker run --rm --network scrabble-internal alpine:3.20 wget -q -T 5 -O /dev/null http://backend:8080/readyz; then
|
||||||
|
echo "healthy: GET / (landing) + /app/ (gateway) + backend /readyz"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
sleep 3
|
sleep 3
|
||||||
done
|
done
|
||||||
echo "probe failed; recent landing + gateway logs:"
|
echo "probe failed; recent landing + gateway + backend logs:"
|
||||||
docker logs --tail 50 scrabble-landing || true
|
docker logs --tail 50 scrabble-landing || true
|
||||||
docker logs --tail 50 scrabble-gateway || true
|
docker logs --tail 50 scrabble-gateway || true
|
||||||
|
docker logs --tail 50 scrabble-backend || true
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Probe the Telegram connector liveness
|
- name: Probe the Telegram validator and bot liveness
|
||||||
run: |
|
run: |
|
||||||
set -u
|
set -u
|
||||||
# The gateway probe cannot see a crash-looping connector (it long-polls and
|
# The gateway/backend probes cannot see a crash-looping validator or bot
|
||||||
# egresses through the VPN sidecar, with no public ingress). Inspect the
|
# (the validator answers only internal gRPC; the bot long-polls + egresses
|
||||||
# container directly: it must be running, not restarting, with a stable
|
# through the VPN sidecar with no public ingress). Inspect the containers
|
||||||
# restart count. A grace period lets the VPN handshake settle (the connector
|
# directly: each must be running, not restarting, with a stable restart
|
||||||
# may restart a few times first).
|
# count. A grace period lets the VPN handshake and the bot-link dial settle.
|
||||||
sleep 20
|
sleep 20
|
||||||
|
for name in scrabble-telegram-validator scrabble-telegram-bot; do
|
||||||
|
ok=
|
||||||
for i in $(seq 1 20); do
|
for i in $(seq 1 20); do
|
||||||
status="$(docker inspect -f '{{.State.Status}}' scrabble-telegram 2>/dev/null || echo missing)"
|
status="$(docker inspect -f '{{.State.Status}}' "$name" 2>/dev/null || echo missing)"
|
||||||
restarting="$(docker inspect -f '{{.State.Restarting}}' scrabble-telegram 2>/dev/null || echo true)"
|
restarting="$(docker inspect -f '{{.State.Restarting}}' "$name" 2>/dev/null || echo true)"
|
||||||
if [ "$status" = "running" ] && [ "$restarting" = "false" ]; then
|
if [ "$status" = "running" ] && [ "$restarting" = "false" ]; then
|
||||||
c1="$(docker inspect -f '{{.RestartCount}}' scrabble-telegram)"
|
c1="$(docker inspect -f '{{.RestartCount}}' "$name")"
|
||||||
sleep 5
|
sleep 5
|
||||||
c2="$(docker inspect -f '{{.RestartCount}}' scrabble-telegram)"
|
c2="$(docker inspect -f '{{.RestartCount}}' "$name")"
|
||||||
if [ "$c1" = "$c2" ]; then
|
if [ "$c1" = "$c2" ]; then
|
||||||
echo "connector healthy: status=$status restarts=$c2"
|
echo "$name healthy: status=$status restarts=$c2"
|
||||||
exit 0
|
ok=1
|
||||||
|
break
|
||||||
fi
|
fi
|
||||||
echo "connector still restarting ($c1 -> $c2); waiting"
|
echo "$name still restarting ($c1 -> $c2); waiting"
|
||||||
fi
|
fi
|
||||||
sleep 3
|
sleep 3
|
||||||
done
|
done
|
||||||
echo "connector not healthy; recent logs:"
|
if [ -z "$ok" ]; then
|
||||||
docker logs --tail 80 scrabble-telegram || true
|
echo "$name not healthy; recent logs:"
|
||||||
|
docker logs --tail 80 "$name" || true
|
||||||
exit 1
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
- name: Prune dangling images
|
- name: Prune dangling images
|
||||||
if: always()
|
if: always()
|
||||||
|
|||||||
@@ -0,0 +1,266 @@
|
|||||||
|
# Manual production rollout. Runs ONLY from master, ONLY on workflow_dispatch with
|
||||||
|
# confirm=deploy (development->master is merged + green first; this is the separate,
|
||||||
|
# deliberate prod step). Visible sequential jobs from most to least significant:
|
||||||
|
# build -> deploy-main -> deploy-bot -> verify
|
||||||
|
# The per-service rolling (postgres->backend->gateway->landing->validator->caddy),
|
||||||
|
# health-gating and auto-rollback live in deploy/prod-deploy.sh on the main host and
|
||||||
|
# show in the deploy-main log. Manual post-deploy rollback is prod-rollback.yaml.
|
||||||
|
# See deploy/README.md (prod runbook).
|
||||||
|
name: prod-deploy
|
||||||
|
run-name: "prod deploy ${{ github.sha }}"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
confirm:
|
||||||
|
description: 'Type "deploy" to confirm a production rollout from master.'
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
NO_COLOR: "1"
|
||||||
|
DOCKER_CLI_HINTS: "false"
|
||||||
|
REGISTRY: docker.iliadenisov.ru/developer
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
if: ${{ github.ref == 'refs/heads/master' && inputs.confirm == 'deploy' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
outputs:
|
||||||
|
tag: ${{ steps.ver.outputs.tag }}
|
||||||
|
env:
|
||||||
|
PROD_REGISTRY_USER: ${{ vars.PROD_REGISTRY_USER }}
|
||||||
|
PROD_REGISTRY_PASSWORD: ${{ secrets.PROD_REGISTRY_PASSWORD }}
|
||||||
|
VITE_TELEGRAM_BOT_ID: ${{ vars.PROD_VITE_TELEGRAM_BOT_ID }}
|
||||||
|
VITE_TELEGRAM_LINK: ${{ vars.PROD_VITE_TELEGRAM_LINK }}
|
||||||
|
VITE_TELEGRAM_GAME_CHANNEL_NAME: ${{ vars.PROD_VITE_TELEGRAM_GAME_CHANNEL_NAME }}
|
||||||
|
VITE_GATEWAY_URL: ${{ vars.PROD_VITE_GATEWAY_URL }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.PROD_POSTGRES_PASSWORD }}
|
||||||
|
GM_BASICAUTH_HASH: ${{ secrets.PROD_GM_BASICAUTH_HASH }}
|
||||||
|
TELEGRAM_MINIAPP_URL: ${{ vars.PROD_TELEGRAM_MINIAPP_URL }}
|
||||||
|
DICT_VERSION: ${{ vars.PROD_DICT_VERSION }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Compute version tag
|
||||||
|
id: ver
|
||||||
|
run: echo "tag=$(git describe --tags --always)" >> "$GITHUB_OUTPUT"
|
||||||
|
- name: Registry login
|
||||||
|
run: echo "$PROD_REGISTRY_PASSWORD" | docker login "${REGISTRY%%/*}" -u "$PROD_REGISTRY_USER" --password-stdin
|
||||||
|
- name: Build and push images
|
||||||
|
working-directory: deploy
|
||||||
|
run: |
|
||||||
|
export TAG="${{ steps.ver.outputs.tag }}" APP_VERSION="${{ steps.ver.outputs.tag }}" SCRABBLE_CONFIG_DIR=.
|
||||||
|
# The four main-stack images via compose (reuses the build args, incl. VERSION);
|
||||||
|
# the bot separately, since it is profiled out of the prod compose.
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.prod.yml build
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.prod.yml push backend gateway landing validator
|
||||||
|
docker build -f ../platform/telegram/Dockerfile --target bot --build-arg VERSION="$TAG" -t "$REGISTRY/scrabble-telegram-bot:$TAG" ..
|
||||||
|
docker push "$REGISTRY/scrabble-telegram-bot:$TAG"
|
||||||
|
|
||||||
|
deploy-main:
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
TAG: ${{ needs.build.outputs.tag }}
|
||||||
|
PROD_REGISTRY_USER: ${{ vars.PROD_REGISTRY_USER }}
|
||||||
|
PROD_REGISTRY_PASSWORD: ${{ secrets.PROD_REGISTRY_PASSWORD }}
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.PROD_POSTGRES_PASSWORD }}
|
||||||
|
GM_BASICAUTH_HASH: ${{ secrets.PROD_GM_BASICAUTH_HASH }}
|
||||||
|
GRAFANA_ADMIN_PASSWORD: ${{ secrets.PROD_GRAFANA_ADMIN_PASSWORD }}
|
||||||
|
TELEGRAM_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_BOT_TOKEN }}
|
||||||
|
PROD_BOTLINK_CA: ${{ secrets.PROD_BOTLINK_CA }}
|
||||||
|
PROD_BOTLINK_GATEWAY_CERT: ${{ secrets.PROD_BOTLINK_GATEWAY_CERT }}
|
||||||
|
PROD_BOTLINK_GATEWAY_KEY: ${{ secrets.PROD_BOTLINK_GATEWAY_KEY }}
|
||||||
|
GM_BASICAUTH_USER: ${{ vars.PROD_GM_BASICAUTH_USER }}
|
||||||
|
GRAFANA_ROOT_URL: ${{ vars.PROD_GRAFANA_ROOT_URL }}
|
||||||
|
CADDY_SITE_ADDRESS: ${{ vars.PROD_CADDY_SITE_ADDRESS }}
|
||||||
|
LOG_LEVEL: ${{ vars.PROD_LOG_LEVEL }}
|
||||||
|
DICT_VERSION: ${{ vars.PROD_DICT_VERSION }}
|
||||||
|
POSTGRES_DB: ${{ vars.PROD_POSTGRES_DB }}
|
||||||
|
POSTGRES_USER: ${{ vars.PROD_POSTGRES_USER }}
|
||||||
|
TELEGRAM_MINIAPP_URL: ${{ vars.PROD_TELEGRAM_MINIAPP_URL }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Determine previous tag and migration
|
||||||
|
run: |
|
||||||
|
ssh_main() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "$@"; }
|
||||||
|
PREV_TAG="$(ssh_main 'cat /opt/scrabble/DEPLOYED_TAG 2>/dev/null || echo none')"
|
||||||
|
MIGRATION=0
|
||||||
|
if [ "$PREV_TAG" != none ]; then
|
||||||
|
if ! git cat-file -e "$PREV_TAG^{commit}" 2>/dev/null; then
|
||||||
|
MIGRATION=1
|
||||||
|
elif git diff --name-only "$PREV_TAG..$TAG" -- backend/internal/postgres/migrations/ | grep -q .; then
|
||||||
|
MIGRATION=1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
{ echo "PREV_TAG=$PREV_TAG"; echo "MIGRATION=$MIGRATION"; } >> "$GITHUB_ENV"
|
||||||
|
echo "prev=$PREV_TAG migration=$MIGRATION"
|
||||||
|
- name: Render main env + certs
|
||||||
|
run: |
|
||||||
|
umask 077
|
||||||
|
mkdir -p stage/certs-main
|
||||||
|
cat > stage/env.sh <<EOF
|
||||||
|
export REGISTRY='$REGISTRY'
|
||||||
|
export SCRABBLE_CONFIG_DIR='/opt/scrabble'
|
||||||
|
export POSTGRES_DB='${POSTGRES_DB:-scrabble}'
|
||||||
|
export POSTGRES_USER='${POSTGRES_USER:-scrabble}'
|
||||||
|
export POSTGRES_PASSWORD='$POSTGRES_PASSWORD'
|
||||||
|
export GM_BASICAUTH_USER='${GM_BASICAUTH_USER:-gm}'
|
||||||
|
export GM_BASICAUTH_HASH='$GM_BASICAUTH_HASH'
|
||||||
|
export GRAFANA_ADMIN_PASSWORD='$GRAFANA_ADMIN_PASSWORD'
|
||||||
|
export GRAFANA_ROOT_URL='$GRAFANA_ROOT_URL'
|
||||||
|
export CADDY_SITE_ADDRESS='$CADDY_SITE_ADDRESS'
|
||||||
|
export LOG_LEVEL='${LOG_LEVEL:-info}'
|
||||||
|
export DICT_VERSION='$DICT_VERSION'
|
||||||
|
export APP_VERSION='$TAG'
|
||||||
|
export TELEGRAM_BOT_TOKEN='$TELEGRAM_BOT_TOKEN'
|
||||||
|
export TELEGRAM_MINIAPP_URL='$TELEGRAM_MINIAPP_URL'
|
||||||
|
export GATEWAY_ABUSE_BAN_ENABLED='true'
|
||||||
|
EOF
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_CA" > stage/certs-main/ca.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_GATEWAY_CERT" > stage/certs-main/gateway.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_GATEWAY_KEY" > stage/certs-main/gateway.key
|
||||||
|
chmod 644 stage/certs-main/*
|
||||||
|
- name: Deploy the main host
|
||||||
|
run: |
|
||||||
|
ssh_main() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "$@"; }
|
||||||
|
ssh_main 'mkdir -p /opt/scrabble/compose'
|
||||||
|
tar -C deploy -czf - docker-compose.yml docker-compose.prod.yml prod-deploy.sh \
|
||||||
|
| ssh_main 'tar -C /opt/scrabble/compose -xzf -'
|
||||||
|
tar -C deploy -czf - caddy otelcol prometheus tempo grafana \
|
||||||
|
| ssh_main 'tar -C /opt/scrabble -xzf -'
|
||||||
|
tar -C stage -czf - certs-main \
|
||||||
|
| ssh_main 'rm -rf /opt/scrabble/certs && mkdir -p /opt/scrabble/certs && tar -C /opt/scrabble/certs --strip-components=1 -xzf -'
|
||||||
|
scp -i ~/.ssh/id_deploy -o BatchMode=yes stage/env.sh "deploy@$MAIN_HOST:/opt/scrabble/env.sh"
|
||||||
|
echo "$PROD_REGISTRY_PASSWORD" | ssh_main "docker login ${REGISTRY%%/*} -u $PROD_REGISTRY_USER --password-stdin"
|
||||||
|
ssh_main "TAG='$TAG' PREV_TAG='$PREV_TAG' MIGRATION='$MIGRATION' bash /opt/scrabble/compose/prod-deploy.sh"
|
||||||
|
|
||||||
|
deploy-bot:
|
||||||
|
needs: [build, deploy-main]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
TAG: ${{ needs.build.outputs.tag }}
|
||||||
|
PROD_REGISTRY_USER: ${{ vars.PROD_REGISTRY_USER }}
|
||||||
|
PROD_REGISTRY_PASSWORD: ${{ secrets.PROD_REGISTRY_PASSWORD }}
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
TG_HOST: ${{ vars.PROD_TG_HOST }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
TELEGRAM_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_BOT_TOKEN }}
|
||||||
|
TELEGRAM_PROMO_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_PROMO_BOT_TOKEN }}
|
||||||
|
PROD_BOTLINK_CA: ${{ secrets.PROD_BOTLINK_CA }}
|
||||||
|
PROD_BOTLINK_BOT_CERT: ${{ secrets.PROD_BOTLINK_BOT_CERT }}
|
||||||
|
PROD_BOTLINK_BOT_KEY: ${{ secrets.PROD_BOTLINK_BOT_KEY }}
|
||||||
|
LOG_LEVEL: ${{ vars.PROD_LOG_LEVEL }}
|
||||||
|
TELEGRAM_MINIAPP_URL: ${{ vars.PROD_TELEGRAM_MINIAPP_URL }}
|
||||||
|
TELEGRAM_GAME_CHANNEL_ID: ${{ vars.PROD_TELEGRAM_GAME_CHANNEL_ID }}
|
||||||
|
TELEGRAM_CHAT_ID: ${{ vars.PROD_TELEGRAM_CHAT_ID }}
|
||||||
|
TELEGRAM_BOT_USERNAME: ${{ vars.PROD_TELEGRAM_BOT_USERNAME }}
|
||||||
|
TELEGRAM_BOT_LINK: ${{ vars.PROD_VITE_TELEGRAM_LINK }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Render bot env + certs
|
||||||
|
run: |
|
||||||
|
umask 077
|
||||||
|
mkdir -p stage/certs-bot
|
||||||
|
cat > stage/env.bot.sh <<EOF
|
||||||
|
export SCRABBLE_CONFIG_DIR='/opt/scrabble'
|
||||||
|
export BOT_IMAGE='$REGISTRY/scrabble-telegram-bot:$TAG'
|
||||||
|
export BOTLINK_GATEWAY_ADDR='$MAIN_HOST:9443'
|
||||||
|
export TELEGRAM_BOT_TOKEN='$TELEGRAM_BOT_TOKEN'
|
||||||
|
export TELEGRAM_MINIAPP_URL='$TELEGRAM_MINIAPP_URL'
|
||||||
|
export TELEGRAM_GAME_CHANNEL_ID='$TELEGRAM_GAME_CHANNEL_ID'
|
||||||
|
export TELEGRAM_CHAT_ID='$TELEGRAM_CHAT_ID'
|
||||||
|
export TELEGRAM_PROMO_BOT_TOKEN='$TELEGRAM_PROMO_BOT_TOKEN'
|
||||||
|
export TELEGRAM_BOT_USERNAME='$TELEGRAM_BOT_USERNAME'
|
||||||
|
export TELEGRAM_BOT_LINK='$TELEGRAM_BOT_LINK'
|
||||||
|
export LOG_LEVEL='${LOG_LEVEL:-info}'
|
||||||
|
EOF
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_CA" > stage/certs-bot/ca.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_BOT_CERT" > stage/certs-bot/bot.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_BOT_KEY" > stage/certs-bot/bot.key
|
||||||
|
chmod 644 stage/certs-bot/*
|
||||||
|
- name: Deploy the bot host
|
||||||
|
run: |
|
||||||
|
ssh_tg() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$TG_HOST" "$@"; }
|
||||||
|
ssh_tg 'mkdir -p /opt/scrabble/compose'
|
||||||
|
tar -C deploy -czf - docker-compose.bot.yml | ssh_tg 'tar -C /opt/scrabble/compose -xzf -'
|
||||||
|
tar -C stage -czf - certs-bot \
|
||||||
|
| ssh_tg 'rm -rf /opt/scrabble/certs && mkdir -p /opt/scrabble/certs && tar -C /opt/scrabble/certs --strip-components=1 -xzf -'
|
||||||
|
scp -i ~/.ssh/id_deploy -o BatchMode=yes stage/env.bot.sh "deploy@$TG_HOST:/opt/scrabble/env.bot.sh"
|
||||||
|
echo "$PROD_REGISTRY_PASSWORD" | ssh_tg "docker login ${REGISTRY%%/*} -u $PROD_REGISTRY_USER --password-stdin"
|
||||||
|
ssh_tg 'set -a; . /opt/scrabble/env.bot.sh; set +a; cd /opt/scrabble/compose;
|
||||||
|
docker compose -f docker-compose.bot.yml pull;
|
||||||
|
docker compose -f docker-compose.bot.yml up -d'
|
||||||
|
ssh_tg 'for i in $(seq 1 20); do
|
||||||
|
s=$(docker inspect -f "{{.State.Status}}" scrabble-telegram-bot 2>/dev/null || echo missing)
|
||||||
|
r=$(docker inspect -f "{{.State.Restarting}}" scrabble-telegram-bot 2>/dev/null || echo true)
|
||||||
|
if [ "$s" = running ] && [ "$r" = false ]; then
|
||||||
|
c1=$(docker inspect -f "{{.RestartCount}}" scrabble-telegram-bot); sleep 5
|
||||||
|
c2=$(docker inspect -f "{{.RestartCount}}" scrabble-telegram-bot)
|
||||||
|
[ "$c1" = "$c2" ] && { echo "bot healthy"; exit 0; }
|
||||||
|
fi
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
echo "bot not healthy:"; docker logs --tail 80 scrabble-telegram-bot; exit 1'
|
||||||
|
|
||||||
|
verify:
|
||||||
|
needs: [deploy-main, deploy-bot]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
CADDY_SITE_ADDRESS: ${{ vars.PROD_CADDY_SITE_ADDRESS }}
|
||||||
|
steps:
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Verify the public site
|
||||||
|
run: |
|
||||||
|
domain="${CADDY_SITE_ADDRESS%% *}"
|
||||||
|
ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "for i in \$(seq 1 20); do
|
||||||
|
if curl -fsS -k --resolve $domain:443:127.0.0.1 https://$domain/ -o /dev/null &&
|
||||||
|
curl -fsS -k --resolve $domain:443:127.0.0.1 https://$domain/app/ -o /dev/null &&
|
||||||
|
docker run --rm --network scrabble-internal alpine:3.20 wget -q -T 5 -O /dev/null http://backend:8080/readyz; then
|
||||||
|
echo 'public site + /app/ + backend healthy'; exit 0
|
||||||
|
fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo 'public verify failed; recent caddy + gateway + backend logs:'
|
||||||
|
docker logs --tail 40 scrabble-caddy; docker logs --tail 40 scrabble-gateway; docker logs --tail 40 scrabble-backend
|
||||||
|
exit 1"
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
# Manual production rollback. Runs ONLY from master, ONLY on workflow_dispatch with
|
||||||
|
# confirm=rollback. Re-deploys an already-published image tag (no build): leave
|
||||||
|
# target_version blank to roll back to the previously deployed version (read from the
|
||||||
|
# main host), or set it to a specific release tag from the Releases page. The
|
||||||
|
# re-deploy is the same rolling, health-gated path as prod-deploy (TAG=target,
|
||||||
|
# MIGRATION=0 — rollback is image-only and never migrates the DB; image rollback is
|
||||||
|
# DB-safe under the expand-contract rule). See deploy/README.md (prod runbook).
|
||||||
|
name: prod-rollback
|
||||||
|
run-name: "prod rollback ${{ inputs.target_version || 'previous' }}"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
confirm:
|
||||||
|
description: 'Type "rollback" to confirm a production rollback.'
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
target_version:
|
||||||
|
description: "Release tag to roll back to (blank = the previous deployed version)."
|
||||||
|
required: false
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
NO_COLOR: "1"
|
||||||
|
DOCKER_CLI_HINTS: "false"
|
||||||
|
REGISTRY: docker.iliadenisov.ru/developer
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
rollback-main:
|
||||||
|
if: ${{ github.ref == 'refs/heads/master' && inputs.confirm == 'rollback' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
outputs:
|
||||||
|
target: ${{ steps.resolve.outputs.target }}
|
||||||
|
env:
|
||||||
|
PROD_REGISTRY_USER: ${{ vars.PROD_REGISTRY_USER }}
|
||||||
|
PROD_REGISTRY_PASSWORD: ${{ secrets.PROD_REGISTRY_PASSWORD }}
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.PROD_POSTGRES_PASSWORD }}
|
||||||
|
GM_BASICAUTH_HASH: ${{ secrets.PROD_GM_BASICAUTH_HASH }}
|
||||||
|
GRAFANA_ADMIN_PASSWORD: ${{ secrets.PROD_GRAFANA_ADMIN_PASSWORD }}
|
||||||
|
TELEGRAM_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_BOT_TOKEN }}
|
||||||
|
PROD_BOTLINK_CA: ${{ secrets.PROD_BOTLINK_CA }}
|
||||||
|
PROD_BOTLINK_GATEWAY_CERT: ${{ secrets.PROD_BOTLINK_GATEWAY_CERT }}
|
||||||
|
PROD_BOTLINK_GATEWAY_KEY: ${{ secrets.PROD_BOTLINK_GATEWAY_KEY }}
|
||||||
|
GM_BASICAUTH_USER: ${{ vars.PROD_GM_BASICAUTH_USER }}
|
||||||
|
GRAFANA_ROOT_URL: ${{ vars.PROD_GRAFANA_ROOT_URL }}
|
||||||
|
CADDY_SITE_ADDRESS: ${{ vars.PROD_CADDY_SITE_ADDRESS }}
|
||||||
|
LOG_LEVEL: ${{ vars.PROD_LOG_LEVEL }}
|
||||||
|
DICT_VERSION: ${{ vars.PROD_DICT_VERSION }}
|
||||||
|
POSTGRES_DB: ${{ vars.PROD_POSTGRES_DB }}
|
||||||
|
POSTGRES_USER: ${{ vars.PROD_POSTGRES_USER }}
|
||||||
|
TELEGRAM_MINIAPP_URL: ${{ vars.PROD_TELEGRAM_MINIAPP_URL }}
|
||||||
|
INPUT_TARGET: ${{ inputs.target_version }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Resolve rollback target
|
||||||
|
id: resolve
|
||||||
|
run: |
|
||||||
|
ssh_main() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "$@"; }
|
||||||
|
CURRENT="$(ssh_main 'cat /opt/scrabble/DEPLOYED_TAG 2>/dev/null || echo none')"
|
||||||
|
if [ -n "$INPUT_TARGET" ]; then
|
||||||
|
TARGET="$INPUT_TARGET"
|
||||||
|
else
|
||||||
|
TARGET="$(ssh_main 'cat /opt/scrabble/PREVIOUS_TAG 2>/dev/null || echo none')"
|
||||||
|
fi
|
||||||
|
if [ -z "$TARGET" ] || [ "$TARGET" = none ]; then
|
||||||
|
echo "no rollback target (no PREVIOUS_TAG on the host and no target_version input)"; exit 1
|
||||||
|
fi
|
||||||
|
if [ "$TARGET" = "$CURRENT" ]; then
|
||||||
|
echo "target $TARGET is already the deployed version; nothing to do"; exit 1
|
||||||
|
fi
|
||||||
|
echo "rolling back: current=$CURRENT -> target=$TARGET"
|
||||||
|
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
|
||||||
|
{ echo "TARGET=$TARGET"; echo "CURRENT=$CURRENT"; } >> "$GITHUB_ENV"
|
||||||
|
- name: Render main env + certs
|
||||||
|
run: |
|
||||||
|
umask 077
|
||||||
|
mkdir -p stage/certs-main
|
||||||
|
cat > stage/env.sh <<EOF
|
||||||
|
export REGISTRY='$REGISTRY'
|
||||||
|
export SCRABBLE_CONFIG_DIR='/opt/scrabble'
|
||||||
|
export POSTGRES_DB='${POSTGRES_DB:-scrabble}'
|
||||||
|
export POSTGRES_USER='${POSTGRES_USER:-scrabble}'
|
||||||
|
export POSTGRES_PASSWORD='$POSTGRES_PASSWORD'
|
||||||
|
export GM_BASICAUTH_USER='${GM_BASICAUTH_USER:-gm}'
|
||||||
|
export GM_BASICAUTH_HASH='$GM_BASICAUTH_HASH'
|
||||||
|
export GRAFANA_ADMIN_PASSWORD='$GRAFANA_ADMIN_PASSWORD'
|
||||||
|
export GRAFANA_ROOT_URL='$GRAFANA_ROOT_URL'
|
||||||
|
export CADDY_SITE_ADDRESS='$CADDY_SITE_ADDRESS'
|
||||||
|
export LOG_LEVEL='${LOG_LEVEL:-info}'
|
||||||
|
export DICT_VERSION='$DICT_VERSION'
|
||||||
|
export APP_VERSION='$TARGET'
|
||||||
|
export TELEGRAM_BOT_TOKEN='$TELEGRAM_BOT_TOKEN'
|
||||||
|
export TELEGRAM_MINIAPP_URL='$TELEGRAM_MINIAPP_URL'
|
||||||
|
export GATEWAY_ABUSE_BAN_ENABLED='true'
|
||||||
|
EOF
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_CA" > stage/certs-main/ca.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_GATEWAY_CERT" > stage/certs-main/gateway.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_GATEWAY_KEY" > stage/certs-main/gateway.key
|
||||||
|
chmod 644 stage/certs-main/*
|
||||||
|
- name: Roll the main host back
|
||||||
|
run: |
|
||||||
|
ssh_main() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "$@"; }
|
||||||
|
ssh_main 'mkdir -p /opt/scrabble/compose'
|
||||||
|
tar -C deploy -czf - docker-compose.yml docker-compose.prod.yml prod-deploy.sh \
|
||||||
|
| ssh_main 'tar -C /opt/scrabble/compose -xzf -'
|
||||||
|
tar -C deploy -czf - caddy otelcol prometheus tempo grafana \
|
||||||
|
| ssh_main 'tar -C /opt/scrabble -xzf -'
|
||||||
|
tar -C stage -czf - certs-main \
|
||||||
|
| ssh_main 'rm -rf /opt/scrabble/certs && mkdir -p /opt/scrabble/certs && tar -C /opt/scrabble/certs --strip-components=1 -xzf -'
|
||||||
|
scp -i ~/.ssh/id_deploy -o BatchMode=yes stage/env.sh "deploy@$MAIN_HOST:/opt/scrabble/env.sh"
|
||||||
|
echo "$PROD_REGISTRY_PASSWORD" | ssh_main "docker login ${REGISTRY%%/*} -u $PROD_REGISTRY_USER --password-stdin"
|
||||||
|
# Image-only rollback: no migration window (TAG=target, MIGRATION=0). A failed
|
||||||
|
# rollback's auto-revert returns to the current version (PREV_TAG=$CURRENT).
|
||||||
|
ssh_main "TAG='$TARGET' PREV_TAG='$CURRENT' MIGRATION=0 bash /opt/scrabble/compose/prod-deploy.sh"
|
||||||
|
|
||||||
|
rollback-bot:
|
||||||
|
needs: rollback-main
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
TARGET: ${{ needs.rollback-main.outputs.target }}
|
||||||
|
PROD_REGISTRY_USER: ${{ vars.PROD_REGISTRY_USER }}
|
||||||
|
PROD_REGISTRY_PASSWORD: ${{ secrets.PROD_REGISTRY_PASSWORD }}
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
TG_HOST: ${{ vars.PROD_TG_HOST }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
TELEGRAM_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_BOT_TOKEN }}
|
||||||
|
TELEGRAM_PROMO_BOT_TOKEN: ${{ secrets.PROD_TELEGRAM_PROMO_BOT_TOKEN }}
|
||||||
|
PROD_BOTLINK_CA: ${{ secrets.PROD_BOTLINK_CA }}
|
||||||
|
PROD_BOTLINK_BOT_CERT: ${{ secrets.PROD_BOTLINK_BOT_CERT }}
|
||||||
|
PROD_BOTLINK_BOT_KEY: ${{ secrets.PROD_BOTLINK_BOT_KEY }}
|
||||||
|
LOG_LEVEL: ${{ vars.PROD_LOG_LEVEL }}
|
||||||
|
TELEGRAM_MINIAPP_URL: ${{ vars.PROD_TELEGRAM_MINIAPP_URL }}
|
||||||
|
TELEGRAM_GAME_CHANNEL_ID: ${{ vars.PROD_TELEGRAM_GAME_CHANNEL_ID }}
|
||||||
|
TELEGRAM_CHAT_ID: ${{ vars.PROD_TELEGRAM_CHAT_ID }}
|
||||||
|
TELEGRAM_BOT_USERNAME: ${{ vars.PROD_TELEGRAM_BOT_USERNAME }}
|
||||||
|
TELEGRAM_BOT_LINK: ${{ vars.PROD_VITE_TELEGRAM_LINK }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Render bot env + certs
|
||||||
|
run: |
|
||||||
|
umask 077
|
||||||
|
mkdir -p stage/certs-bot
|
||||||
|
cat > stage/env.bot.sh <<EOF
|
||||||
|
export SCRABBLE_CONFIG_DIR='/opt/scrabble'
|
||||||
|
export BOT_IMAGE='$REGISTRY/scrabble-telegram-bot:$TARGET'
|
||||||
|
export BOTLINK_GATEWAY_ADDR='$MAIN_HOST:9443'
|
||||||
|
export TELEGRAM_BOT_TOKEN='$TELEGRAM_BOT_TOKEN'
|
||||||
|
export TELEGRAM_MINIAPP_URL='$TELEGRAM_MINIAPP_URL'
|
||||||
|
export TELEGRAM_GAME_CHANNEL_ID='$TELEGRAM_GAME_CHANNEL_ID'
|
||||||
|
export TELEGRAM_CHAT_ID='$TELEGRAM_CHAT_ID'
|
||||||
|
export TELEGRAM_PROMO_BOT_TOKEN='$TELEGRAM_PROMO_BOT_TOKEN'
|
||||||
|
export TELEGRAM_BOT_USERNAME='$TELEGRAM_BOT_USERNAME'
|
||||||
|
export TELEGRAM_BOT_LINK='$TELEGRAM_BOT_LINK'
|
||||||
|
export LOG_LEVEL='${LOG_LEVEL:-info}'
|
||||||
|
EOF
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_CA" > stage/certs-bot/ca.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_BOT_CERT" > stage/certs-bot/bot.crt
|
||||||
|
printf '%s\n' "$PROD_BOTLINK_BOT_KEY" > stage/certs-bot/bot.key
|
||||||
|
chmod 644 stage/certs-bot/*
|
||||||
|
- name: Roll the bot host back
|
||||||
|
run: |
|
||||||
|
ssh_tg() { ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$TG_HOST" "$@"; }
|
||||||
|
ssh_tg 'mkdir -p /opt/scrabble/compose'
|
||||||
|
tar -C deploy -czf - docker-compose.bot.yml | ssh_tg 'tar -C /opt/scrabble/compose -xzf -'
|
||||||
|
tar -C stage -czf - certs-bot \
|
||||||
|
| ssh_tg 'rm -rf /opt/scrabble/certs && mkdir -p /opt/scrabble/certs && tar -C /opt/scrabble/certs --strip-components=1 -xzf -'
|
||||||
|
scp -i ~/.ssh/id_deploy -o BatchMode=yes stage/env.bot.sh "deploy@$TG_HOST:/opt/scrabble/env.bot.sh"
|
||||||
|
echo "$PROD_REGISTRY_PASSWORD" | ssh_tg "docker login ${REGISTRY%%/*} -u $PROD_REGISTRY_USER --password-stdin"
|
||||||
|
ssh_tg 'set -a; . /opt/scrabble/env.bot.sh; set +a; cd /opt/scrabble/compose;
|
||||||
|
docker compose -f docker-compose.bot.yml pull;
|
||||||
|
docker compose -f docker-compose.bot.yml up -d'
|
||||||
|
|
||||||
|
verify:
|
||||||
|
needs: [rollback-main, rollback-bot]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }}
|
||||||
|
PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }}
|
||||||
|
MAIN_HOST: ${{ vars.PROD_MAIN_HOST }}
|
||||||
|
CADDY_SITE_ADDRESS: ${{ vars.PROD_CADDY_SITE_ADDRESS }}
|
||||||
|
steps:
|
||||||
|
- name: Set up SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||||
|
printf '%s\n' "$PROD_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy
|
||||||
|
printf '%s\n' "$PROD_SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||||
|
- name: Verify the public site
|
||||||
|
run: |
|
||||||
|
domain="${CADDY_SITE_ADDRESS%% *}"
|
||||||
|
ssh -i ~/.ssh/id_deploy -o BatchMode=yes "deploy@$MAIN_HOST" "for i in \$(seq 1 20); do
|
||||||
|
if curl -fsS -k --resolve $domain:443:127.0.0.1 https://$domain/ -o /dev/null &&
|
||||||
|
docker run --rm --network scrabble-internal alpine:3.20 wget -q -T 5 -O /dev/null http://backend:8080/readyz; then
|
||||||
|
echo 'rolled-back site healthy'; exit 0
|
||||||
|
fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo 'verify failed'; docker logs --tail 40 scrabble-caddy; docker logs --tail 40 scrabble-backend; exit 1"
|
||||||
@@ -17,5 +17,9 @@
|
|||||||
**/.env.local
|
**/.env.local
|
||||||
**/.env.*.local
|
**/.env.*.local
|
||||||
|
|
||||||
|
# Bot-link mTLS material: private keys never belong in the repo. The test contour
|
||||||
|
# generates them with deploy/gen-certs.sh; prod supplies them from PROD_ secrets.
|
||||||
|
deploy/certs/
|
||||||
|
|
||||||
# Claude Code harness runtime artifacts
|
# Claude Code harness runtime artifacts
|
||||||
.claude/scheduled_tasks.lock
|
.claude/scheduled_tasks.lock
|
||||||
|
|||||||
@@ -125,9 +125,9 @@ backend/ # module scrabble/backend
|
|||||||
internal/inttest/ # //go:build integration Postgres-backed tests
|
internal/inttest/ # //go:build integration Postgres-backed tests
|
||||||
docs/ .gitea/workflows/ PLAN.md CLAUDE.md README.md
|
docs/ .gitea/workflows/ PLAN.md CLAUDE.md README.md
|
||||||
gateway/ ui/ pkg/ # added by their stages
|
gateway/ ui/ pkg/ # added by their stages
|
||||||
platform/telegram/ # Telegram connector side-service (Stage 9): bot + gRPC API
|
platform/telegram/ # Telegram side-service, two binaries (Stage 9; split in phase TX): cmd/validator (HMAC, no VPN) + cmd/bot (Bot API; dials gateway over reverse mTLS bot-link)
|
||||||
loadtest/ # module scrabble/loadtest: the pre-release stress harness (R2)
|
loadtest/ # module scrabble/loadtest: the pre-release stress harness (R2)
|
||||||
backend/Dockerfile gateway/Dockerfile platform/telegram/Dockerfile loadtest/Dockerfile # multi-stage distroless (Stage 16; loadtest R2); gateway/Dockerfile also has the `landing` target (R3)
|
backend/Dockerfile gateway/Dockerfile platform/telegram/Dockerfile loadtest/Dockerfile # multi-stage distroless (Stage 16; loadtest R2); gateway/Dockerfile has the `landing` target (R3), platform/telegram/Dockerfile has `validator`+`bot` targets (TX)
|
||||||
deploy/ # docker-compose (per-service limits, R7) + caddy + landing + otelcol (OTLP + docker_stats per-container metrics) + prometheus/tempo/grafana + postgres_exporter
|
deploy/ # docker-compose (per-service limits, R7) + caddy + landing + otelcol (OTLP + docker_stats per-container metrics) + prometheus/tempo/grafana + postgres_exporter
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -138,7 +138,7 @@ go build ./backend/... # per module ('./...' from the root won't span t
|
|||||||
go vet ./backend/...
|
go vet ./backend/...
|
||||||
gofmt -l . # must print nothing
|
gofmt -l . # must print nothing
|
||||||
go test -count=1 ./backend/...
|
go test -count=1 ./backend/...
|
||||||
go build ./platform/telegram/... && go test ./platform/telegram/... # Telegram connector (Stage 9)
|
go build ./platform/telegram/... && go test ./platform/telegram/... # Telegram validator + bot (Stage 9; split in TX)
|
||||||
go run ./backend/cmd/backend # /healthz, /readyz on :8080
|
go run ./backend/cmd/backend # /healthz, /readyz on :8080
|
||||||
|
|
||||||
cd ui && pnpm install && pnpm check && pnpm test:unit && pnpm build # the UI (Stage 7+)
|
cd ui && pnpm install && pnpm check && pnpm test:unit && pnpm build # the UI (Stage 7+)
|
||||||
|
|||||||
@@ -51,7 +51,8 @@ independent (see ARCHITECTURE §9.1).
|
|||||||
| 15 | Dual Telegram bots & language-gated variants | **done** |
|
| 15 | Dual Telegram bots & language-gated variants | **done** |
|
||||||
| 16 | Deploy infra & test contour (Dockerfiles, gateway static UI, compose, observability) | **done** |
|
| 16 | Deploy infra & test contour (Dockerfiles, gateway static UI, compose, observability) | **done** |
|
||||||
| 17 | Test-contour verification & defect fixes | **done** |
|
| 17 | Test-contour verification & defect fixes | **done** |
|
||||||
| 18 | Prod contour deploy (SSH export/import, manual after merge) | todo |
|
| 18 | Prod contour deploy (registry, two-host, rolling + auto-rollback; manual after merge) | machinery built; first cutover pending DNS |
|
||||||
|
| 19 | User feedback (in-app submit + attachment, admin review/reply, account roles) | **done** |
|
||||||
|
|
||||||
Scaffolding is incremental: `go.work` lists only existing modules; each stage
|
Scaffolding is incremental: `go.work` lists only existing modules; each stage
|
||||||
adds the modules it needs.
|
adds the modules it needs.
|
||||||
@@ -280,6 +281,12 @@ back to `preferred_language`). Non-Telegram logins (web/email/guest) carry the g
|
|||||||
(`GATEWAY_DEFAULT_SUPPORTED_LANGUAGES`, all variants). Admin broadcasts (`SendToUser`/`SendToGameChannel`)
|
(`GATEWAY_DEFAULT_SUPPORTED_LANGUAGES`, all variants). Admin broadcasts (`SendToUser`/`SendToGameChannel`)
|
||||||
pick the bot by an **operator-chosen** language in the console — unrelated to `ValidateInitData`.
|
pick the bot by an **operator-chosen** language in the console — unrelated to `ValidateInitData`.
|
||||||
|
|
||||||
|
> **Superseded (2026-06-20, pre-release phase SB):** the two bots collapsed into **one** and the
|
||||||
|
> language-gated variant choice moved to a per-user **`variant_preferences`** profile set (default Erudit
|
||||||
|
> only). `accounts.service_language`, `supported_languages`, the `*_EN`/`*_RU` env vars,
|
||||||
|
> `GATEWAY_DEFAULT_SUPPORTED_LANGUAGES` and game-language push routing are gone; the single bot renders in
|
||||||
|
> the recipient's `preferred_language`. Current state: `docs/ARCHITECTURE.md` §3/§10, `PRERELEASE.md` row SB.
|
||||||
|
|
||||||
### Stage 16 — Deploy infra & test contour *(done)*
|
### Stage 16 — Deploy infra & test contour *(done)*
|
||||||
Scope: the deploy machinery + the **test contour** (the bulk of the original Stage 14). Backend +
|
Scope: the deploy machinery + the **test contour** (the bulk of the original Stage 14). Backend +
|
||||||
gateway **Dockerfiles** (multi-stage distroless, mirroring the Stage 9 connector image); the gateway
|
gateway **Dockerfiles** (multi-stage distroless, mirroring the Stage 9 connector image); the gateway
|
||||||
@@ -406,18 +413,59 @@ raw list is kept here as the record of what the first contour run surfaced.
|
|||||||
"что-то пошло не так". при этом "new -> эрудит" работает. Попробуй посмотреть в логах сейчас, может что-то есть. Или как-то иначе проанализируй, или давай вместе будем смотреть, если не получится.
|
"что-то пошло не так". при этом "new -> эрудит" работает. Попробуй посмотреть в логах сейчас, может что-то есть. Или как-то иначе проанализируй, или давай вместе будем смотреть, если не получится.
|
||||||
|
|
||||||
### Stage 18 — Prod contour deploy
|
### Stage 18 — Prod contour deploy
|
||||||
Scope: the **production contour** on a remote host over SSH. Deploy by **container export/import**
|
Scope: the **production contour** on **two remote hosts** over SSH — main (full stack, `erudit-game.ru`)
|
||||||
(`docker save` → `scp`/ssh → `docker load` → `docker compose up` on the remote), the SSH key + host IP
|
and tg (the bot only). Resolved open details (re-interviewed):
|
||||||
in Gitea secrets; **strictly manual** (`workflow_dispatch`) after `development` is merged to `master`
|
- **Transport: a registry** (not export/import) — build + push to `docker.iliadenisov.ru`, the hosts pull by tag.
|
||||||
(the Stage 16 branch model: `feature/* → development → master`, merge gated green). Two-contour config
|
- **Cert: ACME** at the contour caddy (`CADDY_SITE_ADDRESS=erudit-game.ru www.erudit-game.ru`, no host caddy).
|
||||||
uses **`TEST_`/`PROD_` secret/variable prefixes** — Gitea 1.26 has no deployment environments (verified:
|
- **No prod VPN** — the bot host has native Bot API egress (verified `api.telegram.org` → 200).
|
||||||
the `environments` API 404s), so a flat prefixed namespace is the convention.
|
- **Rollback** — rolling per-service deploy (least → most dependent), health-gated, auto-rollback to the
|
||||||
Reuses the Stage 16 `deploy/docker-compose.yml` as-is, mapping the **`PROD_`** set onto the same
|
previous image tag; a maintenance window + consistent `pg_dump` only on a schema migration
|
||||||
unprefixed compose vars. **No host caddy on prod**, so the contour's own caddy terminates TLS — set
|
(expand-contract keeps the auto-rollback image-only; the dump is a manual safety net).
|
||||||
`CADDY_SITE_ADDRESS` to the prod domain so caddy does its own ACME (the Caddyfile is already
|
|
||||||
parameterised for this; the test contour leaves it `:80` behind the host caddy).
|
**Strictly manual** (`workflow_dispatch` from `master`, `confirm=deploy`) after `development → master`
|
||||||
Open details (re-interview): export/import vs a registry trade-off; prod domain/cert source (ACME vs a
|
is merged green. `TEST_`/`PROD_` prefixed Gitea secrets/variables (Gitea 1.26 has no deployment
|
||||||
provided cert) at the contour caddy; prod VPN; rollback.
|
environments — the `environments` API 404s). Hosts are provisioned by **`deploy/ansible/`** (docker, a
|
||||||
|
non-sudo `deploy` user with the CI key, key-only sshd, ufw, fail2ban). The main host is **launch-sized**
|
||||||
|
(2 vCPU / 1.9 GiB): `docker-compose.prod.yml` trims the R7 limits (`GOMAXPROCS=2`, smaller caps, 7d
|
||||||
|
Prometheus retention) and adds `node_exporter` for host-memory monitoring (launch undersized, resize at
|
||||||
|
Selectel reactively). `vpn`+`bot` are gated to a `telegram-local` compose profile (test only); the prod
|
||||||
|
bot runs standalone from `docker-compose.bot.yml`. `GATEWAY_ABUSE_BAN_ENABLED=true`.
|
||||||
|
|
||||||
|
**Built:** `deploy/ansible/` (both hosts provisioned + verified), the compose split + `node_exporter`,
|
||||||
|
`.gitea/workflows/prod-deploy.yaml` + `deploy/prod-deploy.sh`, the full `PROD_` secret/variable set.
|
||||||
|
**Remaining (acceptance):** the **first live cutover** — waits on the `erudit-game.ru` DNS delegation
|
||||||
|
(`A`/`www` → the main host) that ACME requires; then run the workflow and verify the public site end-to-end.
|
||||||
|
|
||||||
|
### Stage 19 — User feedback *(done)*
|
||||||
|
A user→operator feedback channel, sequenced after the numbered stages but shipped **before** the Stage 18
|
||||||
|
prod deploy. Scope: a **Feedback** screen under Settings → Info where a registered player sends a message
|
||||||
|
(≤1024 runes) with an optional single attachment; the operator reviews and replies in the server-rendered
|
||||||
|
**admin console**; the reply is delivered back in-app with a Settings/Info badge. Introduces the project's
|
||||||
|
**first per-account role** (`account_roles`), the reusable replacement for per-feature flags: the
|
||||||
|
`feedback_banned` role blocks **only** feedback submission (not the whole account, unlike a suspension),
|
||||||
|
granted from the feedback section's delete-with-block and granted/revoked from `/users`.
|
||||||
|
|
||||||
|
- **Data:** migration `00004_feedback` — `feedback_messages` (body, attachment `bytea`, sender_ip, channel,
|
||||||
|
read/archived/reply/reply-read timestamps) + `account_roles` (account_id, role). New backend domain
|
||||||
|
`internal/feedback` (store + service), modelled on `internal/social` + the admin chat-moderation surface.
|
||||||
|
- **Anti-spam gate:** a player with an unreviewed message cannot send another ("Ожидаем рассмотрения вашего
|
||||||
|
последнего обращения"); enforced server-side. This *is* the rate limit — no separate one.
|
||||||
|
- **Reply lifecycle:** the reply lives on the message row; shown on the feedback screen ("Ответ на ваше
|
||||||
|
последнее сообщение") for the player's latest replied message; it becomes read the moment the screen
|
||||||
|
fetches it (delivery = read) and is hidden one week after. The badge (lobby ⚙️, combined with friend
|
||||||
|
requests; Settings → Info "1") rides the existing `NotificationEvent` with a new `admin_reply` sub-kind —
|
||||||
|
no wire-schema change for the push.
|
||||||
|
- **Wire:** new FlatBuffers `feedback.submit` / `feedback.get` / `feedback.unread`; `feedback.submit` is
|
||||||
|
**guest-gated at the gateway** via a new `Op.NonGuest` flag (the session resolve now carries `is_guest`),
|
||||||
|
so a guest's submission never reaches the backend; the backend rejects guests too.
|
||||||
|
- **Security:** body + attachment limits enforced server-side (the UI limits are UX only); attachments
|
||||||
|
served with `X-Content-Type-Options: nosniff`, images inline-previewed via `<img>` (which never
|
||||||
|
executes), everything else download-only; the UI gates the attachment by extension (allowed types not
|
||||||
|
listed) and the backend mirrors the allow-list + size as the trust boundary; the console renders user
|
||||||
|
content as auto-escaped text (`html/template`).
|
||||||
|
Open details settled at planning: attachment ≤1,000,000 B (keeps the 1 MiB edge cap); allowed types
|
||||||
|
(images + pdf/txt/log/doc/docx/rtf/zip/gz/7z); channel from the client (telegram/ios/android/web); guests
|
||||||
|
cannot submit; three-way admin filter.
|
||||||
|
|
||||||
## Refinements logged during implementation
|
## Refinements logged during implementation
|
||||||
|
|
||||||
@@ -616,7 +664,10 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
- **Margin** (interview): pick the candidate whose resulting margin (own+move−opp)
|
- **Margin** (interview): pick the candidate whose resulting margin (own+move−opp)
|
||||||
is closest to **[1,30]** when playing to win / **[−30,−1]** when playing to lose,
|
is closest to **[1,30]** when playing to win / **[−30,−1]** when playing to lose,
|
||||||
tie-broken toward the conservative edge; no legal play → exchange the full rack
|
tie-broken toward the conservative edge; no legal play → exchange the full rack
|
||||||
when the bag can refill it, else pass.
|
when the bag can refill it, else pass. *(Later refined — separate PR: on ≈20% of
|
||||||
|
opening/midgame moves the robot flips its intent for that one move, the chance
|
||||||
|
tapering to 0 over the last 14 bag tiles and 0 at an empty bag, so the endgame
|
||||||
|
stays strict; deterministic from the seed.)*
|
||||||
- **Substitution** (interview): a matchmaker **reaper** (`Reap`/`RunReaper`)
|
- **Substitution** (interview): a matchmaker **reaper** (`Reap`/`RunReaper`)
|
||||||
substitutes a pooled robot after a **10 s** wait (`BACKEND_LOBBY_ROBOT_WAIT`),
|
substitutes a pooled robot after a **10 s** wait (`BACKEND_LOBBY_ROBOT_WAIT`),
|
||||||
`NewMatchmaker` now takes a `RobotProvider`. A waiter learns of a match — human
|
`NewMatchmaker` now takes a `RobotProvider`. A waiter learns of a match — human
|
||||||
@@ -741,7 +792,7 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
reusable **HoldConfirm** press-and-hold control (MakeMove 🏁 + game-action confirms);
|
reusable **HoldConfirm** press-and-hold control (MakeMove 🏁 + game-action confirms);
|
||||||
board **zoom reworked** to a width-based zoom in a fixed viewport (real native
|
board **zoom reworked** to a width-based zoom in a fixed viewport (real native
|
||||||
scroll, double-tap; pinch/swipe dropped) with constant `cqw` labels, corner-letter
|
scroll, double-tap; pinch/swipe dropped) with constant `cqw` labels, corner-letter
|
||||||
tiles, contrasting grid lines, last-word dark-tile highlight, and a Settings
|
tiles, last-word dark-tile highlight, and a Settings
|
||||||
**bonus-label style** (beginner/
|
**bonus-label style** (beginner/
|
||||||
classic/none); **hint lays its tiles on the board** (no spend when no move — a new
|
classic/none); **hint lays its tiles on the board** (no spend when no move — a new
|
||||||
`no_hint_available` result code); the history opens as an in-place **slide-down**
|
`no_hint_available` result code); the history opens as an in-place **slide-down**
|
||||||
@@ -1223,6 +1274,17 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
first + surname initial / first + full surname), composed deterministically per pool slot (stable
|
first + surname initial / first + full surname), composed deterministically per pool slot (stable
|
||||||
across restarts). `Pick(variant)` is variant-aware: a Russian game draws Russian names with ≤ ~20%
|
across restarts). `Pick(variant)` is variant-aware: a Russian game draws Russian names with ≤ ~20%
|
||||||
Latin, an English game the Latin pool. Robot identities are keyed `robot-<lang>-<index>`.
|
Latin, an English game the Latin pool. Robot identities are keyed `robot-<lang>-<index>`.
|
||||||
|
- **Robot names — per-game variety** (post-release, 2026-06): the seeded pools above now only back
|
||||||
|
each account's *fallback* name. The disguised reaper stamps a **fresh per-game name** on the robot's
|
||||||
|
seat — a new `game_players.display_name` snapshot, which also captures humans' names so a later rename
|
||||||
|
no longer rewrites past games (a reader falls back to the account name for a pre-migration row). The
|
||||||
|
name is drawn from a wide composed corpus (`internal/robot/namevariety.go`): Western locales
|
||||||
|
(EN/DE/ES/IT/FR/PT), native Japanese/Chinese names, a gender-agreed Russian pool, and human-style
|
||||||
|
handles (stem + optional `.`/`_` + optional trailing number). Routing keeps the spirit of `Pick`
|
||||||
|
(Russian: Cyrillic + ≤20% Latin, never a CJK script; English: the full corpus) via `robot.PickNamed`.
|
||||||
|
`account.ValidateDisplayName` was loosened to admit a **trailing run of ≤5 digits** (mirrored in
|
||||||
|
`ui/src/lib/profileValidation.ts`), so "Player2007"-style handles are valid for humans too and the
|
||||||
|
disguised robot stays indistinguishable.
|
||||||
- **Robot timing** (#4, interview): the fixed `2 + 88·u^3.5` move delay became move-number-aware — the
|
- **Robot timing** (#4, interview): the fixed `2 + 88·u^3.5` move delay became move-number-aware — the
|
||||||
band interpolates from [3,10] min at the first move (raised from [1,5] in round 4, #14) to [10,90] min
|
band interpolates from [3,10] min at the first move (raised from [1,5] in round 4, #14) to [10,90] min
|
||||||
by ~28 moves, right-skewed by k=4, so early moves are quick and the endgame can be long. A daytime
|
by ~28 moves, right-skewed by k=4, so early moves are quick and the endgame can be long. A daytime
|
||||||
@@ -1393,9 +1455,9 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
docker-network caddy hop `172.18.0.x` for chat moderation, and bucketing the gateway's
|
docker-network caddy hop `172.18.0.x` for chat moderation, and bucketing the gateway's
|
||||||
per-IP rate limiter on it). Correct + spoof-safe in **both** contours (prod has no host
|
per-IP rate limiter on it). Correct + spoof-safe in **both** contours (prod has no host
|
||||||
caddy → public clients untrusted → real peer used). `peerIP` unit-tested.
|
caddy → public clients untrusted → real peer used). `peerIP` unit-tested.
|
||||||
- **Ad banner** gated **off** behind a compile-time `SHOW_AD_BANNER=false` in `Screen.svelte`
|
- **Ad banner** was gated off here behind `SHOW_AD_BANNER=false`; the **AD** phase
|
||||||
— the `{#if}` branch, the `AdBanner` import and `banner.ts` are tree-shaken out of the prod
|
(PRERELEASE.md) later turned it into the real server-driven advertising network and removed
|
||||||
bundle (code kept for post-release polish).
|
the gate (`Screen` renders it from `app.profile.banner`).
|
||||||
- **Landing** Telegram entry is now just the **64px logo** (clickable, no button/caption).
|
- **Landing** Telegram entry is now just the **64px logo** (clickable, no button/caption).
|
||||||
- **TG-fullscreen header** reworked again: title + menu are one **centred pair** (hamburger
|
- **TG-fullscreen header** reworked again: title + menu are one **centred pair** (hamburger
|
||||||
right of the title) pinned to the **bottom** of the TG nav band, lining up with Telegram's
|
right of the title) pinned to the **bottom** of the TG nav band, lining up with Telegram's
|
||||||
@@ -1476,6 +1538,19 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
`proactiveNudgeGap` unit test, the retimed `TestRobotProactiveNudge`, `TestVariantLanguage`,
|
`proactiveNudgeGap` unit test, the retimed `TestRobotProactiveNudge`, `TestVariantLanguage`,
|
||||||
emit (`your_turn`/`game_over` language) and a `TestNudgeRoutedByGameLanguage` integration test.
|
emit (`your_turn`/`game_over` language) and a `TestNudgeRoutedByGameLanguage` integration test.
|
||||||
|
|
||||||
|
### Stage 19 — user feedback
|
||||||
|
- Dropped the planned `feedback_messages.attachment_type` column: the safe content-type is derived from the
|
||||||
|
file-name extension at both validate and serve time (one source of truth), so a stored column was
|
||||||
|
redundant.
|
||||||
|
- The admin filter is **three-way** (Непрочитанные / Прочитанные / Архив) rather than the two first
|
||||||
|
sketched, mirroring complaints' `open·resolved·all`, so a read-but-unarchived message is never
|
||||||
|
unreachable (owner-approved at planning).
|
||||||
|
- The guest gate was extended to the **gateway** at the owner's request: a new `Op.NonGuest` flag plus
|
||||||
|
`is_guest` threaded through the session resolve + gateway cache reject a guest's `feedback.submit` with
|
||||||
|
the `guest_forbidden` result code before any backend call (the backend keeps its own guest check as the
|
||||||
|
backstop). `handleResolveSession` now loads the account best-effort to report `is_guest` (a read error
|
||||||
|
falls back to false so the auth hot path stays resilient).
|
||||||
|
|
||||||
## Deferred TODOs (cross-stage)
|
## Deferred TODOs (cross-stage)
|
||||||
|
|
||||||
- ~~**TODO-1 — publish & version the solver.**~~ **Done in Stage 14.** `scrabble-solver` is
|
- ~~**TODO-1 — publish & version the solver.**~~ **Done in Stage 14.** `scrabble-solver` is
|
||||||
@@ -1515,15 +1590,24 @@ provided cert) at the contour caddy; prod VPN; rollback.
|
|||||||
unchanged). The DAWG/solver build-time agreement (the original caveat, shared with TODO-2) was
|
unchanged). The DAWG/solver build-time agreement (the original caveat, shared with TODO-2) was
|
||||||
discharged in Stage 14: the dict repo builds against the published solver + pinned
|
discharged in Stage 14: the dict repo builds against the published solver + pinned
|
||||||
`dafsa`/`alphabet`, byte-identical to the fixtures.
|
`dafsa`/`alphabet`, byte-identical to the fixtures.
|
||||||
- **TODO-5 — QR friend codes (owner's idea, Stage 8).** *Partially done in Stage 9:*
|
- **TODO-5 — QR friend codes (owner's idea, Stage 8).** *Partially done in Stage 9, extended later:*
|
||||||
the deep-link scheme now exists (`f<code>`, shared Go ↔ TS), the bot redeems it on
|
the deep-link scheme exists (`f<code>`, shared Go ↔ TS), the bot redeems it on launch, and the UI
|
||||||
launch, and the UI shows a **share-to-Telegram** link for an issued code when
|
offers a real **Share** control for an issued code — Telegram's native share-to-chat picker inside
|
||||||
`VITE_TELEGRAM_LINK` is configured. **Still open:** render the link as a **QR** so a
|
the Mini App (`openTelegramLink` + `t.me/share/url`), the system share sheet (`navigator.share`) on
|
||||||
friend can add you by scanning rather than tapping/typing. The code semantics
|
the web, else copy-the-link. The shared link points at the **same bot the player signed in through**:
|
||||||
(12 h TTL, single use, one active per issuer) stay as-is; only the delivery changes.
|
it carries the session's `service_language` (now on the `Session` wire) and picks
|
||||||
|
`VITE_TELEGRAM_LINK_EN`/`_RU`, falling back to `VITE_TELEGRAM_LINK`. **Still open:** render the link
|
||||||
|
as a **QR** so a friend can add you by scanning. The code semantics (12 h TTL, single use, one active
|
||||||
|
per issuer) stay as-is; only the delivery changes.
|
||||||
- **TODO-6 — smart default for the friend-game "game type" (owner's idea, Stage 8).**
|
- **TODO-6 — smart default for the friend-game "game type" (owner's idea, Stage 8).**
|
||||||
The play-with-friends form has no preselected variant today (an empty, required
|
The play-with-friends form has no preselected variant today (an empty, required
|
||||||
pick). Default it from the player's history (the variant they play most, from
|
pick). Default it from the player's history (the variant they play most, from
|
||||||
`account_stats` or a games query), falling back to their interface language
|
`account_stats` or a games query), falling back to their interface language
|
||||||
(en → English, ru → Russian/Эрудит). Until then the explicit pick avoids guessing
|
(en → English, ru → Russian/Эрудит). Until then the explicit pick avoids guessing
|
||||||
wrong.
|
wrong.
|
||||||
|
- **TODO-7 — animate a lobby card's move between sections (owner's idea, 2026-06).**
|
||||||
|
When a game changes bucket — *your turn* → *finished*, *opponent's turn* → *your turn*, etc. —
|
||||||
|
its card simply re-renders in the new section; only the status emoji **blinks twice** (added
|
||||||
|
alongside the named-nudge + lobby-blink work). A FLIP / slide animation that visibly relocates
|
||||||
|
the card to its new section would be a nicer touch. Deferred — purely cosmetic, nothing depends
|
||||||
|
on it.
|
||||||
|
|||||||
+168
-3
@@ -30,6 +30,18 @@ the edge before prod. Each phase maps back to the owner's raw pre-release TODO l
|
|||||||
| MW3 | Graceful replay degradation: a game whose journalled move became illegal under MW2 is closed as a draw (`end_reason='aborted'`) on open instead of erroring, with an impersonal organizer note in the history + GCG (migration `00002`) | owner ad-hoc | **done** |
|
| MW3 | Graceful replay degradation: a game whose journalled move became illegal under MW2 is closed as a draw (`end_reason='aborted'`) on open instead of erroring, with an impersonal organizer note in the history + GCG (migration `00002`) | owner ad-hoc | **done** |
|
||||||
| OW | Open auto-match: enter the game at once and wait inside it (robot after 90–180 s) | owner ad-hoc | **done** |
|
| OW | Open auto-match: enter the game at once and wait inside it (robot after 90–180 s) | owner ad-hoc | **done** |
|
||||||
| DA | Dictionary admin: online release-archive upload → word-diff preview → install/activate; versioned dict volume; active version persisted in DB; resident label = release tag | owner ad-hoc | **done** |
|
| DA | Dictionary admin: online release-archive upload → word-diff preview → install/activate; versioned dict volume; active version persisted in DB; resident label = release tag | owner ad-hoc | **done** |
|
||||||
|
| AB | Manual account block (admin suspension): permanent/temporary with an editable en+ru reason picklist; a block forfeits the player's active games + cancels their open ones; a backend gate refuses a blocked account with **403 `account_blocked`**; the UI shows a terminal blocked screen and stops all push/poll; manual unblock; temporary blocks self-expire (migration `00003`) | owner ad-hoc | **done** |
|
||||||
|
| AI | Honest AI opponent in quick game: an explicit 🤖 AI / 👤 random selector (AI default); the robot is seated and moves at once; 7-day inactivity loss (the per-turn timeout reused); chat/nudge disabled, no statistics; the opponent is shown as 🤖 everywhere | owner ad-hoc | **done** |
|
||||||
|
| AD | Advertising banner ("ad network"): server-driven weighted campaigns (percent weight + validity window; the perpetual default fills the remainder up to 100%), bilingual messages shown by bot (`service_language`); eligibility = free account + empty hint wallet + no `no_banner` role (guests included); the resolved feed rides `profile.get` with a `notify` `banner` re-poll on eligibility change; `/_gm/banners` admin + global display timings; client smooth-weighted-round-robin rotation + fade-out/gap/fade-in UX. A single `app.load` bootstrap aggregator was considered and **deferred** (see ARCHITECTURE §10). | owner ad-hoc | **done** (PR1 backend+admin, PR2 UI rotation) |
|
||||||
|
| GL | Simultaneous quick-game cap (10): grey "New Game" + a lobby notice at the cap; backend gate on quick enqueue + invitation creation (409 `game_limit_reached`), accepting invitations exempt; `at_game_limit` rides `games.list` | owner ad-hoc | **done** |
|
||||||
|
| CR | In-game chat read receipts: per-message `unread_seats` bitmask (migration `00008`); a per-viewer unread **dot** in the lobby + game header (a nudge counts and clears when its recipient moves); reading = opening the move history (the 💬 fade-blinks twice) or the chat, acked (`chat.read`) only when unread; `chat_read_duration` + `chat_unread_messages` metrics + tracing + the **Scrabble — Messages** Grafana dashboard (follow-up PR); a message to a disguised robot opponent is born read; admin unread-only filter / read column / per-seat read card | owner ad-hoc | **done** |
|
||||||
|
| BX | Asymmetric per-user block + in-game controls: a block now silently suppresses everything **from** the blocked user (chat, nudge, friend requests, invitations are kept but never delivered/surfaced, born-read) while they notice nothing, **without** deleting the friendship (unblock restores it); auto-match excludes a block-related pair (either direction); in-game opponent card gains a ✖️ **block** control (mirroring 🤝, red "Block?" confirm, mutual-hide, struck name + hidden chat composer when blocked); optimistic apply + `user_blocked`/`user_unblocked` event confirm + rollback; admin user card gains **blocks / blocked-by / friends** cross-linked lists. Blocking a disguised-robot opponent is recorded per-game in a separate **`robot_blocks`** table (migration `00011`), keyed on game+seat with the seen name — never the shared robot account — so the matchmaker keeps giving robots; it shows in the blocked list and re-marks the in-game card | owner ad-hoc | **done** |
|
||||||
|
| FM | First-move tile draw (official rules): each seated player draws a tile, the one closest to "A" leads (a blank beats every letter), ties re-drawing until a single leader; **honest per-draw `crypto/rand` entropy**, not the bag seed, so the **record** (`game_setup_draws`, migration `00013`) — not a seed — is the only account of the outcome, kept for future **tournaments** (designed as a discrete per-tile "player N draws" step). Friend/AI draws at create; **auto-match draws at *open*** against a synthetic `uuid.Nil` opponent whose draw rows are back-filled on join, so the opener's seat is fixed up front and the existing open-game pre-move is preserved (no reseating, no play-gating). Admin `/_gm/games/:id` gains the recorded draw list + a simple **step-by-step board replay** (`ReplayTimeline`). | owner ad-hoc | **done** |
|
||||||
|
| SB | Single Telegram bot + per-user variant preferences: the two per-language bots collapse into **one** (drop `accounts.service_language`, `supported_languages`, the `*_EN`/`*_RU` env vars and game-language push routing — the single bot renders in the recipient's `preferred_language`); New Game variant gating moves to a profile **`variant_preferences`** set (default Erudit only, Erudit-first, server-enforced on the caller's auto-match/vs-AI/invitation-create paths, an invited friend may accept any variant); env vars collapse to unsuffixed `TELEGRAM_BOT_TOKEN`/`TELEGRAM_GAME_CHANNEL_ID`/`VITE_TELEGRAM_LINK`/`VITE_TELEGRAM_GAME_CHANNEL_NAME` and `GATEWAY_DEFAULT_SUPPORTED_LANGUAGES` is removed; wire drops `service_language`/`supported_languages` (Session, ValidateInitDataResponse) + the push `language` routing field and adds `variant_preferences` to Profile/UpdateProfile. | owner ad-hoc | **done** |
|
||||||
|
| DV | Dictionary version hygiene: CI + image/compose seed track the current release (`v1.2.1`); a **seed-drift guard** records the flat dir's seed in an authoritative `.seed_version` marker so a bumped build seed on a live volume is ignored (it can't relabel live bytes — which would mis-serve the dictionary + void games pinned to the prior label); `DICT_VERSION` is the fresh-volume seed only, a live contour migrates through the admin console | owner ad-hoc | **done** |
|
||||||
|
| TX | Telegram egress off the main host: split the connector into a home **validator** (Mini App / Login-Widget HMAC, no VPN, no Bot API — so game login no longer depends on Telegram being reachable) and a remote **bot** (Bot API long-poll + `sendMessage`) that holds **no inbound port** and dials the gateway over a reverse **mTLS bot-link** (`pkg/proto/botlink/v1`); the gateway funnels out-of-app push (fire-and-forget, at-most-once) and the backend admin broadcasts (a relay that awaits the bot's ack) down the link. The bot is Telegram-rate-limited; **one bot now**, with seams (a bot registry + `owns_updates` + command ids) for N later; **no webhook** (rejected: one URL per token, adds inbound + a static address). The **unified test contour** runs the split (the bot keeps its VPN sidecar and dials the gateway by its internal name; certs from `deploy/gen-certs.sh`). The **prod** wiring — the bot on a separate host (no VPN), the gateway bot-link port published, `PROD_` certs, an SSH deploy of both hosts together — is **built in Stage 18** (the two-host registry rollout; first cutover pending the `erudit-game.ru` DNS). | owner ad-hoc | **done** (code + test contour; prod wiring built — Stage 18) |
|
||||||
|
| AG | Anti-abuse IP ban + honeypot/honeytoken (prod-only): a fail2ban-style in-memory `ratelimit.Banlist` keyed by client IP, fed by sustained rate-limiter rejections (the IP-keyed public/email/admin classes — the user class stays the soft-flag's concern), a **honeypot** decoy path (the contour caddy tags `/.env`, `/.git`, `/wp-*`, … with `X-Scrabble-Honeypot` and routes them to the gateway), and a **honeytoken** (`GATEWAY_HONEYTOKEN`, a planted bearer). The `abuseGuard` edge middleware refuses a banned IP with **429** before any work — closing the R3 gap that the static SPA/landing was outside the token bucket. Off by default — it keys by the real client IP the shared-NAT test contour does not expose (detection still logs there); enabled in prod via `GATEWAY_ABUSE_BAN_ENABLED`. Operators see + lift bans on the console **Throttled** page; the gateway syncs its active set to the backend (`/api/v1/internal/bans/sync`, `internal/banview`) every 30 s and applies operator unbans. | owner ad-hoc | **done** (code + test contour; ban on in prod via Stage 18 — machinery built, cutover pending DNS) |
|
||||||
|
| CM | Channel-chat moderation + promo bot: a second standalone bot in the bot container answers `/start` with a localized message + a **URL** button into the **main** bot's Mini App (`?startapp`; a `web_app` button would sign initData with the promo token, which the main validator rejects). The **main** bot gates write access in a channel's linked discussion chat. The chat **allows sending by default** and the bot only restricts (Telegram intersects the chat default with the per-user permission, so a per-user grant cannot exceed a deny-by-default group): it **mutes** a member who is not registered or is admin-suspended or holding a new **`chat_muted`** role, and **un-mutes** an eligible one it had muted, for a member currently in the chat (a `getChatMember` guard, since bots cannot list members). Eligibility = `registered AND NOT suspended AND NOT chat_muted` (the game suspension dominates), resolved once in the backend and reached two ways: the bot's `ResolveChatEligibility` on a `chat_member` event over the existing mTLS bot-link, and a backend `chat_access_changed` event → gateway → `ChatGate` command (emitted on block/unblock, a `chat_muted` change, a first registration, or a temporary-block expiry via a sweeper; idempotent). No schema change — `chat_muted` reuses `account_roles`. | owner ad-hoc | **done** |
|
||||||
| → | Stage 18 — prod contour deploy | — | see [`PLAN.md`](PLAN.md) |
|
| → | Stage 18 — prod contour deploy | — | see [`PLAN.md`](PLAN.md) |
|
||||||
|
|
||||||
## Key findings (these reshaped the raw list — read before starting a phase)
|
## Key findings (these reshaped the raw list — read before starting a phase)
|
||||||
@@ -73,6 +85,19 @@ the edge before prod. Each phase maps back to the owner's raw pre-release TODO l
|
|||||||
- **Rate-abuse (TODO 8):** metric + Grafana + admin view **plus a conservative auto-flag** —
|
- **Rate-abuse (TODO 8):** metric + Grafana + admin view **plus a conservative auto-flag** —
|
||||||
a *soft, reversible* "suspected high-rate" marker for operator review, tunable threshold,
|
a *soft, reversible* "suspected high-rate" marker for operator review, tunable threshold,
|
||||||
**no auto-ban**.
|
**no auto-ban**.
|
||||||
|
- **Anti-abuse IP ban (AG, owner ad-hoc):** a honeypot was considered and rejected as a *DDoS*
|
||||||
|
defence — it detects/deceives but does not shed volumetric load, cannot cover the real
|
||||||
|
endpoints, and a tarpit backfires under flood; volumetric L3/L4 is an upstream/CDN concern,
|
||||||
|
out of scope. The effective layer is a **temporary IP ban** (fail2ban-style) that the honeypot
|
||||||
|
and honeytoken merely *feed*. This does **not** reverse the TODO-8 "no auto-ban": that decision
|
||||||
|
governs the **account** soft-flag (still never a gate); the IP ban is a separate, IP-keyed,
|
||||||
|
**prod-only** layer with an **operator unban** in the console. Decisions: banlist lives in the
|
||||||
|
existing `ratelimit` package (smallest surface); the decoy path list is a **single source of
|
||||||
|
truth in the caddy** (it tags requests with a header — the gateway keeps no second list);
|
||||||
|
bans are in-memory + single-instance (like `ratewatch`), auto-expiring, **plus** an admin
|
||||||
|
console view + manual unban over a bidirectional 30 s sync (operator control = owner's choice).
|
||||||
|
An active-bans Grafana **gauge** was trimmed (the console view + the `gateway_abuse_banned_total`
|
||||||
|
counter cover it) to keep the diff focused.
|
||||||
- **Open auto-match (owner ad-hoc):** a quick game **enters a real game at once and waits inside
|
- **Open auto-match (owner ad-hoc):** a quick game **enters a real game at once and waits inside
|
||||||
it** (status `open`, the opponent seat empty); a second human searching the same variant+rule
|
it** (status `open`, the opponent seat empty); a second human searching the same variant+rule
|
||||||
joins it, or a robot fills it after a **90 s + random 0–90 s** wait, pushing the in-app
|
joins it, or a robot fills it after a **90 s + random 0–90 s** wait, pushing the in-app
|
||||||
@@ -81,6 +106,20 @@ the edge before prod. Each phase maps back to the owner's raw pre-release TODO l
|
|||||||
now **DB-backed open games** — the in-memory pool, `lobby.poll` and `lobby.cancel` are gone. The
|
now **DB-backed open games** — the in-memory pool, `lobby.poll` and `lobby.cancel` are gone. The
|
||||||
schema is edited in the baseline (no prod data); `game_players.account_id` is nullable for the
|
schema is edited in the baseline (no prod data); `game_players.account_id` is nullable for the
|
||||||
empty seat.
|
empty seat.
|
||||||
|
- **Telegram egress off-host (TX, owner ad-hoc):** the driver is **removing VPN/Telegram
|
||||||
|
traffic from the main host** (OPSEC / one fewer analysis vector), not only notification
|
||||||
|
resilience. Login is local HMAC, so it stays up regardless of the bot — confirmed in the
|
||||||
|
code and made structural by the split. **Unified topology in code** (validator + bot, the
|
||||||
|
bot dialing the gateway) in **both** contours, differing only in deployment; the test bot
|
||||||
|
keeps its VPN sidecar. Transport = a **reverse gRPC bidi stream, mTLS, bot-dials-gateway**
|
||||||
|
(no inbound/static IP on the bot), reusing the push-stream pattern; **webhook rejected**
|
||||||
|
(one URL per token, adds inbound + a static address). Delivery **at-most-once** (a dropped
|
||||||
|
nudge beats a duplicate). **One bot now**, seams (registry + `owns_updates` + command ids)
|
||||||
|
for N later. **Cert rotation** by a scheduled CI job from a long-lived CA. **Prod deploy by
|
||||||
|
SSH** (pull excluded), the bot rolled **together** with the main app (the bot-link protocol
|
||||||
|
kept back-compatible by one version as the non-atomic-two-host-deploy safety net). The bot
|
||||||
|
is monitored **from the gateway** (connection + ack metrics). The bot-host token-at-rest is
|
||||||
|
**accepted**.
|
||||||
|
|
||||||
## Phases
|
## Phases
|
||||||
|
|
||||||
@@ -272,7 +311,7 @@ Then Stage 18.
|
|||||||
hammer (99.97 % rejected, p99 2 ms). **Top finding:** ~14 % `transport_error` on `game.state` at 500
|
hammer (99.97 % rejected, p99 2 ms). **Top finding:** ~14 % `transport_error` on `game.state` at 500
|
||||||
players, under CPU saturation (backend/gateway/Postgres each ~1 core) and amplified by the harness's
|
players, under CPU saturation (backend/gateway/Postgres each ~1 core) and amplified by the harness's
|
||||||
single shared `http2.Transport`; the harness itself peaked at 86 % of a core on the same host, so the
|
single shared `http2.Transport`; the harness itself peaked at 86 % of a core on the same host, so the
|
||||||
figures are pessimistic. Full trip report in [`../loadtest/REPORT-R2.md`](../loadtest/REPORT-R2.md);
|
figures are pessimistic. Full trip report in [`../loadtest/REPORT.md`](../loadtest/REPORT.md);
|
||||||
it feeds R3 (h2c `MaxConcurrentStreams`/timeouts, body-size cap), R6 and R7 (per-player transports,
|
it feeds R3 (h2c `MaxConcurrentStreams`/timeouts, body-size cap), R6 and R7 (per-player transports,
|
||||||
separate hardware, pool/limit sizing).
|
separate hardware, pool/limit sizing).
|
||||||
- **CI:** `./loadtest/...` added to the path filter + vet/build/test; `go.work.sum` carries the new deps.
|
- **CI:** `./loadtest/...` added to the path filter + vet/build/test; `go.work.sum` carries the new deps.
|
||||||
@@ -415,7 +454,12 @@ Then Stage 18.
|
|||||||
one connection per player it bursts into its 2-core cap (the residual 2.49 % `transport_error`); backend
|
one connection per player it bursts into its 2-core cap (the residual 2.49 % `transport_error`); backend
|
||||||
~0.85 core and postgres ~1.4 cores had headroom; **tempo reached its 1 GiB cap**; the backend pool sat at
|
~0.85 core and postgres ~1.4 cores had headroom; **tempo reached its 1 GiB cap**; the backend pool sat at
|
||||||
its `MaxOpenConns=25` cap (28 backends); docker logs were unbounded (~14 MiB / 30 min on the backend at
|
its `MaxOpenConns=25` cap (28 backends); docker logs were unbounded (~14 MiB / 30 min on the backend at
|
||||||
info). Full write-up in [`../loadtest/REPORT-R7.md`](../loadtest/REPORT-R7.md).
|
info). Full write-up in [`../loadtest/REPORT.md`](../loadtest/REPORT.md). *(Superseded in part: a
|
||||||
|
later pass modelling the `game.evaluate` hot path traced the gateway's CPU appetite to
|
||||||
|
**gateway→backend connection churn** — the default 2-idle-connection HTTP transport — not proxying
|
||||||
|
work. Pooling the connections cut peak gateway CPU ~7× (~1.75 → ~0.26 cores at 500 players) and
|
||||||
|
removed the ephemeral-port-exhaustion cliff behind the residual `transport_error`, so the gateway is
|
||||||
|
no longer the binding constraint — postgres is. The 3-core gateway cap below is now generous headroom.)*
|
||||||
- **Round-2 tuning (owner-agreed, all in `deploy/docker-compose.yml`, no code change):** gateway **2 → 3
|
- **Round-2 tuning (owner-agreed, all in `deploy/docker-compose.yml`, no code change):** gateway **2 → 3
|
||||||
cores + `GOMAXPROCS=3`**; tempo memory **1 → 2 GiB**; backend `MAX_OPEN_CONNS` **25 → 40**; a json-file
|
cores + `GOMAXPROCS=3`**; tempo memory **1 → 2 GiB**; backend `MAX_OPEN_CONNS` **25 → 40**; a json-file
|
||||||
**log-rotation** default (10m × 3) applied contour-wide via a YAML anchor (level stays info).
|
**log-rotation** default (10m × 3) applied contour-wide via a YAML anchor (level stays info).
|
||||||
@@ -425,7 +469,7 @@ Then Stage 18.
|
|||||||
**burst** run (a single 100 → 500 jump) pegged the gateway at 3 cores (≈296 % sustained, 9.27 % error),
|
**burst** run (a single 100 → 500 jump) pegged the gateway at 3 cores (≈296 % sustained, 9.27 % error),
|
||||||
confirming it is **connection-CPU-bound** — a true arrival spike is a **horizontal-scaling** lever, not
|
confirming it is **connection-CPU-bound** — a true arrival spike is a **horizontal-scaling** lever, not
|
||||||
more cores per node (recorded in the prod-sizing recommendation).
|
more cores per node (recorded in the prod-sizing recommendation).
|
||||||
- **No schema change → no contour DB wipe.** Bake-back: `loadtest/REPORT-R7.md` (new), `loadtest/README.md`,
|
- **No schema change → no contour DB wipe.** Bake-back: `loadtest/REPORT.md`, `loadtest/README.md`,
|
||||||
`docs/TESTING.md`, the telemetry/observability section of `docs/ARCHITECTURE.md`, the repo-layout line in `CLAUDE.md`.
|
`docs/TESTING.md`, the telemetry/observability section of `docs/ARCHITECTURE.md`, the repo-layout line in `CLAUDE.md`.
|
||||||
|
|
||||||
- **UI — Tab-bar navigation redesign** (owner ad-hoc, not on the raw TODO list): drop the hamburger
|
- **UI — Tab-bar navigation redesign** (owner ad-hoc, not on the raw TODO list): drop the hamburger
|
||||||
@@ -465,3 +509,124 @@ Then Stage 18.
|
|||||||
`lobby.tournaments` / `lobby.soon`). No backend/wire/history/GCG change.
|
`lobby.tournaments` / `lobby.soon`). No backend/wire/history/GCG change.
|
||||||
- **No schema/wire change → no contour DB wipe.** Bake-back: `docs/UI_DESIGN.md`, `docs/FUNCTIONAL.md`
|
- **No schema/wire change → no contour DB wipe.** Bake-back: `docs/UI_DESIGN.md`, `docs/FUNCTIONAL.md`
|
||||||
(+`_ru`). Regression gate: UI `check` + unit + build + bundle budget + e2e (Chromium & WebKit).
|
(+`_ru`). Regression gate: UI `check` + unit + build + bundle budget + e2e (Chromium & WebKit).
|
||||||
|
|
||||||
|
- **AI — Honest AI opponent in quick game** (owner ad-hoc, not on the raw TODO list): a second quick-game
|
||||||
|
opponent the player *knowingly* chooses, distinct from the disguised robot of the random/open path
|
||||||
|
(which is kept as-is). New Game's quick-game mode replaces the "auto-match" subtitle with a two-button
|
||||||
|
selector **🤖 AI / 👤 Random player** (the `.seg`/`.opt` segmented style, AI the default); for AI the
|
||||||
|
move-clock line reads "Loss after 7 days of inactivity" and the "searching" hint is hidden.
|
||||||
|
- **Locked decisions (interview):** AI move is **event-driven** (the robot replies the instant the
|
||||||
|
player's move commits; the 30 s driver is the fallback); AI games **do not touch `account_stats`**
|
||||||
|
(practice, like guests); the **Stage 5 strength logic is reused unchanged** (`playToWin` 40 % from the
|
||||||
|
seed + margin band); **no per-move timeout — a 7-day inactivity loss** instead; the 7-day line lives on
|
||||||
|
the New Game screen (the in-game screen has no move-clock line); chat + nudge **disabled**, word-check
|
||||||
|
kept, add-friend never drawn, opponent shown as **🤖** everywhere.
|
||||||
|
- **The 7-day rule reuses the existing per-turn timeout:** an AI game is created with
|
||||||
|
`turn_timeout_secs = AIInactivityTimeout` (7 days) and the existing timeout sweeper resigns the overdue
|
||||||
|
seat — since the robot moves at once, only the human is ever on the clock, so the per-turn timeout *is*
|
||||||
|
the abandon rule (no new column, no new sweeper).
|
||||||
|
- **One game flag drives everything:** `games.vs_ai` (edited into the R1 baseline — pre-release, so a
|
||||||
|
contour DB wipe after merge). It is set **only** on AI-started games, so a robot-filled random game keeps
|
||||||
|
`vs_ai=false` and the disguised opponent is never revealed; the UI derives 🤖 / the gates **from the flag,
|
||||||
|
never from the opponent account**. New backend path `Matchmaker.StartVsAI` (picks a pooled robot via the
|
||||||
|
existing `Pick`, creates an **active** seated game via `game.Service.Create`, random seat order) — the AI
|
||||||
|
request never enters the open pool, so the open-game reaper never touches it. The robot driver gains a
|
||||||
|
`vs_ai` branch (no sleep, no proactive nudge, zero delay) and a focused `DriveGame`/`TriggerMove` fast
|
||||||
|
path wired from the game service's after-create/after-commit hook (`SetAITrigger`, a func value so the
|
||||||
|
game package never imports the robot package). Chat/nudge gated by a new `social` `VsAI` check
|
||||||
|
(`ErrGameVsAI` → 409 `ai_game`); statistics skipped in `commit` when `vs_ai`.
|
||||||
|
- **Wire:** `EnqueueRequest` += `vs_ai`, `GameView` += `vs_ai` (trailing FB fields, regenerated Go + TS),
|
||||||
|
threaded through the backend DTO, the gateway transcode and the `pkg/wire` + `notify` builders.
|
||||||
|
- **Tests:** `lobby` unit (StartVsAI seats a robot + flags the game; empty pool leaves no game); backend
|
||||||
|
integration (`ai_game_test.go`: active+seated+vs_ai+7-day clock, robot moves immediately, stats skipped,
|
||||||
|
7-day timeout resigns the human, chat/nudge rejected); UI codec round-trip (`vs_ai` on enqueue + game
|
||||||
|
view); e2e (an AI game shows 🤖, no "searching", chat disabled, the dictionary still works) + the
|
||||||
|
existing quick-match e2e updated to pick **Random player** (the default is now AI).
|
||||||
|
- **Schema/wire change → a contour DB wipe** after merge (`DROP SCHEMA backend CASCADE` + restart, the
|
||||||
|
R1/R3 pattern). Bake-back: `docs/ARCHITECTURE.md`, `docs/FUNCTIONAL.md` (+`_ru`), `docs/UI_DESIGN.md`,
|
||||||
|
`backend/README.md`, Go Doc comments.
|
||||||
|
- **Post-review refinements (owner, same PR):** (1) the **GCG export labels the robot seat "AI"** rather
|
||||||
|
than its human-like pool name (`ExportGCG` overrides the name via `accounts.IsRobot`; the in-app 🤖 is
|
||||||
|
unchanged); (2) honest-AI games **emit no `your_turn`** — the robot replies instantly, so the signal
|
||||||
|
would arrive with the move and be pointless; `opponent_moved` still advances the UI; (3) the **admin
|
||||||
|
console surfaces the AI flag** — a **🤖 column** in `/games` and an "AI game" line on the game card
|
||||||
|
(`GameRow`/`GameDetailView` gain `VsAI`); (4) `games_started_total` / `games_abandoned_total` gain a
|
||||||
|
**`vs_ai`** attribute and the Grafana *Game domain* dashboard splits started/abandoned into **human**
|
||||||
|
and **AI** panels.
|
||||||
|
- **Follow-up (separate PR — strategy deviation):** the robot now plays **≈20%** of opening/midgame moves
|
||||||
|
*against* its per-game `playToWin` intent (toward the opposite margin band — a winning robot eases off, a
|
||||||
|
losing one surges ahead), tapering linearly to **0 over the last 14 bag tiles** and **0 once the bag is
|
||||||
|
empty**, so the endgame follows the chosen strategy strictly while earlier outcomes can swing the human's
|
||||||
|
way. Deterministic from the seed (`mix(seed,"deviate",moveCount)`), applied to **both** robot paths via
|
||||||
|
the shared `selectMove`; the per-game intent (and the admin card) is unchanged. Tests: `robot` unit
|
||||||
|
(taper bounds + monotonicity, never-in-endgame, determinism, ~20% distribution). Bake-back:
|
||||||
|
`docs/ARCHITECTURE.md` §7, `docs/FUNCTIONAL.md` (+`_ru`), `backend/README.md`, `PLAN.md` Stage 5.
|
||||||
|
|
||||||
|
- **GL — Simultaneous quick-game cap** (owner ad-hoc, not on the raw TODO list): a player may hold at
|
||||||
|
most **10** active quick games; at the cap the lobby greys **New Game** and shows a plain notice
|
||||||
|
"Вы достигли лимита одновременных партий", both clearing automatically when an active game finishes.
|
||||||
|
- **Locked decisions (interview):** what counts = active **+** open (searching) quick games, **including
|
||||||
|
AI** (`vs_ai`); friend games (invitation-linked) **never** count. The backend gate refuses **all** new-game
|
||||||
|
creation at the cap — `lobby/enqueue` **and** `invitations` — with **409 `game_limit_reached`**; **accepting**
|
||||||
|
an invitation is never gated, so friend games are capped "from the other end". Delivery = a boolean
|
||||||
|
**`at_game_limit`** on the existing `games.list` (no per-event payload: a turn change does not move the count,
|
||||||
|
and the lobby already re-fetches `games.list` on entry + every game event); the first uncached lobby frame
|
||||||
|
defaults the button **enabled** (the backend gate is the authority).
|
||||||
|
- **What shipped:** `game.MaxActiveQuickGames` + `Store/Service.CountActiveQuickGames` (active/open seats, no
|
||||||
|
`game_invitations` row; hidden games still count → a dedicated count, not a filter over the lobby list);
|
||||||
|
`Server.atGameLimit`/`ensureUnderGameLimit` gating `handleEnqueue` + `handleCreateInvitation`;
|
||||||
|
`gameListDTO.at_game_limit`; the FB `GameList` trailing `at_game_limit` (regenerated Go + TS) threaded through
|
||||||
|
the gateway transcode + UI codec; `lib/model` + `lobbycache` snapshot + `Lobby.svelte` (disabled tab + a muted
|
||||||
|
`.limit` notice); i18n `lobby.limitReached` (en authoritative + ru).
|
||||||
|
- **Caveat (logged):** the gate is a pre-check, not transaction-atomic — concurrent creates from one account could
|
||||||
|
momentarily exceed by 1–2 (harmless soft cap; the UI disables the button regardless). Strict atomicity was judged
|
||||||
|
a disproportionate diff across the two create paths.
|
||||||
|
- **No schema change → no contour DB wipe** (only a trailing FB field, no migration). Tests: backend integration
|
||||||
|
(`game_limit_test.go`: count rule + HTTP gate 409 + accept bypass), server unit (error mapping), gateway
|
||||||
|
transcode round-trip, UI codec + lobbycache unit, e2e (`gamelimit.spec.ts`). Bake-back: `docs/FUNCTIONAL.md`
|
||||||
|
(+`_ru`), `docs/ARCHITECTURE.md` §8, `docs/UI_DESIGN.md`, `backend/README.md`.
|
||||||
|
|
||||||
|
- **CM — Channel-chat moderation + promo bot** (owner ad-hoc, not on the raw TODO list):
|
||||||
|
- **Locked decisions (interview):** the promo bot is a **goroutine in `cmd/bot`** (its own token, no
|
||||||
|
bot-link); the moderated chat's default-no-send is configured by a **human** in the group settings (the
|
||||||
|
bot only grants, never `setChatPermissions`); a non-eligible joiner is **left muted silently**; a
|
||||||
|
temporary-suspension expiry is handled by a **backend sweeper** that emits the re-evaluate event; and a new
|
||||||
|
**`chat_muted` role** is a chat-only mute with the **game suspension dominating**
|
||||||
|
(`eligible = registered AND NOT suspended AND NOT chat_muted`).
|
||||||
|
- **Bot API reality (verified against the docs):** a cross-bot Mini App launch must be a **URL button** to the
|
||||||
|
main bot's `t.me/<bot>?startapp` link — a `web_app` button signs initData with the *sending* bot's token,
|
||||||
|
which the main validator rejects — so the promo button reuses the UI's `VITE_TELEGRAM_LINK`. `chat_member`
|
||||||
|
updates arrive **only** when the bot is a chat **admin** with the "Ban users" right (the client label for the
|
||||||
|
Bot API `can_restrict_members`) and `chat_member` is in `allowed_updates`; bots cannot list members but can
|
||||||
|
`getChatMember` a single user, which is the membership guard on the block/unblock path.
|
||||||
|
- **Wire:** `pkg/proto/botlink/v1` gains a `ChatGateCommand` in the `Command` oneof and a unary
|
||||||
|
`ResolveChatEligibility`; the backend gains `notify.KindChatAccessChanged` (no payload, infra-only — never an
|
||||||
|
out-of-app message) and an internal `POST /api/v1/internal/chat-access` resolver; the gateway resolves the
|
||||||
|
join (by external_id) and the event (by user_id) through it and pushes the chat-gate command fire-and-forget
|
||||||
|
(at-most-once, recovered by the next moderation action or a re-join).
|
||||||
|
- **No schema change → no contour DB wipe:** `chat_muted` is a new `account.KnownRoles` entry (the
|
||||||
|
`account_roles` table is data-driven). The suspension-expiry sweeper is a new `account.SuspensionSweeper`
|
||||||
|
(a 1-minute window, idempotent) started in `cmd/backend`, alongside the guest reaper.
|
||||||
|
- **Deploy:** new `TEST_`/`PROD_` `TELEGRAM_PROMO_BOT_TOKEN` (secret), `TELEGRAM_BOT_USERNAME` and
|
||||||
|
`TELEGRAM_CHAT_ID` (variables); the promo link reuses the existing `*_VITE_TELEGRAM_LINK` variable as
|
||||||
|
`TELEGRAM_BOT_LINK`. The bot must be promoted to admin in the real discussion group, and the group default
|
||||||
|
set to no-send, as part of the Stage 18 prod cutover (the test contour exercises the code path).
|
||||||
|
- **Bake-back:** `docs/ARCHITECTURE.md`, `docs/FUNCTIONAL.md` (+`_ru`), `platform/telegram/README.md`,
|
||||||
|
`backend/README.md`, Go Doc comments. Tests: backend resolver truth table + publish on block/unblock/role +
|
||||||
|
the sweeper window (unit + integration); gateway hub `ResolveChatEligibility` + the chat-gate command; bot
|
||||||
|
`chat_member` grant + `ApplyChatGate` getChatMember-guard; promo `/start` localization + URL button; config
|
||||||
|
parsing.
|
||||||
|
- **Post-contour-test fixes (same PR):** a live test drove three corrections. (1) **Strategy
|
||||||
|
inversion (the key one)** — the original "group default no-send, bot grants the eligible" cannot
|
||||||
|
work: Telegram intersects the chat default with each user's permission, so a per-user grant never
|
||||||
|
exceeds a deny-by-default group (the bot set `can_send=true` yet the user still could not write).
|
||||||
|
The group now **allows sending by default** and the bot only **restricts** — it mutes an ineligible
|
||||||
|
member (unregistered / admin-suspended / `chat_muted`) and un-mutes an eligible one it had muted,
|
||||||
|
acting only when the current state differs (idempotent; the bot's own change is skipped by matching
|
||||||
|
the actor id to the bot). A present member in a default-allow group can appear as `restricted` with
|
||||||
|
`is_member`, so the gate reads both. (2) **Join-before-register** — a user who joins before
|
||||||
|
registering is covered by no `chat_member` event, so `ProvisionTelegram` now reports first contact
|
||||||
|
and the Telegram auth handler emits `chat_access_changed` on it. (3) **Observability** — a startup
|
||||||
|
self-check logs whether the bot is an admin-with-restrict in the chat (it caught a misconfigured
|
||||||
|
`TELEGRAM_CHAT_ID` set to a channel id, not the discussion-group id); the per-event trace is at
|
||||||
|
Debug, the actual mute/unmute and warnings at Info.
|
||||||
|
|||||||
+5
-3
@@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
# --- dictionary artifact -----------------------------------------------------
|
# --- dictionary artifact -----------------------------------------------------
|
||||||
FROM alpine:3.20 AS dawg
|
FROM alpine:3.20 AS dawg
|
||||||
ARG DICT_VERSION=v1.0.0
|
ARG DICT_VERSION=v1.2.1
|
||||||
RUN apk add --no-cache curl tar
|
RUN apk add --no-cache curl tar
|
||||||
RUN mkdir -p /dawg \
|
RUN mkdir -p /dawg \
|
||||||
&& curl -fsSL -o /tmp/dawg.tar.gz \
|
&& curl -fsSL -o /tmp/dawg.tar.gz \
|
||||||
@@ -33,14 +33,16 @@ COPY backend ./backend
|
|||||||
# Reduce the workspace to what the backend needs: backend + pkg. loadtest and the
|
# Reduce the workspace to what the backend needs: backend + pkg. loadtest and the
|
||||||
# gateway replace it requires are not in this context, so drop both.
|
# gateway replace it requires are not in this context, so drop both.
|
||||||
RUN go work edit -dropuse=./gateway -dropuse=./platform/telegram -dropuse=./loadtest -dropreplace=scrabble/gateway@v0.0.0
|
RUN go work edit -dropuse=./gateway -dropuse=./platform/telegram -dropuse=./loadtest -dropreplace=scrabble/gateway@v0.0.0
|
||||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/backend ./backend/cmd/backend
|
# VERSION (the deploy passes the git tag) is stamped into the binary via the linker.
|
||||||
|
ARG VERSION=dev
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "-X scrabble/pkg/version.Version=${VERSION}" -o /out/backend ./backend/cmd/backend
|
||||||
|
|
||||||
# --- runtime -----------------------------------------------------------------
|
# --- runtime -----------------------------------------------------------------
|
||||||
FROM gcr.io/distroless/static-debian12:nonroot
|
FROM gcr.io/distroless/static-debian12:nonroot
|
||||||
# Re-declare the build arg in this stage so it labels the seed dictionary. One
|
# Re-declare the build arg in this stage so it labels the seed dictionary. One
|
||||||
# DICT_VERSION drives both the artifact the dawg stage downloads and the version
|
# DICT_VERSION drives both the artifact the dawg stage downloads and the version
|
||||||
# label the binary pins, so the resident version equals the release tag.
|
# label the binary pins, so the resident version equals the release tag.
|
||||||
ARG DICT_VERSION=v1.0.0
|
ARG DICT_VERSION=v1.2.1
|
||||||
COPY --from=build /out/backend /usr/local/bin/backend
|
COPY --from=build /out/backend /usr/local/bin/backend
|
||||||
# Own the seed dictionary as the nonroot runtime user (UID 65532): a named volume
|
# Own the seed dictionary as the nonroot runtime user (UID 65532): a named volume
|
||||||
# mounted at /opt/dawg inherits this ownership on first use, so the admin console
|
# mounted at /opt/dawg inherits this ownership on first use, so the admin console
|
||||||
|
|||||||
+77
-17
@@ -33,10 +33,22 @@ real game seating the caller with an **empty opponent seat** (status `open`) or,
|
|||||||
another player already waits for the same variant and per-turn word rule, seats the
|
another player already waits for the same variant and per-turn word rule, seats the
|
||||||
caller into that open game and starts it — and
|
caller into that open game and starts it — and
|
||||||
friend-game invitations (invite → accept, starting a 2–4 player game once every
|
friend-game invitations (invite → accept, starting a 2–4 player game once every
|
||||||
invitee accepts). `internal/social` owns the friend graph (request/accept),
|
invitee accepts). A **simultaneous-game cap** (`game.MaxActiveQuickGames` = 10) limits a
|
||||||
|
player's active quick games — status `active`/`open`, excluding invitation-linked friend
|
||||||
|
games (`game.Service.CountActiveQuickGames`); the server refuses `lobby/enqueue` and
|
||||||
|
`invitations` creation with **409 `game_limit_reached`** at the cap (accepting an invitation
|
||||||
|
is exempt), and the `games.list` response carries an `at_game_limit` flag for the lobby.
|
||||||
|
`internal/social` owns the friend graph (request/accept),
|
||||||
per-user blocks, and per-game chat with nudges folded in as a message kind; chat
|
per-user blocks, and per-game chat with nudges folded in as a message kind; chat
|
||||||
messages are length-capped, content-filtered (no links/emails/phone numbers,
|
messages are length-capped, content-filtered (no links/emails/phone numbers,
|
||||||
including obfuscated forms) and stored with the sender's IP. `internal/account`
|
including obfuscated forms) and stored with the sender's IP. Each message carries an
|
||||||
|
`unread_seats` read bitmask (a set bit per recipient seat still to read it); `MarkRead`
|
||||||
|
clears a reader's bit when they open the move history or chat, and a wired `NudgeClearer`
|
||||||
|
clears a nudge when its recipient moves — both record the publish-to-read latency.
|
||||||
|
A friend request (or block) aimed at a **disguised pooled robot** is recorded per game+seat
|
||||||
|
in `robot_friend_requests` / `robot_blocks`, never against the shared robot account; a
|
||||||
|
background reaper drops a robot friend request once its game has been finished for **7 days**.
|
||||||
|
`internal/account`
|
||||||
gains profile editing and the email confirm-code flow (a `Mailer` seam: SMTP or a
|
gains profile editing and the email confirm-code flow (a `Mailer` seam: SMTP or a
|
||||||
development log mailer). The engine now also handles **multi-player drop-out**: in
|
development log mailer). The engine now also handles **multi-player drop-out**: in
|
||||||
a 3–4 player game a resignation or timeout drops that seat and the rest play on
|
a 3–4 player game a resignation or timeout drops that seat and the rest play on
|
||||||
@@ -47,18 +59,37 @@ services are exposed via `Server` accessors for those handlers.
|
|||||||
|
|
||||||
The robot opponent (`internal/robot`). A pool of durable accounts —
|
The robot opponent (`internal/robot`). A pool of durable accounts —
|
||||||
each a `kind='robot'` identity, provisioned at startup with chat and friend
|
each a `kind='robot'` identity, provisioned at startup with chat and friend
|
||||||
requests blocked — backs human-like, per-language composed names. A background driver plays the
|
requests blocked — carries human-like names. The disguised reaper stamps a **fresh per-game name** on
|
||||||
|
the robot's seat (a `game_players.display_name` snapshot — which also freezes humans' names per game, so
|
||||||
|
a later rename never rewrites past games) drawn from a wide composed corpus (Western locales, native
|
||||||
|
Japanese/Chinese, a gender-agreed Russian pool, and handles); a Russian game stays Cyrillic with ≤20%
|
||||||
|
Latin and no CJK script, an English game uses the full corpus (`namevariety.go`, `PickNamed`). A
|
||||||
|
background driver plays the
|
||||||
robot's moves through the public game API as an ordinary seated player (so only
|
robot's moves through the public game API as an ordinary seated player (so only
|
||||||
`internal/engine` imports the solver): it decides once per game whether to play to
|
`internal/engine` imports the solver): it decides once per game whether to play to
|
||||||
win (≈ 40%), targets a small score margin, and times its moves with a move-number-aware
|
win (≈ 40%), targets a small score margin — with an occasional off-strategy move that tapers to
|
||||||
|
none as the bag empties — and times its moves with a move-number-aware
|
||||||
right-skewed delay (quick openings, long endgames), a night-sleep window anchored to the opponent's timezone, and nudge
|
right-skewed delay (quick openings, long endgames), a night-sleep window anchored to the opponent's timezone, and nudge
|
||||||
behaviour — all derived deterministically from the game seed, so it keeps no extra
|
behaviour — all derived deterministically from the game seed, so it keeps no extra
|
||||||
state. A background **reaper** seats a pooled robot (matching the game's language) in any open
|
state. In a dead-drawn endgame — the last two journal moves are both passes, so the robot is bound
|
||||||
|
to pass again — it shortens that delay to a `[0.8, 1.5]×` band around the human's last-move think
|
||||||
|
time (the gap between the last two moves), clamped to `[30 s, 8 min]` and `min`-ed with the normal
|
||||||
|
delay, so a decided game is not dragged out while the robot never moves slower than usual. A background **reaper** seats a pooled robot (matching the game's language) in any open
|
||||||
game whose wait window — a fixed **90 s** plus a random **0–90 s** (so **90–180 s**) — has
|
game whose wait window — a fixed **90 s** plus a random **0–90 s** (so **90–180 s**) — has
|
||||||
elapsed, and the waiting starter is told an opponent took the seat by an in-app
|
elapsed, and the waiting starter is told an opponent took the seat by an in-app
|
||||||
**opponent_joined** push (carrying their refreshed game state) that fills the opponent card and
|
**opponent_joined** push (carrying their refreshed game state) that fills the opponent card and
|
||||||
re-enables resign and chat in place.
|
re-enables resign and chat in place.
|
||||||
|
|
||||||
|
The same robot also backs an **honest-AI quick game** (`games.vs_ai`), the alternative to the random
|
||||||
|
path that the player chooses on New Game. `Matchmaker.StartVsAI` picks a pooled robot and creates a
|
||||||
|
game **already seated and active** (random seat order) — it never enters the open pool. The robot
|
||||||
|
driver has a `vs_ai` branch (no sleep, no proactive nudge, zero delay) plus a focused
|
||||||
|
`DriveGame`/`TriggerMove` fast path wired from the game service's after-create/after-commit hook
|
||||||
|
(`SetAITrigger`), so the robot replies the instant the player moves. AI games keep the same strength
|
||||||
|
(`playToWin`), have **no per-move timeout** (`turn_timeout_secs = AIInactivityTimeout`, 7 days, so an
|
||||||
|
abandoned game is lost after a week of inactivity — only the human is ever on the clock), record **no
|
||||||
|
statistics** (skipped in `commit`), and disable chat/nudge (`social` `VsAI` → `ErrGameVsAI`).
|
||||||
|
|
||||||
The backend opens to the edge. The route groups gain their first
|
The backend opens to the edge. The route groups gain their first
|
||||||
handlers (`internal/server/handlers_*.go`): gateway-only session endpoints under
|
handlers (`internal/server/handlers_*.go`): gateway-only session endpoints under
|
||||||
`/api/v1/internal` (Telegram/guest/email login → mint, resolve, revoke) and a
|
`/api/v1/internal` (Telegram/guest/email login → mint, resolve, revoke) and a
|
||||||
@@ -72,9 +103,16 @@ second listener — `internal/pushgrpc`, a gRPC server (`BACKEND_GRPC_ADDR`) str
|
|||||||
live events (your-turn, opponent-moved, chat, nudge, match-found, notify) to the
|
live events (your-turn, opponent-moved, chat, nudge, match-found, notify) to the
|
||||||
gateway. The gateway-only `POST /api/v1/internal/push-target` (a user's
|
gateway. The gateway-only `POST /api/v1/internal/push-target` (a user's
|
||||||
Telegram `external_id`, language and `notifications_in_app_only` flag) lets the gateway
|
Telegram `external_id`, language and `notifications_in_app_only` flag) lets the gateway
|
||||||
route out-of-app push to the Telegram connector; the Telegram login
|
route out-of-app push to the Telegram bot over the gateway bot-link; the Telegram login
|
||||||
seeds a new account's language and display name from the launch fields, and the
|
seeds a new account's language and display name from the launch fields, and the
|
||||||
`accounts.notifications_in_app_only` flag (default true).
|
`accounts.notifications_in_app_only` flag (default true).
|
||||||
|
The gateway-only `POST /api/v1/internal/chat-access` resolves a Telegram identity (the
|
||||||
|
bot's join-time query) or an account id (a `chat_access_changed` event) to its
|
||||||
|
**moderated-chat write eligibility** — `registered AND NOT suspended AND NOT chat_muted`.
|
||||||
|
That event is emitted on an admin block/unblock, a `chat_muted` role grant/revoke, or — via
|
||||||
|
the `account.SuspensionSweeper` started in `cmd/backend` — a temporary block lapsing;
|
||||||
|
`chat_muted` is an `account.KnownRoles` entry, a chat-only mute distinct from the game
|
||||||
|
suspension (which dominates it).
|
||||||
`accounts.is_guest` marks an ephemeral guest — a durable row
|
`accounts.is_guest` marks an ephemeral guest — a durable row
|
||||||
with no identity, excluded from statistics. The server-rendered
|
with no identity, excluded from statistics. The server-rendered
|
||||||
**admin console** at `/_gm` (`internal/adminconsole` + `internal/server/handlers_admin_console.go`;
|
**admin console** at `/_gm` (`internal/adminconsole` + `internal/server/handlers_admin_console.go`;
|
||||||
@@ -85,12 +123,17 @@ pipeline, the online **dictionary update** (upload the `scrabble-dawg-vX.Y.Z.tar
|
|||||||
archive, preview the per-variant word diff, then install + activate — `internal/dictadmin` +
|
archive, preview the per-variant word diff, then install + activate — `internal/dictadmin` +
|
||||||
`engine.DiffWords` / `Registry.LoadAvailable`, written to per-version subdirectories of the
|
`engine.DiffWords` / `Registry.LoadAvailable`, written to per-version subdirectories of the
|
||||||
`BACKEND_DICT_DIR` volume with the active version persisted in `dictionary_state`), and operator **broadcasts** via a
|
`BACKEND_DICT_DIR` volume with the active version persisted in `dictionary_state`), and operator **broadcasts** via a
|
||||||
backend Telegram-connector client (`internal/connector`, `BACKEND_CONNECTOR_ADDR`) — each
|
backend client (`internal/connector`, `BACKEND_CONNECTOR_ADDR`) that calls the gateway's
|
||||||
broadcast picks the delivering bot by an operator-chosen language. `accounts.service_language`
|
**bot-link relay** — each broadcast renders through the bot in an operator-chosen language
|
||||||
holds the language tag of the bot a Telegram
|
and the relay awaits the bot's delivery ack. There is one bot,
|
||||||
user last signed in through, written on every login and returned by
|
so `/internal/push-target` returns the recipient's `preferred_language` as the render
|
||||||
`/internal/push-target` (falling back to `preferred_language`) so out-of-app push routes
|
language for out-of-app push; no per-bot routing remains. The console also manages the **advertising banner** (`/_gm/banners` +
|
||||||
to the right bot. The shared wire contracts live in the sibling [`../pkg`](../pkg) module.
|
`/_gm/banner-settings`, `internal/ads`): operator campaigns with a percent weight, an optional
|
||||||
|
window and bilingual messages, plus the global display timings. `GET /api/v1/user/profile` attaches
|
||||||
|
the resolved, weighted campaign feed for an **eligible** viewer (`!paid_account && hint_balance == 0
|
||||||
|
&& !no_banner` role, the message language picked by `preferred_language`); changing those inputs
|
||||||
|
publishes a `notify` `banner` re-poll signal so the client shows/hides it in place. The shared wire
|
||||||
|
contracts live in the sibling [`../pkg`](../pkg) module.
|
||||||
|
|
||||||
**Account linking & merge** (`/api/v1/user/link/*`). `internal/link`
|
**Account linking & merge** (`/api/v1/user/link/*`). `internal/link`
|
||||||
orchestrates it: an email confirm-code or a gateway-validated Telegram identity is
|
orchestrates it: an email confirm-code or a gateway-validated Telegram identity is
|
||||||
@@ -112,6 +155,13 @@ rejected calls within `BACKEND_HIGHRATE_FLAG_WINDOW` gets the soft, reversible
|
|||||||
`accounts.flagged_high_rate_at` marker (set-once; a badge in the user list and a
|
`accounts.flagged_high_rate_at` marker (set-once; a badge in the user list and a
|
||||||
**Clear** action on the user card; never an automatic ban).
|
**Clear** action on the user card; never an automatic ban).
|
||||||
|
|
||||||
|
The gateway also syncs its active IP bans (prod-only — see ARCHITECTURE §11) to
|
||||||
|
`POST /api/v1/internal/bans/sync`; `internal/banview` mirrors them for the console's
|
||||||
|
**Throttled** page (an **Active IP bans** panel with an **Unban** action) and returns
|
||||||
|
the operator's pending unbans in the response, which the gateway applies on its next
|
||||||
|
sync. Like `ratewatch` it is in-memory and resets on restart — the enforced ban lives
|
||||||
|
in the gateway, not here.
|
||||||
|
|
||||||
## Package layout
|
## Package layout
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -130,11 +180,14 @@ internal/server/ # gin engine, route groups, X-User-ID middleware, probes
|
|||||||
internal/engine/ # in-process scrabble-solver bridge: registry, bag, Game, replay
|
internal/engine/ # in-process scrabble-solver bridge: registry, bag, Game, replay
|
||||||
internal/game/ # game domain: lifecycle, journal+cache, hint, word-check, GCG, sweeper
|
internal/game/ # game domain: lifecycle, journal+cache, hint, word-check, GCG, sweeper
|
||||||
internal/social/ # friend graph, per-user blocks, per-game chat + nudge, content filter
|
internal/social/ # friend graph, per-user blocks, per-game chat + nudge, content filter
|
||||||
|
internal/feedback/ # user feedback: messages + attachment (bytea), anti-spam gate, admin review/reply
|
||||||
internal/lobby/ # auto-match (DB-backed open games + robot substitution) + friend-game invitations
|
internal/lobby/ # auto-match (DB-backed open games + robot substitution) + friend-game invitations
|
||||||
internal/robot/ # human-like robot opponent: account pool, seed-derived strategy, move driver
|
internal/robot/ # human-like robot opponent: account pool, seed-derived strategy, move driver
|
||||||
internal/adminconsole/ # server-rendered admin console (Go templates + embedded CSS, view models), served at /_gm
|
internal/adminconsole/ # server-rendered admin console (Go templates + embedded CSS, view models), served at /_gm
|
||||||
internal/connector/ # backend gRPC client to the Telegram connector (operator broadcasts)
|
internal/ads/ # advertising banner: campaigns + bilingual messages + display timings, weighted-rotation feed (ActiveSet)
|
||||||
|
internal/connector/ # backend gRPC client to the gateway bot-link relay (operator broadcasts)
|
||||||
internal/ratewatch/ # gateway rate-limit reports: episode window for the console + the high-rate auto-flag
|
internal/ratewatch/ # gateway rate-limit reports: episode window for the console + the high-rate auto-flag
|
||||||
|
internal/banview/ # gateway active-ban mirror: the console's Active IP bans panel + the operator unban backchannel
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration (environment)
|
## Configuration (environment)
|
||||||
@@ -153,7 +206,7 @@ internal/ratewatch/ # gateway rate-limit reports: episode window for the consol
|
|||||||
| `BACKEND_OTEL_TRACES_EXPORTER` | `none` | `none`, `stdout` or `otlp` (gRPC; endpoint from the standard `OTEL_EXPORTER_OTLP_*`). |
|
| `BACKEND_OTEL_TRACES_EXPORTER` | `none` | `none`, `stdout` or `otlp` (gRPC; endpoint from the standard `OTEL_EXPORTER_OTLP_*`). |
|
||||||
| `BACKEND_OTEL_METRICS_EXPORTER` | `none` | `none`, `stdout` or `otlp`. |
|
| `BACKEND_OTEL_METRICS_EXPORTER` | `none` | `none`, `stdout` or `otlp`. |
|
||||||
| `BACKEND_DICT_DIR` | — | **Required.** Directory of committed `.dawg` dictionaries. |
|
| `BACKEND_DICT_DIR` | — | **Required.** Directory of committed `.dawg` dictionaries. |
|
||||||
| `BACKEND_DICT_VERSION` | `v1` | Dictionary version new games pin. |
|
| `BACKEND_DICT_VERSION` | `v1` | Version label for the flat dictionary dir. Recorded in a `.seed_version` marker on first boot and authoritative after: on a seeded volume a changed value is ignored (it seeds only a fresh volume) — the seed-drift guard (ARCHITECTURE.md §5). |
|
||||||
| `BACKEND_GAME_TIMEOUT_SWEEP_INTERVAL` | `1m` | How often the turn-timeout sweeper runs. |
|
| `BACKEND_GAME_TIMEOUT_SWEEP_INTERVAL` | `1m` | How often the turn-timeout sweeper runs. |
|
||||||
| `BACKEND_GAME_CACHE_TTL` | `24h` | Idle window before a live game is evicted from cache. |
|
| `BACKEND_GAME_CACHE_TTL` | `24h` | Idle window before a live game is evicted from cache. |
|
||||||
| `BACKEND_LOBBY_ROBOT_WAIT` | `10s` | Auto-match wait before a robot is substituted for a missing human. |
|
| `BACKEND_LOBBY_ROBOT_WAIT` | `10s` | Auto-match wait before a robot is substituted for a missing human. |
|
||||||
@@ -164,7 +217,7 @@ internal/ratewatch/ # gateway rate-limit reports: episode window for the consol
|
|||||||
| `BACKEND_SMTP_USERNAME` | — | SMTP user; empty relays without authentication. |
|
| `BACKEND_SMTP_USERNAME` | — | SMTP user; empty relays without authentication. |
|
||||||
| `BACKEND_SMTP_PASSWORD` | — | SMTP password. |
|
| `BACKEND_SMTP_PASSWORD` | — | SMTP password. |
|
||||||
| `BACKEND_SMTP_FROM` | `no-reply@localhost` | Envelope/From address for confirm-codes. |
|
| `BACKEND_SMTP_FROM` | `no-reply@localhost` | Envelope/From address for confirm-codes. |
|
||||||
| `BACKEND_CONNECTOR_ADDR` | — | Telegram connector gRPC address for admin-console operator broadcasts. Empty disables broadcasts. |
|
| `BACKEND_CONNECTOR_ADDR` | — | the gateway bot-link relay gRPC address for admin-console operator broadcasts. Empty disables broadcasts. |
|
||||||
| `BACKEND_GUEST_REAP_INTERVAL` | `1h` | How often the abandoned-guest reaper sweeps. |
|
| `BACKEND_GUEST_REAP_INTERVAL` | `1h` | How often the abandoned-guest reaper sweeps. |
|
||||||
| `BACKEND_GUEST_RETENTION` | `720h` | Account age past which a guest with no game seat is deleted. |
|
| `BACKEND_GUEST_RETENTION` | `720h` | Account age past which a guest with no game seat is deleted. |
|
||||||
| `BACKEND_HIGHRATE_FLAG_THRESHOLD` | `1000` | Gateway-reported rejected calls within the window past which an account is soft-flagged. |
|
| `BACKEND_HIGHRATE_FLAG_THRESHOLD` | `1000` | Gateway-reported rejected calls within the window past which an account is soft-flagged. |
|
||||||
@@ -175,7 +228,7 @@ internal/ratewatch/ # gateway rate-limit reports: episode window for the consol
|
|||||||
```sh
|
```sh
|
||||||
docker run -d --name scrabble-pg -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:17-alpine
|
docker run -d --name scrabble-pg -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:17-alpine
|
||||||
# DAWGs: extract the dictionary release artifact (or point at a local scrabble-solver/dawg):
|
# DAWGs: extract the dictionary release artifact (or point at a local scrabble-solver/dawg):
|
||||||
mkdir -p /tmp/dawg && curl -fsSL https://gitea.iliadenisov.ru/developer/scrabble-dictionary/releases/download/v1.0.0/scrabble-dawg-v1.0.0.tar.gz | tar xz -C /tmp/dawg
|
mkdir -p /tmp/dawg && curl -fsSL https://gitea.iliadenisov.ru/developer/scrabble-dictionary/releases/download/v1.2.1/scrabble-dawg-v1.2.1.tar.gz | tar xz -C /tmp/dawg
|
||||||
BACKEND_POSTGRES_DSN='postgres://postgres:dev@localhost:5432/postgres?search_path=backend&sslmode=disable' \
|
BACKEND_POSTGRES_DSN='postgres://postgres:dev@localhost:5432/postgres?search_path=backend&sslmode=disable' \
|
||||||
BACKEND_DICT_DIR=/tmp/dawg \
|
BACKEND_DICT_DIR=/tmp/dawg \
|
||||||
GOPRIVATE='gitea.iliadenisov.ru/*' \
|
GOPRIVATE='gitea.iliadenisov.ru/*' \
|
||||||
@@ -214,7 +267,14 @@ local solver co-development you may add a temporary replace — see `go.work`).
|
|||||||
from the [`scrabble-dictionary`](https://gitea.iliadenisov.ru/developer/scrabble-dictionary)
|
from the [`scrabble-dictionary`](https://gitea.iliadenisov.ru/developer/scrabble-dictionary)
|
||||||
repo (one semver per set); the engine loads them by `(variant, dict_version)` from
|
repo (one semver per set); the engine loads them by `(variant, dict_version)` from
|
||||||
`BACKEND_DICT_DIR`. The backend loads them at startup as a hard dependency
|
`BACKEND_DICT_DIR`. The backend loads them at startup as a hard dependency
|
||||||
(a missing dictionary aborts the boot).
|
(a missing dictionary aborts the boot). The flat directory is the seed version,
|
||||||
|
labelled `BACKEND_DICT_VERSION`; uploaded versions live in `<version>/`
|
||||||
|
subdirectories the admin console writes and a restart re-loads. Because the DAWGs
|
||||||
|
carry no embedded version, the first boot records the seed in a `.seed_version`
|
||||||
|
marker that is authoritative after: on a seeded volume a changed `BACKEND_DICT_VERSION`
|
||||||
|
is ignored (it seeds only a fresh volume) — the seed-drift guard — so a live contour's
|
||||||
|
dictionary is changed through the console, never by bumping the build seed
|
||||||
|
(ARCHITECTURE.md §5).
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
|
|||||||
@@ -15,13 +15,17 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
||||||
"scrabble/backend/internal/account"
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/accountmerge"
|
"scrabble/backend/internal/accountmerge"
|
||||||
|
"scrabble/backend/internal/ads"
|
||||||
|
"scrabble/backend/internal/banview"
|
||||||
"scrabble/backend/internal/config"
|
"scrabble/backend/internal/config"
|
||||||
"scrabble/backend/internal/connector"
|
"scrabble/backend/internal/connector"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/feedback"
|
||||||
"scrabble/backend/internal/game"
|
"scrabble/backend/internal/game"
|
||||||
"scrabble/backend/internal/link"
|
"scrabble/backend/internal/link"
|
||||||
"scrabble/backend/internal/lobby"
|
"scrabble/backend/internal/lobby"
|
||||||
@@ -157,6 +161,15 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
zap.Duration("interval", cfg.GuestReapInterval),
|
zap.Duration("interval", cfg.GuestReapInterval),
|
||||||
zap.Duration("retention", cfg.GuestRetention))
|
zap.Duration("retention", cfg.GuestRetention))
|
||||||
|
|
||||||
|
// Re-evaluate moderated-chat write access when a temporary block self-expires:
|
||||||
|
// no operator action fires then, so the sweeper emits the chat-access-changed
|
||||||
|
// event for lapsed blocks and the gateway re-pushes the chat-gate command.
|
||||||
|
chatSweeper := account.NewSuspensionSweeper(accounts, func(id uuid.UUID) {
|
||||||
|
hub.Publish(notify.ChatAccessChanged(id))
|
||||||
|
}, logger)
|
||||||
|
go chatSweeper.Run(ctx)
|
||||||
|
logger.Info("suspension expiry sweeper started", zap.Duration("interval", chatSweeper.Interval()))
|
||||||
|
|
||||||
// Lobby & social domains. Their REST and stream surface lives in the gateway,
|
// Lobby & social domains. Their REST and stream surface lives in the gateway,
|
||||||
// so they are handed to the server (like the route groups) for the handlers.
|
// so they are handed to the server (like the route groups) for the handlers.
|
||||||
mailer := newMailer(cfg.SMTP, logger)
|
mailer := newMailer(cfg.SMTP, logger)
|
||||||
@@ -167,6 +180,17 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
socialSvc := social.NewService(social.NewStore(db), accounts, games)
|
socialSvc := social.NewService(social.NewStore(db), accounts, games)
|
||||||
socialSvc.SetNotifier(hub)
|
socialSvc.SetNotifier(hub)
|
||||||
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
|
socialSvc.SetMetrics(tel.MeterProvider().Meter("scrabble/backend/social"))
|
||||||
|
// A nudge the recipient answered by moving is marked read on the move path.
|
||||||
|
games.SetNudgeClearer(socialSvc.ClearNudges)
|
||||||
|
// Reap per-game disguised-robot friend requests once their game is long finished
|
||||||
|
// (the robot ignores them; the row only pins the in-game "request sent" state).
|
||||||
|
robotReqReaper := social.NewRobotFriendRequestReaper(socialSvc, logger)
|
||||||
|
go robotReqReaper.Run(ctx)
|
||||||
|
logger.Info("robot friend request reaper started",
|
||||||
|
zap.Duration("interval", robotReqReaper.Interval()),
|
||||||
|
zap.Duration("retention", robotReqReaper.Retention()))
|
||||||
|
feedbackSvc := feedback.NewService(feedback.NewStore(db), accounts)
|
||||||
|
feedbackSvc.SetNotifier(hub)
|
||||||
|
|
||||||
// Robot opponent: provision its durable account pool (a hard startup
|
// Robot opponent: provision its durable account pool (a hard startup
|
||||||
// dependency, like the dictionaries) and start its move driver. The matchmaker
|
// dependency, like the dictionaries) and start its move driver. The matchmaker
|
||||||
@@ -175,11 +199,15 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
if err := robots.EnsurePool(ctx); err != nil {
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
return fmt.Errorf("provision robot pool: %w", err)
|
return fmt.Errorf("provision robot pool: %w", err)
|
||||||
}
|
}
|
||||||
|
// Honest-AI fast path: a move in a vs_ai game triggers the robot's reply at once
|
||||||
|
// (the periodic driver below is the fallback). Set after the pool is provisioned.
|
||||||
|
games.SetAITrigger(robots.TriggerMove)
|
||||||
go robots.Run(ctx, cfg.Robot.DriveInterval)
|
go robots.Run(ctx, cfg.Robot.DriveInterval)
|
||||||
logger.Info("robot driver started", zap.Duration("interval", cfg.Robot.DriveInterval))
|
logger.Info("robot driver started", zap.Duration("interval", cfg.Robot.DriveInterval))
|
||||||
|
|
||||||
matchmaker := lobby.NewMatchmaker(games, robots, cfg.Lobby.RobotWait, cfg.Lobby.RobotWaitJitter, logger)
|
matchmaker := lobby.NewMatchmaker(games, robots, cfg.Lobby.RobotWait, cfg.Lobby.RobotWaitJitter, logger)
|
||||||
matchmaker.SetNotifier(hub)
|
matchmaker.SetNotifier(hub)
|
||||||
|
matchmaker.SetBlocker(socialSvc)
|
||||||
go matchmaker.RunReaper(ctx, cfg.Lobby.ReaperInterval)
|
go matchmaker.RunReaper(ctx, cfg.Lobby.ReaperInterval)
|
||||||
invitations := lobby.NewInvitationService(lobby.NewStore(db), games, accounts, socialSvc)
|
invitations := lobby.NewInvitationService(lobby.NewStore(db), games, accounts, socialSvc)
|
||||||
invitations.SetNotifier(hub)
|
invitations.SetNotifier(hub)
|
||||||
@@ -194,6 +222,14 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
zap.Int("flag_threshold", cfg.RateWatch.FlagThreshold),
|
zap.Int("flag_threshold", cfg.RateWatch.FlagThreshold),
|
||||||
zap.Duration("flag_window", cfg.RateWatch.FlagWindow))
|
zap.Duration("flag_window", cfg.RateWatch.FlagWindow))
|
||||||
|
|
||||||
|
// Ban observability: mirror the gateway's active IP bans for the admin console's
|
||||||
|
// active-bans panel and collect operator unban requests.
|
||||||
|
banView := banview.New()
|
||||||
|
|
||||||
|
// Advertising-banner domain: campaign rotation feeding the profile.get banner
|
||||||
|
// block and the banner admin console section.
|
||||||
|
adsSvc := ads.NewService(ads.NewStore(db))
|
||||||
|
|
||||||
srv := server.New(cfg.HTTPAddr, server.Deps{
|
srv := server.New(cfg.HTTPAddr, server.Deps{
|
||||||
Logger: logger,
|
Logger: logger,
|
||||||
DB: db,
|
DB: db,
|
||||||
@@ -202,6 +238,7 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
Sessions: sessions,
|
Sessions: sessions,
|
||||||
Accounts: accounts,
|
Accounts: accounts,
|
||||||
Games: games,
|
Games: games,
|
||||||
|
Feedback: feedbackSvc,
|
||||||
Social: socialSvc,
|
Social: socialSvc,
|
||||||
Matchmaker: matchmaker,
|
Matchmaker: matchmaker,
|
||||||
Invitations: invitations,
|
Invitations: invitations,
|
||||||
@@ -211,6 +248,9 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
|||||||
DictDir: cfg.Game.DictDir,
|
DictDir: cfg.Game.DictDir,
|
||||||
Connector: conn,
|
Connector: conn,
|
||||||
RateWatch: rateWatch,
|
RateWatch: rateWatch,
|
||||||
|
BanView: banView,
|
||||||
|
Ads: adsSvc,
|
||||||
|
Notifier: hub,
|
||||||
})
|
})
|
||||||
pushSrv := pushgrpc.NewServer(cfg.GRPCAddr, hub, logger)
|
pushSrv := pushgrpc.NewServer(cfg.GRPCAddr, hub, logger)
|
||||||
|
|
||||||
|
|||||||
@@ -55,12 +55,12 @@ type Account struct {
|
|||||||
HintBalance int
|
HintBalance int
|
||||||
BlockChat bool
|
BlockChat bool
|
||||||
BlockFriendRequests bool
|
BlockFriendRequests bool
|
||||||
// ServiceLanguage is the language tag (en/ru) of the bot the account last
|
// VariantPreferences is the set of game variants (engine.Variant stable labels:
|
||||||
// authenticated through (its last Telegram ValidateInitData); it routes the
|
// "scrabble_en", "scrabble_ru", "erudit_ru") the player is willing to be matched
|
||||||
// account's out-of-app push back through the right bot. Empty when the account
|
// into. It gates the New Game picker, the matchmaker and the friend-invite the
|
||||||
// has never signed in through a tagged bot. Distinct from PreferredLanguage (the
|
// player creates; an invited friend may still accept any variant. A new account
|
||||||
// interface language) and from a game's variant language.
|
// defaults to Erudit only. Never empty — enforced on update and by a DB check.
|
||||||
ServiceLanguage string
|
VariantPreferences []string
|
||||||
// IsGuest marks an ephemeral guest account: a durable row with no identity,
|
// IsGuest marks an ephemeral guest account: a durable row with no identity,
|
||||||
// excluded from statistics, friends and history.
|
// excluded from statistics, friends and history.
|
||||||
IsGuest bool
|
IsGuest bool
|
||||||
@@ -99,12 +99,15 @@ type Identity struct {
|
|||||||
type Store struct {
|
type Store struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
metrics *accountMetrics
|
metrics *accountMetrics
|
||||||
|
// suspensions caches each account's current manual block, read by the suspension gate on
|
||||||
|
// every authenticated request and invalidated on Suspend/LiftSuspension. See suspension.go.
|
||||||
|
suspensions *suspensionCache
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewStore constructs a Store wrapping db. Metrics default to a no-op meter until
|
// NewStore constructs a Store wrapping db. Metrics default to a no-op meter until
|
||||||
// SetMetrics installs the real one during startup wiring.
|
// SetMetrics installs the real one during startup wiring.
|
||||||
func NewStore(db *sql.DB) *Store {
|
func NewStore(db *sql.DB) *Store {
|
||||||
return &Store{db: db, metrics: defaultAccountMetrics()}
|
return &Store{db: db, metrics: defaultAccountMetrics(), suspensions: newSuspensionCache()}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProvisionByIdentity returns the account bound to (kind, externalID), creating
|
// ProvisionByIdentity returns the account bound to (kind, externalID), creating
|
||||||
@@ -148,14 +151,26 @@ func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName stri
|
|||||||
return modelToAccount(row), nil
|
return modelToAccount(row), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProvisionTelegram provisions (or finds) the account bound to a Telegram
|
// ProvisionTelegram provisions (or finds) the account bound to a Telegram identity,
|
||||||
// identity. On first contact only, it seeds the new account's preferred language
|
// reporting whether this call created it (first contact). On first contact only, it
|
||||||
// from the Telegram client languageCode (when it maps to a supported language) and
|
// seeds the new account's preferred language from the Telegram client languageCode
|
||||||
// its display name sanitized from firstName (falling back to username, then to a
|
// (when it maps to a supported language) and its display name sanitized from firstName
|
||||||
// generated placeholder when neither yields any letters); an already-existing
|
// (falling back to username, then to a generated placeholder when neither yields any
|
||||||
// account is returned unchanged, so a later profile edit is never overwritten.
|
// letters); an already-existing account is returned unchanged, so a later profile edit
|
||||||
func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode, username, firstName string) (Account, error) {
|
// is never overwritten. The created flag lets the auth handler re-evaluate moderated-
|
||||||
return s.provision(ctx, KindTelegram, externalID, telegramSeed(languageCode, username, firstName))
|
// chat write access on first registration — the path of a user who joined the chat
|
||||||
|
// before registering, whom no chat_member event covers.
|
||||||
|
func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode, username, firstName string) (Account, bool, error) {
|
||||||
|
// Pre-check whether the identity already exists so the caller can act on first
|
||||||
|
// contact. A race with a concurrent create only over- or under-reports created for
|
||||||
|
// that one call, which the idempotent chat-access re-evaluation tolerates.
|
||||||
|
_, err := s.findByIdentity(ctx, KindTelegram, externalID)
|
||||||
|
created := errors.Is(err, ErrNotFound)
|
||||||
|
if err != nil && !created {
|
||||||
|
return Account{}, false, err
|
||||||
|
}
|
||||||
|
acc, err := s.provision(ctx, KindTelegram, externalID, telegramSeed(languageCode, username, firstName))
|
||||||
|
return acc, created, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// provision finds the account for (kind, externalID) or creates it with seed,
|
// provision finds the account for (kind, externalID) or creates it with seed,
|
||||||
@@ -300,6 +315,14 @@ func (s *Store) CountAccounts(ctx context.Context) (int, error) {
|
|||||||
return int(dest.Count), nil
|
return int(dest.Count), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AccountByIdentity returns the account bound to (kind, externalID), or ErrNotFound
|
||||||
|
// when none exists. Unlike ProvisionByIdentity it never creates one: the chat-access
|
||||||
|
// resolver uses it to tell a registered Telegram user (eligible to be granted chat
|
||||||
|
// write access) from an unregistered one (left muted).
|
||||||
|
func (s *Store) AccountByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
||||||
|
return s.findByIdentity(ctx, kind, externalID)
|
||||||
|
}
|
||||||
|
|
||||||
// findByIdentity joins identities to accounts and returns the matching account,
|
// findByIdentity joins identities to accounts and returns the matching account,
|
||||||
// or ErrNotFound.
|
// or ErrNotFound.
|
||||||
func (s *Store) findByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
func (s *Store) findByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
||||||
@@ -427,6 +450,30 @@ func (s *Store) SpendHint(ctx context.Context, id uuid.UUID) (bool, error) {
|
|||||||
return n > 0, nil
|
return n > 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GrantHints adds n hints to the account's wallet and returns the new balance. n must be
|
||||||
|
// positive: the additive update can only raise the balance, never lower it, so it enforces the
|
||||||
|
// admin console's raise-only rule by construction and stays correct under a concurrent SpendHint.
|
||||||
|
// It returns ErrNotFound when no account matches.
|
||||||
|
func (s *Store) GrantHints(ctx context.Context, id uuid.UUID, n int) (int, error) {
|
||||||
|
if n <= 0 {
|
||||||
|
return 0, fmt.Errorf("account: grant hints %s: n must be positive, got %d", id, n)
|
||||||
|
}
|
||||||
|
stmt := table.Accounts.
|
||||||
|
UPDATE(table.Accounts.HintBalance, table.Accounts.UpdatedAt).
|
||||||
|
SET(table.Accounts.HintBalance.ADD(postgres.Int(int64(n))), postgres.TimestampzT(time.Now().UTC())).
|
||||||
|
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(id))).
|
||||||
|
RETURNING(table.Accounts.HintBalance)
|
||||||
|
|
||||||
|
var row model.Accounts
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return 0, ErrNotFound
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("account: grant hints %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return int(row.HintBalance), nil
|
||||||
|
}
|
||||||
|
|
||||||
// FlagHighRate stamps the soft "suspected high-rate" marker with at, only when
|
// FlagHighRate stamps the soft "suspected high-rate" marker with at, only when
|
||||||
// the account is not already flagged — the first sustained episode wins, and a
|
// the account is not already flagged — the first sustained episode wins, and a
|
||||||
// re-flag after an operator clear starts a fresh timestamp. An infra marker, not
|
// re-flag after an operator clear starts a fresh timestamp. An infra marker, not
|
||||||
@@ -464,36 +511,12 @@ func (s *Store) ClearHighRateFlag(ctx context.Context, id uuid.UUID) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetServiceLanguage records the service language (en/ru) of the bot a Telegram
|
|
||||||
// user authenticated through. It is called on every Telegram login — new and
|
|
||||||
// existing accounts — so it tracks the bot the user last came through (last-login-
|
|
||||||
// wins), and the out-of-app push routes by it. It is a no-op for an empty language
|
|
||||||
// (a non-Telegram login carries none) and does not bump updated_at (an infra
|
|
||||||
// routing field, not a user profile edit).
|
|
||||||
func (s *Store) SetServiceLanguage(ctx context.Context, id uuid.UUID, language string) error {
|
|
||||||
if language == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
stmt := table.Accounts.
|
|
||||||
UPDATE(table.Accounts.ServiceLanguage).
|
|
||||||
SET(postgres.String(language)).
|
|
||||||
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(id)))
|
|
||||||
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
|
||||||
return fmt.Errorf("account: set service language %s: %w", id, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// modelToAccount projects a generated model row into the public Account struct.
|
// modelToAccount projects a generated model row into the public Account struct.
|
||||||
func modelToAccount(row model.Accounts) Account {
|
func modelToAccount(row model.Accounts) Account {
|
||||||
var mergedInto uuid.UUID
|
var mergedInto uuid.UUID
|
||||||
if row.MergedInto != nil {
|
if row.MergedInto != nil {
|
||||||
mergedInto = *row.MergedInto
|
mergedInto = *row.MergedInto
|
||||||
}
|
}
|
||||||
var serviceLanguage string
|
|
||||||
if row.ServiceLanguage != nil {
|
|
||||||
serviceLanguage = *row.ServiceLanguage
|
|
||||||
}
|
|
||||||
var flaggedHighRateAt time.Time
|
var flaggedHighRateAt time.Time
|
||||||
if row.FlaggedHighRateAt != nil {
|
if row.FlaggedHighRateAt != nil {
|
||||||
flaggedHighRateAt = *row.FlaggedHighRateAt
|
flaggedHighRateAt = *row.FlaggedHighRateAt
|
||||||
@@ -502,7 +525,7 @@ func modelToAccount(row model.Accounts) Account {
|
|||||||
ID: row.AccountID,
|
ID: row.AccountID,
|
||||||
DisplayName: row.DisplayName,
|
DisplayName: row.DisplayName,
|
||||||
PreferredLanguage: row.PreferredLanguage,
|
PreferredLanguage: row.PreferredLanguage,
|
||||||
ServiceLanguage: serviceLanguage,
|
VariantPreferences: []string(row.VariantPreferences),
|
||||||
TimeZone: row.TimeZone,
|
TimeZone: row.TimeZone,
|
||||||
AwayStart: row.AwayStart,
|
AwayStart: row.AwayStart,
|
||||||
AwayEnd: row.AwayEnd,
|
AwayEnd: row.AwayEnd,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"github.com/go-jet/jet/v2/postgres"
|
"github.com/go-jet/jet/v2/postgres"
|
||||||
"github.com/go-jet/jet/v2/qrm"
|
"github.com/go-jet/jet/v2/qrm"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/lib/pq"
|
||||||
|
|
||||||
"scrabble/backend/internal/postgres/jet/backend/model"
|
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
@@ -23,9 +24,10 @@ import (
|
|||||||
// is unbounded; auto-provisioned platform names bypass this editor validation).
|
// is unbounded; auto-provisioned platform names bypass this editor validation).
|
||||||
const maxDisplayName = 32
|
const maxDisplayName = 32
|
||||||
|
|
||||||
// maxDisplayNameSpecials caps the total special characters (the "." / "_" separators —
|
// maxDisplayNameSpecials caps the total special characters (every name rune that is
|
||||||
// every name rune that is neither a letter nor a space) an editable display name may
|
// neither a letter, a space, nor a digit — i.e. the "." / "_" separators) an editable
|
||||||
// carry, so a still-well-formed name cannot be made of mostly punctuation.
|
// display name may carry, so a still-well-formed name cannot be made of mostly
|
||||||
|
// punctuation. A trailing digit run is bounded separately by displayNameRe.
|
||||||
const maxDisplayNameSpecials = 5
|
const maxDisplayNameSpecials = 5
|
||||||
|
|
||||||
// maxAwayWindow bounds the daily away window's duration (midnight-wrap aware).
|
// maxAwayWindow bounds the daily away window's duration (midnight-wrap aware).
|
||||||
@@ -34,9 +36,11 @@ const maxAwayWindow = 12 * time.Hour
|
|||||||
// displayNameRe enforces the editable display-name format: Unicode letters
|
// displayNameRe enforces the editable display-name format: Unicode letters
|
||||||
// joined by single space / "." / "_" separators, where a "." or "_" may be followed
|
// joined by single space / "." / "_" separators, where a "." or "_" may be followed
|
||||||
// by a single space. No leading separator and no two adjacent separators (except
|
// by a single space. No leading separator and no two adjacent separators (except
|
||||||
// "<dot|underscore> <space>"); a single trailing "." is allowed, so
|
// "<dot|underscore> <space>"). The name may end with EITHER a single trailing "."
|
||||||
// "Name_P. Last" and "Anna B." are valid, "Name P._Last" is not.
|
// (an initial, "Anna B.") OR a run of 1–5 digits (a handle's number or year,
|
||||||
var displayNameRe = regexp.MustCompile(`^\p{L}+(?:(?:[._] ?| )\p{L}+)*\.?$`)
|
// "Player2007"), but not both; digits never appear elsewhere. So "Name_P. Last",
|
||||||
|
// "Anna B." and "Аня2007" are valid, while "Name P._Last" and "Dark2Wolf" are not.
|
||||||
|
var displayNameRe = regexp.MustCompile(`^\p{L}+(?:(?:[._] ?| )\p{L}+)*(?:\.|[0-9]{1,5})?$`)
|
||||||
|
|
||||||
// ErrInvalidProfile is returned when a profile update carries an unacceptable
|
// ErrInvalidProfile is returned when a profile update carries an unacceptable
|
||||||
// field (an unknown language, an invalid timezone, or an over-long display name).
|
// field (an unknown language, an invalid timezone, or an over-long display name).
|
||||||
@@ -55,6 +59,46 @@ type ProfileUpdate struct {
|
|||||||
BlockChat bool
|
BlockChat bool
|
||||||
BlockFriendRequests bool
|
BlockFriendRequests bool
|
||||||
NotificationsInAppOnly bool
|
NotificationsInAppOnly bool
|
||||||
|
// VariantPreferences is the set of game variants the player allows themselves to
|
||||||
|
// be matched into (engine.Variant stable labels). UpdateProfile cleans it to a
|
||||||
|
// deduplicated, canonically ordered subset of the known variants and rejects an
|
||||||
|
// empty set.
|
||||||
|
VariantPreferences []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// knownVariants is the closed set of game-variant labels (engine.Variant stable
|
||||||
|
// labels) a profile's variant preferences may contain. It lives here so the store
|
||||||
|
// does not depend on the engine package; the server handler additionally validates
|
||||||
|
// against engine.ParseVariant, and a DB check enforces the same subset.
|
||||||
|
var knownVariants = map[string]bool{"erudit_ru": true, "scrabble_ru": true, "scrabble_en": true}
|
||||||
|
|
||||||
|
// canonicalVariantOrder is the deterministic order variant preferences are stored
|
||||||
|
// in (Erudit, Russian Scrabble, English), independent of the client's order.
|
||||||
|
var canonicalVariantOrder = []string{"erudit_ru", "scrabble_ru", "scrabble_en"}
|
||||||
|
|
||||||
|
// validateVariantPreferences cleans a profile's variant-preference set: it drops
|
||||||
|
// duplicates, rejects an unknown label or an empty set (ErrInvalidProfile) and
|
||||||
|
// returns the preferences in canonicalVariantOrder so the stored value is
|
||||||
|
// deterministic regardless of the order the client sent.
|
||||||
|
func validateVariantPreferences(prefs []string) ([]string, error) {
|
||||||
|
seen := make(map[string]bool, len(prefs))
|
||||||
|
for _, p := range prefs {
|
||||||
|
p = strings.TrimSpace(p)
|
||||||
|
if !knownVariants[p] {
|
||||||
|
return nil, fmt.Errorf("%w: variant preference %q", ErrInvalidProfile, p)
|
||||||
|
}
|
||||||
|
seen[p] = true
|
||||||
|
}
|
||||||
|
if len(seen) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: variant preferences must not be empty", ErrInvalidProfile)
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(seen))
|
||||||
|
for _, v := range canonicalVariantOrder {
|
||||||
|
if seen[v] {
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateProfile validates and overwrites the editable fields of the account, then
|
// UpdateProfile validates and overwrites the editable fields of the account, then
|
||||||
@@ -76,17 +120,26 @@ func (s *Store) UpdateProfile(ctx context.Context, id uuid.UUID, p ProfileUpdate
|
|||||||
if err := validateAwayWindow(p.AwayStart, p.AwayEnd); err != nil {
|
if err := validateAwayWindow(p.AwayStart, p.AwayEnd); err != nil {
|
||||||
return Account{}, err
|
return Account{}, err
|
||||||
}
|
}
|
||||||
|
prefs, err := validateVariantPreferences(p.VariantPreferences)
|
||||||
|
if err != nil {
|
||||||
|
return Account{}, err
|
||||||
|
}
|
||||||
|
|
||||||
stmt := table.Accounts.UPDATE(
|
stmt := table.Accounts.UPDATE(
|
||||||
table.Accounts.DisplayName, table.Accounts.PreferredLanguage, table.Accounts.TimeZone,
|
table.Accounts.DisplayName, table.Accounts.PreferredLanguage, table.Accounts.TimeZone,
|
||||||
table.Accounts.AwayStart, table.Accounts.AwayEnd,
|
table.Accounts.AwayStart, table.Accounts.AwayEnd,
|
||||||
table.Accounts.BlockChat, table.Accounts.BlockFriendRequests,
|
table.Accounts.BlockChat, table.Accounts.BlockFriendRequests,
|
||||||
table.Accounts.NotificationsInAppOnly, table.Accounts.UpdatedAt,
|
table.Accounts.NotificationsInAppOnly, table.Accounts.VariantPreferences,
|
||||||
|
table.Accounts.UpdatedAt,
|
||||||
).SET(
|
).SET(
|
||||||
postgres.String(name), postgres.String(lang), postgres.String(tz),
|
postgres.String(name), postgres.String(lang), postgres.String(tz),
|
||||||
postgres.TimeT(p.AwayStart), postgres.TimeT(p.AwayEnd),
|
postgres.TimeT(p.AwayStart), postgres.TimeT(p.AwayEnd),
|
||||||
postgres.Bool(p.BlockChat), postgres.Bool(p.BlockFriendRequests),
|
postgres.Bool(p.BlockChat), postgres.Bool(p.BlockFriendRequests),
|
||||||
postgres.Bool(p.NotificationsInAppOnly), postgres.TimestampzT(time.Now().UTC()),
|
postgres.Bool(p.NotificationsInAppOnly),
|
||||||
|
// prefs are validated against the closed knownVariants set; bind as a text[]
|
||||||
|
// parameter (lib/pq encodes the array, the cast pins the column type).
|
||||||
|
postgres.Raw("#variant_prefs::text[]", map[string]interface{}{"#variant_prefs": pq.StringArray(prefs)}),
|
||||||
|
postgres.TimestampzT(time.Now().UTC()),
|
||||||
).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(id))).
|
).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(id))).
|
||||||
RETURNING(table.Accounts.AllColumns)
|
RETURNING(table.Accounts.AllColumns)
|
||||||
|
|
||||||
@@ -117,7 +170,7 @@ func ValidateDisplayName(raw string) (string, error) {
|
|||||||
}
|
}
|
||||||
specials := 0
|
specials := 0
|
||||||
for _, r := range name {
|
for _, r := range name {
|
||||||
if r != ' ' && !unicode.IsLetter(r) {
|
if r != ' ' && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
|
||||||
specials++
|
specials++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package account
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -16,7 +17,7 @@ import (
|
|||||||
// offset/IANA timezone), not just their unit tests in validate_test.go.
|
// offset/IANA timezone), not just their unit tests in validate_test.go.
|
||||||
func TestUpdateProfileValidation(t *testing.T) {
|
func TestUpdateProfileValidation(t *testing.T) {
|
||||||
s := &Store{}
|
s := &Store{}
|
||||||
base := ProfileUpdate{DisplayName: "Kaya", PreferredLanguage: "en", TimeZone: "UTC"}
|
base := ProfileUpdate{DisplayName: "Kaya", PreferredLanguage: "en", TimeZone: "UTC", VariantPreferences: []string{"erudit_ru"}}
|
||||||
hm := func(h, m int) time.Time { return time.Date(0, 1, 1, h, m, 0, 0, time.UTC) }
|
hm := func(h, m int) time.Time { return time.Date(0, 1, 1, h, m, 0, 0, time.UTC) }
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -28,6 +29,8 @@ func TestUpdateProfileValidation(t *testing.T) {
|
|||||||
{"over-long name", func(p *ProfileUpdate) { p.DisplayName = strings.Repeat("x", maxDisplayName+1) }},
|
{"over-long name", func(p *ProfileUpdate) { p.DisplayName = strings.Repeat("x", maxDisplayName+1) }},
|
||||||
{"bad name layout", func(p *ProfileUpdate) { p.DisplayName = "Bad__Name" }},
|
{"bad name layout", func(p *ProfileUpdate) { p.DisplayName = "Bad__Name" }},
|
||||||
{"away over 12h", func(p *ProfileUpdate) { p.AwayStart, p.AwayEnd = hm(8, 0), hm(21, 0) }},
|
{"away over 12h", func(p *ProfileUpdate) { p.AwayStart, p.AwayEnd = hm(8, 0), hm(21, 0) }},
|
||||||
|
{"empty variant preferences", func(p *ProfileUpdate) { p.VariantPreferences = nil }},
|
||||||
|
{"unknown variant preference", func(p *ProfileUpdate) { p.VariantPreferences = []string{"chess"} }},
|
||||||
}
|
}
|
||||||
for _, tc := range tests {
|
for _, tc := range tests {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
@@ -39,3 +42,22 @@ func TestUpdateProfileValidation(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestValidateVariantPreferences checks the cleaning of a profile's variant set:
|
||||||
|
// duplicates collapse, the result is canonically ordered (Erudit, Russian Scrabble,
|
||||||
|
// English) regardless of input order, and an empty or unknown set is rejected.
|
||||||
|
func TestValidateVariantPreferences(t *testing.T) {
|
||||||
|
got, err := validateVariantPreferences([]string{"scrabble_en", "erudit_ru", "scrabble_en"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("validate: %v", err)
|
||||||
|
}
|
||||||
|
if want := []string{"erudit_ru", "scrabble_en"}; !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("got %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if _, err := validateVariantPreferences(nil); !errors.Is(err, ErrInvalidProfile) {
|
||||||
|
t.Fatalf("empty err = %v, want ErrInvalidProfile", err)
|
||||||
|
}
|
||||||
|
if _, err := validateVariantPreferences([]string{"chess"}); !errors.Is(err, ErrInvalidProfile) {
|
||||||
|
t.Fatalf("unknown err = %v, want ErrInvalidProfile", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/go-jet/jet/v2/postgres"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Per-account roles. A role is a named capability or restriction attached to an
|
||||||
|
// account, the reusable replacement for per-feature boolean flags. The set is
|
||||||
|
// expected to grow; roles are validated against KnownRoles in Go so adding one
|
||||||
|
// needs no migration. Granted/revoked from the admin console (/users and the
|
||||||
|
// feedback section).
|
||||||
|
const (
|
||||||
|
// RoleFeedbackBanned forbids the account from submitting feedback (only that;
|
||||||
|
// it is not a full account suspension). See internal/feedback.
|
||||||
|
RoleFeedbackBanned = "feedback_banned"
|
||||||
|
|
||||||
|
// RoleNoBanner suppresses the in-app advertising banner for the account
|
||||||
|
// unconditionally, overriding the usual eligibility (a free account with an
|
||||||
|
// empty hint wallet otherwise sees it). See internal/ads.
|
||||||
|
RoleNoBanner = "no_banner"
|
||||||
|
|
||||||
|
// RoleChatMuted forbids the account from writing in the moderated Telegram
|
||||||
|
// discussion chat, without otherwise restricting the game (the chat-only
|
||||||
|
// counterpart to a full account suspension). It is one input to the chat-access
|
||||||
|
// gate; an active admin suspension mutes the player regardless, so this role only
|
||||||
|
// matters for an account that is not suspended. Granting or revoking it re-pushes
|
||||||
|
// the chat-gate command for a member currently in the chat.
|
||||||
|
RoleChatMuted = "chat_muted"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KnownRoles is the set of roles the console may grant or revoke; an operator
|
||||||
|
// cannot assign an unrecognised role.
|
||||||
|
var KnownRoles = []string{RoleFeedbackBanned, RoleNoBanner, RoleChatMuted}
|
||||||
|
|
||||||
|
// IsKnownRole reports whether role is a recognised account role.
|
||||||
|
func IsKnownRole(role string) bool {
|
||||||
|
for _, r := range KnownRoles {
|
||||||
|
if r == role {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// GrantRole gives the account the role, idempotently (a repeat grant is a no-op).
|
||||||
|
func (s *Store) GrantRole(ctx context.Context, accountID uuid.UUID, role string) error {
|
||||||
|
stmt := table.AccountRoles.
|
||||||
|
INSERT(table.AccountRoles.AccountID, table.AccountRoles.Role).
|
||||||
|
VALUES(accountID, role).
|
||||||
|
ON_CONFLICT(table.AccountRoles.AccountID, table.AccountRoles.Role).DO_NOTHING()
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return fmt.Errorf("account: grant role %q to %s: %w", role, accountID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeRole removes the role from the account, idempotently.
|
||||||
|
func (s *Store) RevokeRole(ctx context.Context, accountID uuid.UUID, role string) error {
|
||||||
|
stmt := table.AccountRoles.
|
||||||
|
DELETE().
|
||||||
|
WHERE(table.AccountRoles.AccountID.EQ(postgres.UUID(accountID)).
|
||||||
|
AND(table.AccountRoles.Role.EQ(postgres.String(role))))
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return fmt.Errorf("account: revoke role %q from %s: %w", role, accountID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasRole reports whether the account holds the role.
|
||||||
|
func (s *Store) HasRole(ctx context.Context, accountID uuid.UUID, role string) (bool, error) {
|
||||||
|
var ok bool
|
||||||
|
err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT EXISTS (SELECT 1 FROM backend.account_roles WHERE account_id = $1 AND role = $2)`,
|
||||||
|
accountID, role).Scan(&ok)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("account: has-role %q %s: %w", role, accountID, err)
|
||||||
|
}
|
||||||
|
return ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRoles returns the account's roles, oldest grant first.
|
||||||
|
func (s *Store) ListRoles(ctx context.Context, accountID uuid.UUID) ([]string, error) {
|
||||||
|
rows, err := s.db.QueryContext(ctx,
|
||||||
|
`SELECT role FROM backend.account_roles WHERE account_id = $1 ORDER BY granted_at ASC`,
|
||||||
|
accountID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("account: list roles %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []string
|
||||||
|
for rows.Next() {
|
||||||
|
var role string
|
||||||
|
if err := rows.Scan(&role); err != nil {
|
||||||
|
return nil, fmt.Errorf("account: scan role: %w", err)
|
||||||
|
}
|
||||||
|
out = append(out, role)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package account
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
@@ -13,16 +14,43 @@ import (
|
|||||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// BestMoveTile is one letter cell of a best-move word: its concrete letter (the
|
||||||
|
// designated letter for a blank), its tile point value (0 for a blank) and whether it
|
||||||
|
// is a blank. It is the persisted/served shape: the game domain marshals a slice of
|
||||||
|
// these into account_best_move.tiles, and the statistics screen renders them as game
|
||||||
|
// tiles without consulting the variant's alphabet.
|
||||||
|
type BestMoveTile struct {
|
||||||
|
Letter string `json:"letter"`
|
||||||
|
Value int `json:"value"`
|
||||||
|
Blank bool `json:"blank"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BestMove is an account's highest-scoring single play within one game variant: the
|
||||||
|
// move's total score (every word it formed plus the all-tiles bonus, matching
|
||||||
|
// MaxWordPoints) and its main word as an ordered slice of tiles.
|
||||||
|
type BestMove struct {
|
||||||
|
Variant string
|
||||||
|
Score int
|
||||||
|
Tiles []BestMoveTile
|
||||||
|
}
|
||||||
|
|
||||||
// Stats is a durable account's lifetime record, written by the game domain on each
|
// Stats is a durable account's lifetime record, written by the game domain on each
|
||||||
// finish and read for the player's statistics screen. MaxGamePoints is the best
|
// finish and read for the player's statistics screen. MaxGamePoints is the best
|
||||||
// single game's total; MaxWordPoints is the best single move's score (which already
|
// single game's total; MaxWordPoints is the best single move's score (which already
|
||||||
// includes every word it formed plus the all-tiles bonus).
|
// includes every word it formed plus the all-tiles bonus). BestMoves holds the same
|
||||||
|
// best move broken down per variant, with the word itself — empty for an account with
|
||||||
|
// no recorded play yet, and never carrying a variant the account has not played.
|
||||||
type Stats struct {
|
type Stats struct {
|
||||||
Wins int
|
Wins int
|
||||||
Losses int
|
Losses int
|
||||||
Draws int
|
Draws int
|
||||||
MaxGamePoints int
|
MaxGamePoints int
|
||||||
MaxWordPoints int
|
MaxWordPoints int
|
||||||
|
// Moves is the lifetime count of the account's plays (tile placements); HintsUsed is the
|
||||||
|
// lifetime count of hints taken. The statistics screen shows the hint share (HintsUsed / Moves).
|
||||||
|
Moves int
|
||||||
|
HintsUsed int
|
||||||
|
BestMoves []BestMove
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetStats returns the lifetime statistics for id. An account with no account_stats
|
// GetStats returns the lifetime statistics for id. An account with no account_stats
|
||||||
@@ -40,11 +68,48 @@ func (s *Store) GetStats(ctx context.Context, id uuid.UUID) (Stats, error) {
|
|||||||
}
|
}
|
||||||
return Stats{}, fmt.Errorf("account: get stats %s: %w", id, err)
|
return Stats{}, fmt.Errorf("account: get stats %s: %w", id, err)
|
||||||
}
|
}
|
||||||
|
best, err := s.bestMoves(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return Stats{}, err
|
||||||
|
}
|
||||||
return Stats{
|
return Stats{
|
||||||
Wins: int(row.Wins),
|
Wins: int(row.Wins),
|
||||||
Losses: int(row.Losses),
|
Losses: int(row.Losses),
|
||||||
Draws: int(row.Draws),
|
Draws: int(row.Draws),
|
||||||
MaxGamePoints: int(row.MaxGamePoints),
|
MaxGamePoints: int(row.MaxGamePoints),
|
||||||
MaxWordPoints: int(row.MaxWordPoints),
|
MaxWordPoints: int(row.MaxWordPoints),
|
||||||
|
Moves: int(row.Moves),
|
||||||
|
HintsUsed: int(row.HintsUsed),
|
||||||
|
BestMoves: best,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// bestMoves reads an account's per-variant best moves, ordered by variant for a stable
|
||||||
|
// response. Each row's tiles JSON is decoded into the served BestMoveTile slice. An
|
||||||
|
// account with no recorded play yields an empty (nil) slice rather than an error.
|
||||||
|
func (s *Store) bestMoves(ctx context.Context, id uuid.UUID) ([]BestMove, error) {
|
||||||
|
stmt := postgres.SELECT(
|
||||||
|
table.AccountBestMove.Variant,
|
||||||
|
table.AccountBestMove.Score,
|
||||||
|
table.AccountBestMove.Tiles,
|
||||||
|
).
|
||||||
|
FROM(table.AccountBestMove).
|
||||||
|
WHERE(table.AccountBestMove.AccountID.EQ(postgres.UUID(id))).
|
||||||
|
ORDER_BY(table.AccountBestMove.Variant.ASC())
|
||||||
|
var rows []model.AccountBestMove
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("account: best moves %s: %w", id, err)
|
||||||
|
}
|
||||||
|
out := make([]BestMove, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
var tiles []BestMoveTile
|
||||||
|
if err := json.Unmarshal([]byte(r.Tiles), &tiles); err != nil {
|
||||||
|
return nil, fmt.Errorf("account: decode best-move tiles %s/%s: %w", id, r.Variant, err)
|
||||||
|
}
|
||||||
|
out = append(out, BestMove{Variant: r.Variant, Score: int(r.Score), Tiles: tiles})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,375 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-jet/jet/v2/postgres"
|
||||||
|
"github.com/go-jet/jet/v2/qrm"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||||
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Suspension is an account's currently-in-force manual block, the operator's hard counterpart
|
||||||
|
// to the soft, reversible FlaggedHighRateAt marker. It is named "suspension" to stay distinct
|
||||||
|
// from the peer-to-peer blocks in internal/social (one player muting another); the vocabulary
|
||||||
|
// the player sees is "blocked". BlockedUntil is nil for a permanent block and the expiry
|
||||||
|
// instant for a temporary one. ReasonEn and ReasonRu are the reason-text snapshot taken at
|
||||||
|
// block time (both empty when no reason was cited), so editing or deleting the picklist entry
|
||||||
|
// never changes what an already-blocked player is shown.
|
||||||
|
type Suspension struct {
|
||||||
|
AccountID uuid.UUID
|
||||||
|
BlockedAt time.Time
|
||||||
|
BlockedUntil *time.Time
|
||||||
|
ReasonEn string
|
||||||
|
ReasonRu string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permanent reports whether the suspension has no expiry.
|
||||||
|
func (s Suspension) Permanent() bool { return s.BlockedUntil == nil }
|
||||||
|
|
||||||
|
// LocalizedReason returns the reason text in the given language ("ru" selects Russian, anything
|
||||||
|
// else English), or empty when no reason was cited. The two snapshots are always both set or
|
||||||
|
// both empty, since a reason is chosen from the en+ru picklist.
|
||||||
|
func (s Suspension) LocalizedReason(language string) string {
|
||||||
|
if language == "ru" {
|
||||||
|
return s.ReasonRu
|
||||||
|
}
|
||||||
|
return s.ReasonEn
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reason is one entry of the operator-editable suspension-reason picklist, carrying the English
|
||||||
|
// and Russian text shown to a blocked player in their language.
|
||||||
|
type Reason struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
TextEn string
|
||||||
|
TextRu string
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suspend records a new manual block on the account: permanent when until is nil, otherwise in
|
||||||
|
// force until that instant. reasonEn and reasonRu are the optional reason-text snapshot (both
|
||||||
|
// empty for no reason) and reasonID is the loose picklist link (nil when none, nulled later if
|
||||||
|
// that entry is deleted). It returns the persisted Suspension. Suspending an already-blocked
|
||||||
|
// account simply appends another block; CurrentSuspension always reflects the strongest.
|
||||||
|
func (s *Store) Suspend(ctx context.Context, accountID uuid.UUID, until *time.Time, reasonEn, reasonRu string, reasonID *uuid.UUID) (Suspension, error) {
|
||||||
|
suspensionID, err := uuid.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
return Suspension{}, fmt.Errorf("account: new suspension id: %w", err)
|
||||||
|
}
|
||||||
|
stmt := table.AccountSuspensions.INSERT(
|
||||||
|
table.AccountSuspensions.SuspensionID,
|
||||||
|
table.AccountSuspensions.AccountID,
|
||||||
|
table.AccountSuspensions.BlockedUntil,
|
||||||
|
table.AccountSuspensions.ReasonEn,
|
||||||
|
table.AccountSuspensions.ReasonRu,
|
||||||
|
table.AccountSuspensions.ReasonID,
|
||||||
|
).VALUES(
|
||||||
|
suspensionID,
|
||||||
|
accountID,
|
||||||
|
nullableTimestamp(until),
|
||||||
|
nullableString(reasonEn),
|
||||||
|
nullableString(reasonRu),
|
||||||
|
nullableUUID(reasonID),
|
||||||
|
).RETURNING(table.AccountSuspensions.AllColumns)
|
||||||
|
|
||||||
|
var row model.AccountSuspensions
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
return Suspension{}, fmt.Errorf("account: suspend %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
s.invalidateSuspension(accountID)
|
||||||
|
return modelToSuspension(row), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LiftSuspension lifts every in-force block on the account (the operator's manual unblock),
|
||||||
|
// stamping lifted_at on each. It is a no-op when the account is not currently blocked. Lifting
|
||||||
|
// does not un-resign games already forfeited at block time — those stay lost.
|
||||||
|
func (s *Store) LiftSuspension(ctx context.Context, accountID uuid.UUID) error {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
stmt := table.AccountSuspensions.
|
||||||
|
UPDATE(table.AccountSuspensions.LiftedAt).
|
||||||
|
SET(postgres.TimestampzT(now)).
|
||||||
|
WHERE(
|
||||||
|
table.AccountSuspensions.AccountID.EQ(postgres.UUID(accountID)).
|
||||||
|
AND(activeSuspensionPredicate(now)),
|
||||||
|
)
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return fmt.Errorf("account: lift suspension %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
s.invalidateSuspension(accountID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurrentSuspension returns the account's in-force block and true, or false when the account is
|
||||||
|
// not blocked. When several blocks overlap it returns the strongest — a permanent one first,
|
||||||
|
// otherwise the latest-expiring — which is what the player's blocked screen shows. The gate
|
||||||
|
// middleware calls it on every authenticated request, served by account_suspensions_account_idx.
|
||||||
|
func (s *Store) CurrentSuspension(ctx context.Context, accountID uuid.UUID) (Suspension, bool, error) {
|
||||||
|
// A store with no database (the zero-value store used by the routing unit tests) has no
|
||||||
|
// suspensions; report not-blocked rather than dereferencing a nil pool. A real pool that
|
||||||
|
// errors still surfaces the error to the gate, which fails closed.
|
||||||
|
if s.db == nil {
|
||||||
|
return Suspension{}, false, nil
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
if s.suspensions != nil {
|
||||||
|
if e, ok := s.suspensions.get(accountID); ok {
|
||||||
|
if !e.found {
|
||||||
|
return Suspension{}, false, nil // cached: not blocked
|
||||||
|
}
|
||||||
|
if suspensionActiveAt(e.susp, now) {
|
||||||
|
return e.susp, true, nil // cached block still in force
|
||||||
|
}
|
||||||
|
// The cached block has lapsed since it was cached; refresh from the database below.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
susp, found, err := s.queryCurrentSuspension(ctx, accountID, now)
|
||||||
|
if err != nil {
|
||||||
|
return Suspension{}, false, err
|
||||||
|
}
|
||||||
|
if s.suspensions != nil {
|
||||||
|
s.suspensions.put(accountID, suspensionCacheEntry{susp: susp, found: found})
|
||||||
|
}
|
||||||
|
return susp, found, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryCurrentSuspension reads the account's strongest in-force block straight from the database
|
||||||
|
// (no cache), as of now. It backs CurrentSuspension on a cache miss or a lapsed entry.
|
||||||
|
func (s *Store) queryCurrentSuspension(ctx context.Context, accountID uuid.UUID, now time.Time) (Suspension, bool, error) {
|
||||||
|
stmt := postgres.SELECT(table.AccountSuspensions.AllColumns).
|
||||||
|
FROM(table.AccountSuspensions).
|
||||||
|
WHERE(
|
||||||
|
table.AccountSuspensions.AccountID.EQ(postgres.UUID(accountID)).
|
||||||
|
AND(activeSuspensionPredicate(now)),
|
||||||
|
).
|
||||||
|
ORDER_BY(table.AccountSuspensions.BlockedUntil.DESC().NULLS_FIRST()).
|
||||||
|
LIMIT(1)
|
||||||
|
|
||||||
|
var row model.AccountSuspensions
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return Suspension{}, false, nil
|
||||||
|
}
|
||||||
|
return Suspension{}, false, fmt.Errorf("account: current suspension %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
return modelToSuspension(row), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuspensionsExpiredBetween returns the distinct account ids whose temporary block lapsed in the
|
||||||
|
// half-open window (since, until]: a non-lifted suspension with a blocked_until in that range. The
|
||||||
|
// chat-access sweeper uses it to re-evaluate chat write access when a temporary block self-expires,
|
||||||
|
// since no operator action fires then. An account that still has another active block may be
|
||||||
|
// included; the eligibility resolver returns the true state, so emitting for it is harmless.
|
||||||
|
func (s *Store) SuspensionsExpiredBetween(ctx context.Context, since, until time.Time) ([]uuid.UUID, error) {
|
||||||
|
rows, err := s.db.QueryContext(ctx,
|
||||||
|
`SELECT DISTINCT account_id FROM backend.account_suspensions
|
||||||
|
WHERE lifted_at IS NULL AND blocked_until > $1 AND blocked_until <= $2`,
|
||||||
|
since.UTC(), until.UTC())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("account: suspensions expired between: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []uuid.UUID
|
||||||
|
for rows.Next() {
|
||||||
|
var id uuid.UUID
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return nil, fmt.Errorf("account: scan expired suspension: %w", err)
|
||||||
|
}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// invalidateSuspension drops the account's cached block so the next CurrentSuspension re-reads it.
|
||||||
|
// Called after Suspend and LiftSuspension.
|
||||||
|
func (s *Store) invalidateSuspension(accountID uuid.UUID) {
|
||||||
|
if s.suspensions != nil {
|
||||||
|
s.suspensions.invalidate(accountID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// suspensionActiveAt reports whether a suspension is in force at now: permanent, or not yet
|
||||||
|
// expired. The lifted check is implicit — only non-lifted blocks are ever cached or returned.
|
||||||
|
func suspensionActiveAt(susp Suspension, now time.Time) bool {
|
||||||
|
return susp.BlockedUntil == nil || susp.BlockedUntil.After(now)
|
||||||
|
}
|
||||||
|
|
||||||
|
// suspensionCache is the gate's write-through cache of each account's current block, keyed by
|
||||||
|
// account id. The suspension gate reads it on every authenticated request; Suspend and
|
||||||
|
// LiftSuspension invalidate the account's entry. An entry holds the strongest active block at
|
||||||
|
// query time (or a not-blocked marker), re-evaluated against the wall clock on read, so a
|
||||||
|
// temporary block lapses without an explicit invalidation. It is single-instance, matching the
|
||||||
|
// deployment (one shared Store); a multi-instance deployment would need a shared cache.
|
||||||
|
type suspensionCache struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
m map[uuid.UUID]suspensionCacheEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
// suspensionCacheEntry is a cached lookup: the strongest active block when found, else a
|
||||||
|
// not-blocked marker (found=false).
|
||||||
|
type suspensionCacheEntry struct {
|
||||||
|
susp Suspension
|
||||||
|
found bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSuspensionCache() *suspensionCache {
|
||||||
|
return &suspensionCache{m: make(map[uuid.UUID]suspensionCacheEntry)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *suspensionCache) get(id uuid.UUID) (suspensionCacheEntry, bool) {
|
||||||
|
c.mu.RLock()
|
||||||
|
defer c.mu.RUnlock()
|
||||||
|
e, ok := c.m[id]
|
||||||
|
return e, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *suspensionCache) put(id uuid.UUID, e suspensionCacheEntry) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.m[id] = e
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *suspensionCache) invalidate(id uuid.UUID) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
delete(c.m, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// activeSuspensionPredicate matches the rows of a block that is in force at now: not lifted and
|
||||||
|
// either permanent or not yet expired.
|
||||||
|
func activeSuspensionPredicate(now time.Time) postgres.BoolExpression {
|
||||||
|
return table.AccountSuspensions.LiftedAt.IS_NULL().
|
||||||
|
AND(
|
||||||
|
table.AccountSuspensions.BlockedUntil.IS_NULL().
|
||||||
|
OR(table.AccountSuspensions.BlockedUntil.GT(postgres.TimestampzT(now))),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListReasons returns the suspension-reason picklist, oldest first.
|
||||||
|
func (s *Store) ListReasons(ctx context.Context) ([]Reason, error) {
|
||||||
|
stmt := postgres.SELECT(table.SuspensionReasons.AllColumns).
|
||||||
|
FROM(table.SuspensionReasons).
|
||||||
|
ORDER_BY(table.SuspensionReasons.CreatedAt.ASC())
|
||||||
|
var rows []model.SuspensionReasons
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return nil, fmt.Errorf("account: list reasons: %w", err)
|
||||||
|
}
|
||||||
|
out := make([]Reason, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out = append(out, modelToReason(r))
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReason loads one picklist entry, or ErrNotFound when it is absent.
|
||||||
|
func (s *Store) GetReason(ctx context.Context, id uuid.UUID) (Reason, error) {
|
||||||
|
stmt := postgres.SELECT(table.SuspensionReasons.AllColumns).
|
||||||
|
FROM(table.SuspensionReasons).
|
||||||
|
WHERE(table.SuspensionReasons.ReasonID.EQ(postgres.UUID(id))).
|
||||||
|
LIMIT(1)
|
||||||
|
var row model.SuspensionReasons
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return Reason{}, ErrNotFound
|
||||||
|
}
|
||||||
|
return Reason{}, fmt.Errorf("account: get reason %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return modelToReason(row), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateReason inserts a new picklist entry with the given English and Russian text.
|
||||||
|
func (s *Store) CreateReason(ctx context.Context, textEn, textRu string) (Reason, error) {
|
||||||
|
id, err := uuid.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
return Reason{}, fmt.Errorf("account: new reason id: %w", err)
|
||||||
|
}
|
||||||
|
stmt := table.SuspensionReasons.INSERT(
|
||||||
|
table.SuspensionReasons.ReasonID,
|
||||||
|
table.SuspensionReasons.TextEn,
|
||||||
|
table.SuspensionReasons.TextRu,
|
||||||
|
).VALUES(id, textEn, textRu).
|
||||||
|
RETURNING(table.SuspensionReasons.AllColumns)
|
||||||
|
var row model.SuspensionReasons
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
return Reason{}, fmt.Errorf("account: create reason: %w", err)
|
||||||
|
}
|
||||||
|
return modelToReason(row), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateReason rewrites a picklist entry's English and Russian text, returning ErrNotFound when
|
||||||
|
// it is absent. Existing suspensions keep their text snapshot, so the change only affects future
|
||||||
|
// blocks.
|
||||||
|
func (s *Store) UpdateReason(ctx context.Context, id uuid.UUID, textEn, textRu string) (Reason, error) {
|
||||||
|
stmt := table.SuspensionReasons.
|
||||||
|
UPDATE(table.SuspensionReasons.TextEn, table.SuspensionReasons.TextRu, table.SuspensionReasons.UpdatedAt).
|
||||||
|
SET(postgres.String(textEn), postgres.String(textRu), postgres.TimestampzT(time.Now().UTC())).
|
||||||
|
WHERE(table.SuspensionReasons.ReasonID.EQ(postgres.UUID(id))).
|
||||||
|
RETURNING(table.SuspensionReasons.AllColumns)
|
||||||
|
var row model.SuspensionReasons
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return Reason{}, ErrNotFound
|
||||||
|
}
|
||||||
|
return Reason{}, fmt.Errorf("account: update reason %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return modelToReason(row), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteReason removes a picklist entry. It is a hard delete: the reason_id link on past
|
||||||
|
// suspensions is nulled by the foreign key, but their text snapshot is untouched.
|
||||||
|
func (s *Store) DeleteReason(ctx context.Context, id uuid.UUID) error {
|
||||||
|
stmt := table.SuspensionReasons.
|
||||||
|
DELETE().
|
||||||
|
WHERE(table.SuspensionReasons.ReasonID.EQ(postgres.UUID(id)))
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return fmt.Errorf("account: delete reason %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// modelToSuspension projects a generated row into the public Suspension struct.
|
||||||
|
func modelToSuspension(row model.AccountSuspensions) Suspension {
|
||||||
|
s := Suspension{AccountID: row.AccountID, BlockedAt: row.BlockedAt, BlockedUntil: row.BlockedUntil}
|
||||||
|
if row.ReasonEn != nil {
|
||||||
|
s.ReasonEn = *row.ReasonEn
|
||||||
|
}
|
||||||
|
if row.ReasonRu != nil {
|
||||||
|
s.ReasonRu = *row.ReasonRu
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// modelToReason projects a generated row into the public Reason struct.
|
||||||
|
func modelToReason(row model.SuspensionReasons) Reason {
|
||||||
|
return Reason{ID: row.ReasonID, TextEn: row.TextEn, TextRu: row.TextRu, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt}
|
||||||
|
}
|
||||||
|
|
||||||
|
// nullableString renders an empty string as SQL NULL, otherwise the string literal.
|
||||||
|
func nullableString(v string) postgres.Expression {
|
||||||
|
if v == "" {
|
||||||
|
return postgres.NULL
|
||||||
|
}
|
||||||
|
return postgres.String(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// nullableTimestamp renders a nil time as SQL NULL, otherwise the UTC timestamp literal.
|
||||||
|
func nullableTimestamp(v *time.Time) postgres.Expression {
|
||||||
|
if v == nil {
|
||||||
|
return postgres.NULL
|
||||||
|
}
|
||||||
|
return postgres.TimestampzT(v.UTC())
|
||||||
|
}
|
||||||
|
|
||||||
|
// nullableUUID renders a nil id as SQL NULL, otherwise the uuid literal.
|
||||||
|
func nullableUUID(v *uuid.UUID) postgres.Expression {
|
||||||
|
if v == nil {
|
||||||
|
return postgres.NULL
|
||||||
|
}
|
||||||
|
return postgres.UUID(*v)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSuspensionActiveAt covers the wall-clock re-evaluation the cache relies on: a permanent
|
||||||
|
// block is always active, a future-dated one is active, a past-dated one is not.
|
||||||
|
func TestSuspensionActiveAt(t *testing.T) {
|
||||||
|
now := time.Date(2026, 6, 14, 12, 0, 0, 0, time.UTC)
|
||||||
|
future := now.Add(time.Hour)
|
||||||
|
past := now.Add(-time.Hour)
|
||||||
|
|
||||||
|
if !suspensionActiveAt(Suspension{BlockedUntil: nil}, now) {
|
||||||
|
t.Error("a permanent block must be active")
|
||||||
|
}
|
||||||
|
if !suspensionActiveAt(Suspension{BlockedUntil: &future}, now) {
|
||||||
|
t.Error("a future-dated block must be active")
|
||||||
|
}
|
||||||
|
if suspensionActiveAt(Suspension{BlockedUntil: &past}, now) {
|
||||||
|
t.Error("a past-dated block must be inactive")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionCache covers the cache primitives: a miss on an empty cache, a hit after put for
|
||||||
|
// both the not-blocked and blocked markers, and a miss after invalidate.
|
||||||
|
func TestSuspensionCache(t *testing.T) {
|
||||||
|
c := newSuspensionCache()
|
||||||
|
id := uuid.New()
|
||||||
|
|
||||||
|
if _, ok := c.get(id); ok {
|
||||||
|
t.Fatal("empty cache must miss")
|
||||||
|
}
|
||||||
|
|
||||||
|
c.put(id, suspensionCacheEntry{found: false})
|
||||||
|
if e, ok := c.get(id); !ok || e.found {
|
||||||
|
t.Fatalf("cached not-blocked entry = (%+v, ok %v), want hit with found=false", e, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.put(id, suspensionCacheEntry{susp: Suspension{AccountID: id}, found: true})
|
||||||
|
if e, ok := c.get(id); !ok || !e.found {
|
||||||
|
t.Fatalf("cached blocked entry = (%+v, ok %v), want hit with found=true", e, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.invalidate(id)
|
||||||
|
if _, ok := c.get(id); ok {
|
||||||
|
t.Fatal("invalidated entry must miss")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
// suspensionSweepInterval is how often the sweeper re-checks for temporary blocks
|
||||||
|
// that lapsed. A minute is well under the coarsest block grain (operators pick day
|
||||||
|
// presets) while keeping the query trivial.
|
||||||
|
const suspensionSweepInterval = time.Minute
|
||||||
|
|
||||||
|
// suspensionExpiryQuerier is the slice of the account store the sweeper depends on:
|
||||||
|
// the accounts whose temporary block lapsed in a window. *Store satisfies it; a fake
|
||||||
|
// drives the sweeper's unit tests.
|
||||||
|
type suspensionExpiryQuerier interface {
|
||||||
|
SuspensionsExpiredBetween(ctx context.Context, since, until time.Time) ([]uuid.UUID, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuspensionSweeper re-evaluates chat write access when a temporary block self-
|
||||||
|
// expires. No operator action fires on expiry — the suspension gate just re-reads
|
||||||
|
// the wall clock — so without this a temporarily blocked player would stay muted in
|
||||||
|
// the moderated discussion chat after their block lapsed. Each tick it finds blocks
|
||||||
|
// that expired since the previous tick and calls onExpire for the affected accounts;
|
||||||
|
// onExpire is wired to publish the chat-access-changed event, after which the gateway
|
||||||
|
// re-resolves the true eligibility. A liberal call (an account that still has another
|
||||||
|
// active block) is therefore harmless. The window is in-memory, so a block that
|
||||||
|
// expires while the process is down is not re-granted until the next operator action
|
||||||
|
// or the player rejoins — an accepted best-effort gap.
|
||||||
|
type SuspensionSweeper struct {
|
||||||
|
store suspensionExpiryQuerier
|
||||||
|
onExpire func(accountID uuid.UUID)
|
||||||
|
log *zap.Logger
|
||||||
|
// since is the upper bound of the previous swept window; the next sweep covers
|
||||||
|
// (since, now]. It advances only on a successful query, so a failed tick retries
|
||||||
|
// the same window rather than dropping expiries.
|
||||||
|
since time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSuspensionSweeper builds the sweeper over the account store, the per-account
|
||||||
|
// expiry callback (publishing the chat-access-changed event) and a logger. The first
|
||||||
|
// window opens at construction time, so blocks that lapsed earlier are not re-emitted.
|
||||||
|
func NewSuspensionSweeper(store *Store, onExpire func(accountID uuid.UUID), log *zap.Logger) *SuspensionSweeper {
|
||||||
|
if log == nil {
|
||||||
|
log = zap.NewNop()
|
||||||
|
}
|
||||||
|
return &SuspensionSweeper{store: store, onExpire: onExpire, log: log, since: time.Now().UTC()}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interval reports the sweep cadence, for the startup log line.
|
||||||
|
func (w *SuspensionSweeper) Interval() time.Duration { return suspensionSweepInterval }
|
||||||
|
|
||||||
|
// Run sweeps every Interval until ctx is cancelled.
|
||||||
|
func (w *SuspensionSweeper) Run(ctx context.Context) {
|
||||||
|
ticker := time.NewTicker(suspensionSweepInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
w.sweep(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sweep emits a chat-access-changed signal for every account whose temporary block
|
||||||
|
// lapsed in (since, now], then advances the window. On a query error it keeps the
|
||||||
|
// window so the next tick retries it.
|
||||||
|
func (w *SuspensionSweeper) sweep(ctx context.Context) {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
ids, err := w.store.SuspensionsExpiredBetween(ctx, w.since, now)
|
||||||
|
if err != nil {
|
||||||
|
w.log.Warn("suspension expiry sweep failed", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.since = now
|
||||||
|
for _, id := range ids {
|
||||||
|
w.onExpire(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package account
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeExpiryQuerier records the `since` bound of each call and replays a scripted
|
||||||
|
// result/error per call, so the sweeper's window and dispatch logic is testable
|
||||||
|
// without a database.
|
||||||
|
type fakeExpiryQuerier struct {
|
||||||
|
results [][]uuid.UUID
|
||||||
|
errs []error
|
||||||
|
sinces []time.Time
|
||||||
|
idx int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeExpiryQuerier) SuspensionsExpiredBetween(_ context.Context, since, _ time.Time) ([]uuid.UUID, error) {
|
||||||
|
f.sinces = append(f.sinces, since)
|
||||||
|
i := f.idx
|
||||||
|
f.idx++
|
||||||
|
if i < len(f.errs) && f.errs[i] != nil {
|
||||||
|
return nil, f.errs[i]
|
||||||
|
}
|
||||||
|
if i < len(f.results) {
|
||||||
|
return f.results[i], nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSweeper(store suspensionExpiryQuerier, onExpire func(uuid.UUID)) *SuspensionSweeper {
|
||||||
|
return &SuspensionSweeper{
|
||||||
|
store: store,
|
||||||
|
onExpire: onExpire,
|
||||||
|
log: zap.NewNop(),
|
||||||
|
since: time.Now().Add(-time.Minute).UTC(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSuspensionSweeperDispatchesAndAdvances(t *testing.T) {
|
||||||
|
id1, id2 := uuid.New(), uuid.New()
|
||||||
|
fake := &fakeExpiryQuerier{results: [][]uuid.UUID{{id1, id2}, nil}}
|
||||||
|
var got []uuid.UUID
|
||||||
|
w := newSweeper(fake, func(id uuid.UUID) { got = append(got, id) })
|
||||||
|
|
||||||
|
first := w.since
|
||||||
|
w.sweep(context.Background())
|
||||||
|
assert.Equal(t, []uuid.UUID{id1, id2}, got, "every expired account is dispatched")
|
||||||
|
assert.True(t, w.since.After(first), "the window advances on success")
|
||||||
|
|
||||||
|
// A second sweep opens the next window at the previous upper bound.
|
||||||
|
prev := w.since
|
||||||
|
w.sweep(context.Background())
|
||||||
|
require.Len(t, fake.sinces, 2)
|
||||||
|
assert.True(t, fake.sinces[1].After(fake.sinces[0]), "consecutive windows are contiguous and forward")
|
||||||
|
assert.True(t, fake.sinces[1].Equal(prev), "the next window starts at the previous upper bound")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSuspensionSweeperKeepsWindowOnError(t *testing.T) {
|
||||||
|
fake := &fakeExpiryQuerier{errs: []error{errors.New("db down")}}
|
||||||
|
w := newSweeper(fake, func(uuid.UUID) { t.Fatal("onExpire must not run when the query fails") })
|
||||||
|
|
||||||
|
before := w.since
|
||||||
|
w.sweep(context.Background())
|
||||||
|
assert.True(t, w.since.Equal(before), "the window is retained on error so the next tick retries it")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewSuspensionSweeperDefaults(t *testing.T) {
|
||||||
|
w := NewSuspensionSweeper(nil, func(uuid.UUID) {}, nil)
|
||||||
|
assert.Equal(t, time.Minute, w.Interval())
|
||||||
|
assert.NotNil(t, w.log, "a nil logger is tolerated")
|
||||||
|
assert.WithinDuration(t, time.Now().UTC(), w.since, time.Second, "the first window opens at construction time")
|
||||||
|
}
|
||||||
@@ -24,7 +24,16 @@ func TestValidateDisplayName(t *testing.T) {
|
|||||||
"trailing underscore": {"Name_", "", false},
|
"trailing underscore": {"Name_", "", false},
|
||||||
"trailing dot ok": {"Anna B.", "Anna B.", true},
|
"trailing dot ok": {"Anna B.", "Anna B.", true},
|
||||||
"double trailing dot": {"Name..", "", false},
|
"double trailing dot": {"Name..", "", false},
|
||||||
"digit rejected": {"Name2", "", false},
|
"trailing digit ok": {"Name2", "Name2", true},
|
||||||
|
"trailing year ok": {"Аня2007", "Аня2007", true},
|
||||||
|
"five digits ok": {"Player12345", "Player12345", true},
|
||||||
|
"six digits rejected": {"Player123456", "", false},
|
||||||
|
"mid digit rejected": {"Dark2Wolf", "", false},
|
||||||
|
"all digits rejected": {"12345", "", false},
|
||||||
|
"digit then dot": {"Name2.", "", false},
|
||||||
|
"dot then digit": {"Anna B.2", "", false},
|
||||||
|
"sep plus digits ok": {"Night.Fox2007", "Night.Fox2007", true}, // "." is the only special; digits do not count
|
||||||
|
"max specials+digits": {"a.a.a.a.a.a2007", "a.a.a.a.a.a2007", true}, // 5 dots + a digit run still passes
|
||||||
"blank": {" ", "", false},
|
"blank": {" ", "", false},
|
||||||
"too long": {strings.Repeat("a", 33), "", false},
|
"too long": {strings.Repeat("a", 33), "", false},
|
||||||
"five specials ok": {"a.a.a.a.a.a", "a.a.a.a.a.a", true}, // 5 dots
|
"five specials ok": {"a.a.a.a.a.a", "a.a.a.a.a.a", true}, // 5 dots
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
// Package accountmerge retires a secondary account into a primary one in a single
|
// Package accountmerge retires a secondary account into a primary one in a single
|
||||||
// transaction: it sums statistics and the hint wallet, ORs the paid flag, repoints
|
// transaction: it sums statistics (merging the per-variant best moves), sums the hint
|
||||||
|
// wallet, ORs the paid flag, repoints
|
||||||
// the secondary's identities, transfers its games/chat/complaints/invitations,
|
// the secondary's identities, transfers its games/chat/complaints/invitations,
|
||||||
// de-duplicates friends and blocks, and leaves the secondary as an audit tombstone
|
// de-duplicates friends and blocks, and leaves the secondary as an audit tombstone
|
||||||
// (accounts.merged_into). It is the data core of account linking & merge
|
// (accounts.merged_into). It is the data core of account linking & merge
|
||||||
@@ -68,6 +69,9 @@ func (m *Merger) Merge(ctx context.Context, primary, secondary uuid.UUID) error
|
|||||||
if err := mergeStats(ctx, tx, primary, secondary, now); err != nil {
|
if err := mergeStats(ctx, tx, primary, secondary, now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := mergeBestMoves(ctx, tx, primary, secondary, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := mergeAccountFields(ctx, tx, primary, secondary, now); err != nil {
|
if err := mergeAccountFields(ctx, tx, primary, secondary, now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -147,8 +151,8 @@ func activeGameIDs(ctx context.Context, tx *sql.Tx, accountID uuid.UUID) ([]uuid
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// mergeStats folds secondary's lifetime statistics into primary (wins/losses/draws
|
// mergeStats folds secondary's lifetime statistics into primary (wins/losses/draws and
|
||||||
// summed, max points kept) and deletes the secondary row.
|
// the moves/hints-used counters summed, max points kept) and deletes the secondary row.
|
||||||
func mergeStats(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
func mergeStats(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
||||||
var sec model.AccountStats
|
var sec model.AccountStats
|
||||||
err := postgres.SELECT(table.AccountStats.AllColumns).
|
err := postgres.SELECT(table.AccountStats.AllColumns).
|
||||||
@@ -178,13 +182,16 @@ func mergeStats(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, n
|
|||||||
|
|
||||||
upd := table.AccountStats.UPDATE(
|
upd := table.AccountStats.UPDATE(
|
||||||
table.AccountStats.Wins, table.AccountStats.Losses, table.AccountStats.Draws,
|
table.AccountStats.Wins, table.AccountStats.Losses, table.AccountStats.Draws,
|
||||||
table.AccountStats.MaxGamePoints, table.AccountStats.MaxWordPoints, table.AccountStats.UpdatedAt,
|
table.AccountStats.MaxGamePoints, table.AccountStats.MaxWordPoints,
|
||||||
|
table.AccountStats.Moves, table.AccountStats.HintsUsed, table.AccountStats.UpdatedAt,
|
||||||
).SET(
|
).SET(
|
||||||
postgres.Int(int64(pri.Wins+sec.Wins)),
|
postgres.Int(int64(pri.Wins+sec.Wins)),
|
||||||
postgres.Int(int64(pri.Losses+sec.Losses)),
|
postgres.Int(int64(pri.Losses+sec.Losses)),
|
||||||
postgres.Int(int64(pri.Draws+sec.Draws)),
|
postgres.Int(int64(pri.Draws+sec.Draws)),
|
||||||
postgres.Int(int64(max(pri.MaxGamePoints, sec.MaxGamePoints))),
|
postgres.Int(int64(max(pri.MaxGamePoints, sec.MaxGamePoints))),
|
||||||
postgres.Int(int64(max(pri.MaxWordPoints, sec.MaxWordPoints))),
|
postgres.Int(int64(max(pri.MaxWordPoints, sec.MaxWordPoints))),
|
||||||
|
postgres.Int(int64(pri.Moves+sec.Moves)),
|
||||||
|
postgres.Int(int64(pri.HintsUsed+sec.HintsUsed)),
|
||||||
postgres.TimestampzT(now),
|
postgres.TimestampzT(now),
|
||||||
).WHERE(table.AccountStats.AccountID.EQ(postgres.UUID(primary)))
|
).WHERE(table.AccountStats.AccountID.EQ(postgres.UUID(primary)))
|
||||||
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
||||||
@@ -198,6 +205,41 @@ func mergeStats(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, n
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mergeBestMoves folds secondary's per-variant best moves into primary, keeping the
|
||||||
|
// higher-scoring play per variant (the same rule the per-game upsert uses), then deletes
|
||||||
|
// the secondary's rows — the secondary is only tombstoned, not removed, so without this
|
||||||
|
// they would linger on a dead account and never reach the merged statistics screen.
|
||||||
|
func mergeBestMoves(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
||||||
|
var srows []model.AccountBestMove
|
||||||
|
err := postgres.SELECT(table.AccountBestMove.AllColumns).
|
||||||
|
FROM(table.AccountBestMove).
|
||||||
|
WHERE(table.AccountBestMove.AccountID.EQ(postgres.UUID(secondary))).
|
||||||
|
QueryContext(ctx, tx, &srows)
|
||||||
|
if err != nil && !errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return fmt.Errorf("accountmerge: load secondary best moves: %w", err)
|
||||||
|
}
|
||||||
|
for _, s := range srows {
|
||||||
|
ins := table.AccountBestMove.
|
||||||
|
INSERT(table.AccountBestMove.AccountID, table.AccountBestMove.Variant,
|
||||||
|
table.AccountBestMove.Score, table.AccountBestMove.Tiles, table.AccountBestMove.UpdatedAt).
|
||||||
|
VALUES(primary, s.Variant, s.Score, s.Tiles, postgres.TimestampzT(now)).
|
||||||
|
ON_CONFLICT(table.AccountBestMove.AccountID, table.AccountBestMove.Variant).
|
||||||
|
DO_UPDATE(postgres.SET(
|
||||||
|
table.AccountBestMove.Score.SET(table.AccountBestMove.EXCLUDED.Score),
|
||||||
|
table.AccountBestMove.Tiles.SET(table.AccountBestMove.EXCLUDED.Tiles),
|
||||||
|
table.AccountBestMove.UpdatedAt.SET(table.AccountBestMove.EXCLUDED.UpdatedAt),
|
||||||
|
).WHERE(table.AccountBestMove.EXCLUDED.Score.GT(table.AccountBestMove.Score)))
|
||||||
|
if _, err := ins.ExecContext(ctx, tx); err != nil {
|
||||||
|
return fmt.Errorf("accountmerge: merge best move %s: %w", s.Variant, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
del := table.AccountBestMove.DELETE().WHERE(table.AccountBestMove.AccountID.EQ(postgres.UUID(secondary)))
|
||||||
|
if _, err := del.ExecContext(ctx, tx); err != nil {
|
||||||
|
return fmt.Errorf("accountmerge: delete secondary best moves: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// mergeAccountFields adds secondary's hint wallet to primary and ORs the paid flag;
|
// mergeAccountFields adds secondary's hint wallet to primary and ORs the paid flag;
|
||||||
// all other profile fields stay the primary's.
|
// all other profile fields stay the primary's.
|
||||||
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
func mergeAccountFields(ctx context.Context, tx *sql.Tx, primary, secondary uuid.UUID, now time.Time) error {
|
||||||
|
|||||||
@@ -86,6 +86,22 @@ h1 { font-size: 1.4rem; margin: 0 0 0.4rem; }
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
}
|
}
|
||||||
.form textarea { min-height: 4rem; resize: vertical; }
|
.form textarea { min-height: 4rem; resize: vertical; }
|
||||||
|
/* A static help aside (e.g. message-formatting hints) beside an intro note at the top of a
|
||||||
|
section: the note fills the row, the aside takes ~40% and both wrap on a narrow viewport. */
|
||||||
|
.help-top { display: flex; flex-wrap: wrap; gap: 1rem; align-items: flex-start; margin: 0.2rem 0 0.6rem; }
|
||||||
|
.help-top .note { flex: 1 1 16rem; margin: 0; }
|
||||||
|
.help {
|
||||||
|
flex: 0 1 40%;
|
||||||
|
min-width: 16rem;
|
||||||
|
background: var(--panel-hi);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.5rem 0.8rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--ink-dim);
|
||||||
|
}
|
||||||
|
.help h4 { margin: 0 0 0.4rem; font-size: 0.85rem; color: var(--ink); }
|
||||||
|
.help p { margin: 0.35rem 0; }
|
||||||
button {
|
button {
|
||||||
background: var(--accent);
|
background: var(--accent);
|
||||||
color: #06121f;
|
color: #06121f;
|
||||||
@@ -116,3 +132,64 @@ code { background: var(--bg); padding: 0.05rem 0.3rem; border-radius: 4px; }
|
|||||||
.lg-min { color: var(--ok); }
|
.lg-min { color: var(--ok); }
|
||||||
.lg-avg { color: var(--accent); }
|
.lg-avg { color: var(--accent); }
|
||||||
.lg-max { color: var(--danger); }
|
.lg-max { color: var(--danger); }
|
||||||
|
|
||||||
|
/* Feedback: user-controlled message bodies are wrapped and escaped (never HTML);
|
||||||
|
an image attachment is previewed inline, bounded so it cannot dominate the page. */
|
||||||
|
.msgbody { white-space: pre-wrap; word-break: break-word; background: var(--bg); padding: 0.6rem 0.8rem; border-radius: 6px; margin: 0.6rem 0; }
|
||||||
|
.attach { max-width: 100%; max-height: 480px; height: auto; border: 1px solid var(--line); border-radius: 6px; }
|
||||||
|
|
||||||
|
/* Game replay (admin): a script-stepped board with rack panels around it, a move log and the
|
||||||
|
first-move draw. A placed tile shows its value as a subscript; a 0 value (a blank) shows none. */
|
||||||
|
.replay-stage {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||||
|
grid-template-areas: ". top ." "left board right" ". bottom .";
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-items: center;
|
||||||
|
margin-bottom: 0.6rem;
|
||||||
|
}
|
||||||
|
.rack-top { grid-area: top; }
|
||||||
|
.rack-bottom { grid-area: bottom; }
|
||||||
|
.rack-left { grid-area: left; }
|
||||||
|
.rack-right { grid-area: right; }
|
||||||
|
.replay-board { grid-area: board; overflow: auto; }
|
||||||
|
.board-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1.4rem repeat(15, 1.7rem);
|
||||||
|
grid-auto-rows: 1.7rem;
|
||||||
|
gap: 1px;
|
||||||
|
background: var(--line);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
width: max-content;
|
||||||
|
}
|
||||||
|
.board-grid .bh { display: flex; align-items: center; justify-content: center; font-size: 0.6rem; color: var(--ink-dim); background: var(--panel); }
|
||||||
|
.board-grid .cell { position: relative; display: flex; align-items: center; justify-content: center; background: var(--panel-hi); }
|
||||||
|
.cell .prem { font-size: 0.55rem; color: var(--ink); opacity: 0.8; }
|
||||||
|
.cell.tw { background: #7a2230; }
|
||||||
|
.cell.dw { background: #a8506a; }
|
||||||
|
.cell.tl { background: #235a7a; }
|
||||||
|
.cell.dl { background: #3f87a8; }
|
||||||
|
.cell.centre .prem { font-size: 0.95rem; color: var(--warn); opacity: 1; }
|
||||||
|
.tile {
|
||||||
|
display: inline-flex; align-items: baseline; justify-content: center;
|
||||||
|
min-width: 1.35rem; height: 1.35rem; padding: 0 0.12rem;
|
||||||
|
background: #e8d9a0; color: #1b1408; border-radius: 3px;
|
||||||
|
font-weight: 700; font-size: 0.8rem; line-height: 1.35rem;
|
||||||
|
}
|
||||||
|
.tile sub { font-size: 0.5rem; font-weight: 600; line-height: 1; align-self: flex-end; margin-left: 1px; }
|
||||||
|
.tile.blank { background: #cdbfe0; }
|
||||||
|
.cell.filled { background: var(--panel-hi); }
|
||||||
|
.cell.filled .tile { width: 100%; height: 100%; border-radius: 2px; }
|
||||||
|
.rack-slot { padding: 0.25rem; border-radius: 6px; }
|
||||||
|
.rack-slot.active { outline: 2px solid var(--accent); background: var(--panel-hi); }
|
||||||
|
.rack-name { font-size: 0.72rem; color: var(--ink-dim); margin-bottom: 0.2rem; text-align: center; }
|
||||||
|
.rack-tiles { display: flex; gap: 2px; flex-wrap: wrap; justify-content: center; }
|
||||||
|
.rack-left .rack-tiles, .rack-right .rack-tiles { flex-direction: column; }
|
||||||
|
.replay-controls { display: flex; align-items: center; gap: 0.8rem; justify-content: center; margin: 0.6rem 0; }
|
||||||
|
.replay-controls button { background: var(--panel-hi); color: var(--ink); border: 1px solid var(--line); font-weight: 600; }
|
||||||
|
.replay-controls button:disabled { opacity: 0.4; cursor: default; }
|
||||||
|
.replay-pos { color: var(--ink-dim); font-variant-numeric: tabular-nums; }
|
||||||
|
.replay-log { margin: 0.4rem 0 0; padding-left: 1.4rem; max-height: 14rem; overflow: auto; font-size: 0.85rem; }
|
||||||
|
.replay-log li { color: var(--ink-dim); padding: 0.1rem 0; }
|
||||||
|
.replay-log li.cur { color: var(--ink); font-weight: 600; }
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ func TestRendererRendersEveryPage(t *testing.T) {
|
|||||||
{"users", UsersView{Items: []UserRow{{ID: "a1", DisplayName: "Kaya", FlaggedHighRate: true}}, Pager: NewPager(1, 50, 1)}, "high-rate"},
|
{"users", UsersView{Items: []UserRow{{ID: "a1", DisplayName: "Kaya", FlaggedHighRate: true}}, Pager: NewPager(1, 50, 1)}, "high-rate"},
|
||||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", HasStats: true, Stats: StatsRow{Wins: 2}, TelegramID: "123", ConnectorEnabled: true}, "Send Telegram message"},
|
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", HasStats: true, Stats: StatsRow{Wins: 2}, TelegramID: "123", ConnectorEnabled: true}, "Send Telegram message"},
|
||||||
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", FlaggedHighRateAt: "2026-06-10 12:00"}, "Clear high-rate flag"},
|
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", FlaggedHighRateAt: "2026-06-10 12:00"}, "Clear high-rate flag"},
|
||||||
|
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya", Roles: []string{"feedback_banned"}, KnownRoles: []string{"feedback_banned"}}, "feedback_banned"},
|
||||||
|
{"user_detail", UserDetailView{ID: "a1", DisplayName: "Kaya",
|
||||||
|
Friends: []RelationRow{{AccountID: "b2", DisplayName: "Ann", Date: "2026-06-10 12:00"}},
|
||||||
|
Blocks: []RelationRow{{AccountID: "c3", DisplayName: "Bob", Date: "2026-06-11 09:00"}},
|
||||||
|
BlockedBy: []RelationRow{{AccountID: "d4", DisplayName: "Cay", Date: "2026-06-12 08:00"}},
|
||||||
|
}, `/_gm/users/c3`},
|
||||||
{"throttled", ThrottledView{
|
{"throttled", ThrottledView{
|
||||||
Episodes: []ThrottleEpisodeRow{{Class: "user", Key: "a1", UserID: "a1", Rejected: 1234, FirstSeen: "2026-06-10 12:00", LastSeen: "2026-06-10 12:05"}},
|
Episodes: []ThrottleEpisodeRow{{Class: "user", Key: "a1", UserID: "a1", Rejected: 1234, FirstSeen: "2026-06-10 12:00", LastSeen: "2026-06-10 12:05"}},
|
||||||
Flagged: []FlaggedAccountRow{{ID: "a1", DisplayName: "Kaya", FlaggedAt: "2026-06-10 12:05"}},
|
Flagged: []FlaggedAccountRow{{ID: "a1", DisplayName: "Kaya", FlaggedAt: "2026-06-10 12:05"}},
|
||||||
@@ -34,7 +40,10 @@ func TestRendererRendersEveryPage(t *testing.T) {
|
|||||||
{"games", GamesView{Items: []GameRow{{ID: "g-open", Variant: "scrabble_en", Status: "open"}}, Status: "open", Pager: NewPager(1, 50, 1)}, "?status=open"},
|
{"games", GamesView{Items: []GameRow{{ID: "g-open", Variant: "scrabble_en", Status: "open"}}, Status: "open", Pager: NewPager(1, 50, 1)}, "?status=open"},
|
||||||
{"game_detail", GameDetailView{ID: "g1", Variant: "scrabble_en", Seats: []SeatRow{{Seat: 0, DisplayName: "Kaya"}}}, "Seats"},
|
{"game_detail", GameDetailView{ID: "g1", Variant: "scrabble_en", Seats: []SeatRow{{Seat: 0, DisplayName: "Kaya"}}}, "Seats"},
|
||||||
{"complaints", ComplaintsView{Items: []ComplaintRow{{ID: "c1", Word: "qi", Status: "open"}}, Status: "open", Pager: NewPager(1, 50, 1)}, "qi"},
|
{"complaints", ComplaintsView{Items: []ComplaintRow{{ID: "c1", Word: "qi", Status: "open"}}, Status: "open", Pager: NewPager(1, 50, 1)}, "qi"},
|
||||||
{"messages", MessagesView{Items: []MessageRow{{ID: "m1", SenderID: "a1", SenderName: "Kaya", Source: "telegram", Body: "good luck", GameID: "g1"}}, Pager: NewPager(1, 50, 1)}, "good luck"},
|
{"messages", MessagesView{Items: []MessageRow{{ID: "m1", SenderID: "a1", SenderName: "Kaya", Source: "telegram", Body: "good luck", GameID: "g1", Unread: true}}, UnreadOnly: true, Pager: NewPager(1, 50, 1)}, "unread only"},
|
||||||
|
{"chatmessage", ChatMessageDetailView{ID: "m1", GameID: "g1", SenderID: "a1", SenderName: "Kaya", Source: "telegram", Kind: "message", Body: "good luck", Unread: true, Seats: []ChatSeatStatusRow{{Seat: 0, AccountID: "a1", DisplayName: "Kaya", Role: "sender"}, {Seat: 1, AccountID: "b2", DisplayName: "Opp", Role: "unread"}}}, "Read by seat"},
|
||||||
|
{"feedback", FeedbackView{Items: []FeedbackRow{{ID: "f1", AccountID: "a1", SenderName: "Kaya", Source: "telegram", Channel: "web", HasAttachment: true, Replied: true}}, Status: "unread", Pager: NewPager(1, 50, 1)}, "replied"},
|
||||||
|
{"feedback_detail", FeedbackDetailView{ID: "f1", AccountID: "a1", SenderName: "Kaya", Channel: "telegram", InterfaceLanguage: "en", Body: "please fix the board", HasAttachment: true, AttachmentName: "shot.png", IsImage: true, Banned: true}, "Interface language"},
|
||||||
{"complaint_detail", ComplaintDetailView{ID: "c1", Word: "qi", Variant: "scrabble_en"}, "Resolve"},
|
{"complaint_detail", ComplaintDetailView{ID: "c1", Word: "qi", Variant: "scrabble_en"}, "Resolve"},
|
||||||
{"dictionary", DictionaryView{ActiveVersion: "v1.0.0", Variants: []VariantVersions{{Variant: "scrabble_en", Versions: []string{"v1.0.0"}}}, Changes: []DictChangeRow{{Variant: "scrabble_en", Word: "qi", Action: "add"}}}, "Update dictionaries"},
|
{"dictionary", DictionaryView{ActiveVersion: "v1.0.0", Variants: []VariantVersions{{Variant: "scrabble_en", Versions: []string{"v1.0.0"}}}, Changes: []DictChangeRow{{Variant: "scrabble_en", Word: "qi", Action: "add"}}}, "Update dictionaries"},
|
||||||
{"dictionary_preview", DictionaryPreviewView{Version: "v1.1.0", Token: "0123456789abcdef0123456789abcdef", ActiveVersion: "v1.0.0", Variants: []VariantDiffRow{{Variant: "scrabble_en", AddedCount: 2, RemovedCount: 1, AddedSample: []string{"qi", "za"}, RemovedSample: []string{"xqz"}, RemovedTruncated: true}}}, "v1.1.0"},
|
{"dictionary_preview", DictionaryPreviewView{Version: "v1.1.0", Token: "0123456789abcdef0123456789abcdef", ActiveVersion: "v1.0.0", Variants: []VariantDiffRow{{Variant: "scrabble_en", AddedCount: 2, RemovedCount: 1, AddedSample: []string{"qi", "za"}, RemovedSample: []string{"xqz"}, RemovedTruncated: true}}}, "v1.1.0"},
|
||||||
|
|||||||
@@ -16,8 +16,11 @@
|
|||||||
<a href="/_gm/users"{{if eq .ActiveNav "users"}} class="active"{{end}}>Users</a>
|
<a href="/_gm/users"{{if eq .ActiveNav "users"}} class="active"{{end}}>Users</a>
|
||||||
<a href="/_gm/games"{{if eq .ActiveNav "games"}} class="active"{{end}}>Games</a>
|
<a href="/_gm/games"{{if eq .ActiveNav "games"}} class="active"{{end}}>Games</a>
|
||||||
<a href="/_gm/complaints"{{if eq .ActiveNav "complaints"}} class="active"{{end}}>Complaints</a>
|
<a href="/_gm/complaints"{{if eq .ActiveNav "complaints"}} class="active"{{end}}>Complaints</a>
|
||||||
|
<a href="/_gm/feedback"{{if eq .ActiveNav "feedback"}} class="active"{{end}}>Feedback</a>
|
||||||
<a href="/_gm/messages"{{if eq .ActiveNav "messages"}} class="active"{{end}}>Messages</a>
|
<a href="/_gm/messages"{{if eq .ActiveNav "messages"}} class="active"{{end}}>Messages</a>
|
||||||
<a href="/_gm/throttled"{{if eq .ActiveNav "throttled"}} class="active"{{end}}>Throttled</a>
|
<a href="/_gm/throttled"{{if eq .ActiveNav "throttled"}} class="active"{{end}}>Throttled</a>
|
||||||
|
<a href="/_gm/reasons"{{if eq .ActiveNav "reasons"}} class="active"{{end}}>Reasons</a>
|
||||||
|
<a href="/_gm/banners"{{if eq .ActiveNav "banners"}} class="active"{{end}}>Banners</a>
|
||||||
<a href="/_gm/dictionary"{{if eq .ActiveNav "dictionary"}} class="active"{{end}}>Dictionary</a>
|
<a href="/_gm/dictionary"{{if eq .ActiveNav "dictionary"}} class="active"{{end}}>Dictionary</a>
|
||||||
<a href="/_gm/broadcast"{{if eq .ActiveNav "broadcast"}} class="active"{{end}}>Broadcast</a>
|
<a href="/_gm/broadcast"{{if eq .ActiveNav "broadcast"}} class="active"{{end}}>Broadcast</a>
|
||||||
<a href="/_gm/grafana/">Grafana ↗</a>
|
<a href="/_gm/grafana/">Grafana ↗</a>
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
{{with .Data}}
|
||||||
|
<p class="note"><a href="/_gm/banners">← all campaigns</a></p>
|
||||||
|
<h1>{{.Name}}{{if .IsDefault}} <span class="pill">default</span>{{end}}</h1>
|
||||||
|
<section class="panel"><h2>Settings</h2>
|
||||||
|
{{if .IsDefault}}<p class="note">The default campaign is perpetual and fills the unsold remainder — only its name and messages are editable.</p>{{end}}
|
||||||
|
<form class="form col" method="post" action="/_gm/banners/{{.ID}}">
|
||||||
|
<label>Name <input type="text" name="name" value="{{.Name}}" maxlength="80" required></label>
|
||||||
|
{{if not .IsDefault}}
|
||||||
|
<label>Weight (%) <input type="number" name="weight" min="1" max="100" value="{{.Weight}}" required></label>
|
||||||
|
<label>Starts (UTC) <input type="datetime-local" name="starts_at" value="{{.StartsAt}}"></label>
|
||||||
|
<label>Ends (UTC) <input type="datetime-local" name="ends_at" value="{{.EndsAt}}"></label>
|
||||||
|
<label><input type="checkbox" name="enabled"{{if .Enabled}} checked{{end}}> Enabled</label>
|
||||||
|
{{end}}
|
||||||
|
<div><button type="submit">Save</button></div>
|
||||||
|
</form>
|
||||||
|
{{if not .IsDefault}}
|
||||||
|
<form class="form" method="post" action="/_gm/banners/{{.ID}}/delete" onsubmit="return confirm('Delete this campaign and its messages?')">
|
||||||
|
<button type="submit" class="danger">Delete campaign</button>
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Messages</h2>
|
||||||
|
<div class="help-top">
|
||||||
|
<p class="note">Each message must be filled in both languages; the viewer sees the variant for the bot they play through. The messages of a campaign share its show weight, rotating in this order.</p>
|
||||||
|
<aside class="help">
|
||||||
|
<h4>Formatting</h4>
|
||||||
|
<p>Plain text is shown as-is (any HTML is escaped).</p>
|
||||||
|
<p>Add a link with markdown — <code>[visible text](https://example.com)</code> — which renders as the linked <em>visible text</em>.</p>
|
||||||
|
<p>Only <code>https://</code>, <code>http://</code> and root-relative <code>/path</code> targets become links; any other scheme (e.g. <code>javascript:</code>, <code>ftp:</code>) is dropped and shown as plain text.</p>
|
||||||
|
<p>Keep it short: an over-long line scrolls in the strip; the same formatting applies when editing a message above.</p>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
{{range .Messages}}
|
||||||
|
<div class="row">
|
||||||
|
<form class="form col" method="post" action="/_gm/banners/{{$.Data.ID}}/messages/{{.ID}}">
|
||||||
|
<label>English <textarea name="body_en" rows="3" maxlength="500" required>{{.BodyEn}}</textarea></label>
|
||||||
|
<label>Russian <textarea name="body_ru" rows="3" maxlength="500" required>{{.BodyRu}}</textarea></label>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div class="actions">
|
||||||
|
<form class="form" method="post" action="/_gm/banners/{{$.Data.ID}}/messages/{{.ID}}/move"><input type="hidden" name="dir" value="up"><button type="submit"{{if .First}} disabled{{end}}>↑</button></form>
|
||||||
|
<form class="form" method="post" action="/_gm/banners/{{$.Data.ID}}/messages/{{.ID}}/move"><input type="hidden" name="dir" value="down"><button type="submit"{{if .Last}} disabled{{end}}>↓</button></form>
|
||||||
|
<form class="form" method="post" action="/_gm/banners/{{$.Data.ID}}/messages/{{.ID}}/delete" onsubmit="return confirm('Delete this message?')"><button type="submit" class="danger">Delete</button></form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{else}}<p class="note">no messages yet</p>{{end}}
|
||||||
|
<h3>Add message</h3>
|
||||||
|
<form class="form col" method="post" action="/_gm/banners/{{.ID}}/messages">
|
||||||
|
<label>English <textarea name="body_en" rows="3" maxlength="500" required></textarea></label>
|
||||||
|
<label>Russian <textarea name="body_ru" rows="3" maxlength="500" required></textarea></label>
|
||||||
|
<div><button type="submit">Add message</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
<p class="note"><a href="/_gm/banners">← all campaigns</a></p>
|
||||||
|
<h1>Banner display timings</h1>
|
||||||
|
{{with .Data}}
|
||||||
|
<p class="note">Global timings the client's banner rotator reads. Out-of-range values are clamped on save. The transition between messages is fade-out, then a gap, then fade-in (skipped under reduce-motion).</p>
|
||||||
|
<section class="panel">
|
||||||
|
<form class="form col" method="post" action="/_gm/banner-settings">
|
||||||
|
<label>Hold (ms) — how long one message shows <input type="number" name="hold_ms" min="3000" max="600000" value="{{.HoldMs}}" required></label>
|
||||||
|
<label>Edge pause (ms) — pause at each end before/after scrolling a long message <input type="number" name="edge_pause_ms" min="0" max="60000" value="{{.EdgePauseMs}}" required></label>
|
||||||
|
<label>Scroll speed (px/s) — for a message wider than the strip <input type="number" name="scroll_px_per_sec" min="5" max="1000" value="{{.ScrollPxPerSec}}" required></label>
|
||||||
|
<label>Fade-out (ms) <input type="number" name="fade_out_ms" min="0" max="5000" value="{{.FadeOutMs}}" required></label>
|
||||||
|
<label>Gap (ms) — pause between fade-out and fade-in <input type="number" name="gap_ms" min="0" max="5000" value="{{.GapMs}}" required></label>
|
||||||
|
<label>Fade-in (ms) <input type="number" name="fade_in_ms" min="0" max="5000" value="{{.FadeInMs}}" required></label>
|
||||||
|
<div><button type="submit">Save</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
<h1>Advertising banners</h1>
|
||||||
|
{{with .Data}}
|
||||||
|
<p class="note">Campaigns compete for the one-line banner shown to free users (no paid account, an empty hint wallet, and no <code>no_banner</code> role). A campaign's weight is a show percent; the perpetual <strong>default</strong> campaign fills the remainder up to 100% and drops out of the rotation when timed campaigns already total 100%. <a href="/_gm/banner-settings">Display timings →</a></p>
|
||||||
|
<section class="panel"><h2>Add campaign</h2>
|
||||||
|
<form class="form col" method="post" action="/_gm/banners">
|
||||||
|
<label>Name <input type="text" name="name" maxlength="80" required></label>
|
||||||
|
<label>Weight (%) <input type="number" name="weight" min="1" max="100" value="10" required></label>
|
||||||
|
<label>Starts (UTC) <input type="datetime-local" name="starts_at"></label>
|
||||||
|
<label>Ends (UTC) <input type="datetime-local" name="ends_at"></label>
|
||||||
|
<label><input type="checkbox" name="enabled" checked> Enabled</label>
|
||||||
|
<div><button type="submit">Add</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Campaigns</h2>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Name</th><th class="num">Weight</th><th>Window</th><th class="num">Messages</th><th>Status</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Items}}
|
||||||
|
<tr>
|
||||||
|
<td><a href="/_gm/banners/{{.ID}}">{{.Name}}</a>{{if .IsDefault}} <span class="pill">default</span>{{end}}</td>
|
||||||
|
<td class="num">{{if .IsDefault}}remainder{{else}}{{.Weight}}%{{end}}</td>
|
||||||
|
<td>{{.Window}}</td>
|
||||||
|
<td class="num">{{.Messages}}</td>
|
||||||
|
<td>{{if .ActiveNow}}live{{else if .Enabled}}idle{{else}}disabled{{end}}</td>
|
||||||
|
</tr>
|
||||||
|
{{else}}<tr><td colspan="5"><span class="note">no campaigns</span></td></tr>{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -5,7 +5,6 @@
|
|||||||
{{if .ConnectorEnabled}}
|
{{if .ConnectorEnabled}}
|
||||||
<form class="form col" method="post" action="/_gm/broadcast">
|
<form class="form col" method="post" action="/_gm/broadcast">
|
||||||
<label>Message <textarea name="text" required></textarea></label>
|
<label>Message <textarea name="text" required></textarea></label>
|
||||||
<label>Bot language <select name="language"><option value="en">en</option><option value="ru">ru</option></select></label>
|
|
||||||
<div><button type="submit">Post to channel</button></div>
|
<div><button type="submit">Post to channel</button></div>
|
||||||
</form>
|
</form>
|
||||||
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
{{with .Data}}
|
||||||
|
<h1>Message</h1>
|
||||||
|
<nav class="subnav"><a href="/_gm/messages">« messages</a> · <a href="/_gm/games/{{.GameID}}">game</a> · <a href="/_gm/messages?game={{.GameID}}">game messages</a></nav>
|
||||||
|
<section class="panel"><h2>Summary</h2>
|
||||||
|
<ul class="kv">
|
||||||
|
<li><b>Time</b> {{.CreatedAt}}</li>
|
||||||
|
<li><b>Sender</b> <a href="/_gm/users/{{.SenderID}}">{{.SenderName}}</a> ({{.Source}})</li>
|
||||||
|
<li><b>IP</b> {{.IP}}</li>
|
||||||
|
<li><b>Kind</b> {{.Kind}}</li>
|
||||||
|
<li><b>Read</b> {{if .Unread}}unread{{else}}read{{end}}</li>
|
||||||
|
<li><b>Message</b> {{.Body}}</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Read by seat</h2>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Seat</th><th>Player</th><th>Status</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Seats}}
|
||||||
|
<tr><td>{{.Seat}}</td><td><a href="/_gm/users/{{.AccountID}}">{{if .DisplayName}}{{.DisplayName}}{{else}}{{.AccountID}}{{end}}</a></td><td>{{if eq .Role "read"}}<span class="ok">read</span>{{else if eq .Role "unread"}}unread{{else}}sender{{end}}</td></tr>
|
||||||
|
{{else}}
|
||||||
|
<tr><td colspan="3"><span class="note">no seats</span></td></tr>
|
||||||
|
{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
<a class="card" href="/_gm/games"><h2>Games</h2><p class="bignum">{{.Games}}</p></a>
|
<a class="card" href="/_gm/games"><h2>Games</h2><p class="bignum">{{.Games}}</p></a>
|
||||||
<a class="card" href="/_gm/games?status=active"><h2>Active games</h2><p class="bignum">{{.ActiveGames}}</p></a>
|
<a class="card" href="/_gm/games?status=active"><h2>Active games</h2><p class="bignum">{{.ActiveGames}}</p></a>
|
||||||
<a class="card" href="/_gm/complaints?status=open"><h2>Open complaints</h2><p class="bignum">{{.OpenComplaints}}</p></a>
|
<a class="card" href="/_gm/complaints?status=open"><h2>Open complaints</h2><p class="bignum">{{.OpenComplaints}}</p></a>
|
||||||
|
<a class="card" href="/_gm/feedback?status=unread"><h2>Unread feedback</h2><p class="bignum">{{.OpenFeedback}}</p></a>
|
||||||
<a class="card" href="/_gm/dictionary"><h2>Pending dict changes</h2><p class="bignum">{{.PendingChanges}}</p></a>
|
<a class="card" href="/_gm/dictionary"><h2>Pending dict changes</h2><p class="bignum">{{.PendingChanges}}</p></a>
|
||||||
</div>
|
</div>
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
<h1>Feedback</h1>
|
||||||
|
{{with .Data}}
|
||||||
|
<nav class="subnav">
|
||||||
|
<a href="/_gm/feedback?status=unread"{{if eq .Status "unread"}} class="active"{{end}}>unread</a> ·
|
||||||
|
<a href="/_gm/feedback?status=read"{{if eq .Status "read"}} class="active"{{end}}>read</a> ·
|
||||||
|
<a href="/_gm/feedback?status=archived"{{if eq .Status "archived"}} class="active"{{end}}>archived</a>
|
||||||
|
</nav>
|
||||||
|
<form class="form" method="get" action="/_gm/feedback">
|
||||||
|
<input type="hidden" name="status" value="{{.Status}}">
|
||||||
|
{{if .UserID}}<input type="hidden" name="user" value="{{.UserID}}">{{end}}
|
||||||
|
<input name="name" value="{{.NameMask}}" placeholder="display name mask (* ?)">
|
||||||
|
<input name="ext" value="{{.ExtMask}}" placeholder="external id mask (* ?)">
|
||||||
|
<button type="submit">Filter</button>
|
||||||
|
</form>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Sender</th><th>Source</th><th>Channel</th><th>Attach</th><th>Reply</th><th>State</th><th>Filed</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Items}}
|
||||||
|
<tr>
|
||||||
|
<td><a href="/_gm/feedback/{{.ID}}">{{.SenderName}}</a></td>
|
||||||
|
<td>{{.Source}}</td>
|
||||||
|
<td>{{.Channel}}</td>
|
||||||
|
<td>{{if .HasAttachment}}yes{{else}}<span class="note">—</span>{{end}}</td>
|
||||||
|
<td>{{if .Replied}}<span class="ok">replied</span>{{else}}<span class="note">—</span>{{end}}</td>
|
||||||
|
<td>{{if .Archived}}archived{{else if .Read}}read{{else}}<span class="warn">unread</span>{{end}}</td>
|
||||||
|
<td>{{.CreatedAt}}</td>
|
||||||
|
</tr>
|
||||||
|
{{else}}<tr><td colspan="7"><span class="note">no feedback</span></td></tr>{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<nav class="pager">
|
||||||
|
{{if .Pager.HasPrev}}<a href="/_gm/feedback?{{.FilterQuery}}&page={{.Pager.PrevPage}}">« prev</a>{{end}}
|
||||||
|
<span>page {{.Pager.Page}} · {{.Pager.Total}} total</span>
|
||||||
|
{{if .Pager.HasNext}}<a href="/_gm/feedback?{{.FilterQuery}}&page={{.Pager.NextPage}}">next »</a>{{end}}
|
||||||
|
</nav>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
{{with .Data}}
|
||||||
|
<h1>Feedback</h1>
|
||||||
|
<nav class="subnav"><a href="/_gm/feedback">« feedback</a> · <a href="/_gm/users/{{.AccountID}}">user</a></nav>
|
||||||
|
<section class="panel"><h2>Message</h2>
|
||||||
|
<ul class="kv">
|
||||||
|
<li><b>From</b> <a href="/_gm/users/{{.AccountID}}">{{.SenderName}}</a> ({{.Source}})</li>
|
||||||
|
<li><b>Channel</b> {{.Channel}}</li>
|
||||||
|
<li><b>Interface language</b> {{.InterfaceLanguage}}</li>
|
||||||
|
<li><b>IP</b> {{if .IP}}<code>{{.IP}}</code>{{else}}<span class="note">none</span>{{end}}</li>
|
||||||
|
<li><b>Filed</b> {{.CreatedAt}}</li>
|
||||||
|
<li><b>State</b> {{if .Archived}}archived{{else if .Read}}read{{else}}<span class="warn">unread</span>{{end}}</li>
|
||||||
|
{{if .Banned}}<li><b>Feedback</b> <span class="warn">sender is banned from feedback</span></li>{{end}}
|
||||||
|
</ul>
|
||||||
|
<div class="msgbody">{{.Body}}</div>
|
||||||
|
{{if .HasAttachment}}
|
||||||
|
<h3>Attachment</h3>
|
||||||
|
{{if .IsImage}}<p><img class="attach" src="/_gm/feedback/{{.ID}}/attachment" alt="attachment"></p>{{end}}
|
||||||
|
<p><a href="/_gm/feedback/{{.ID}}/attachment" download>download {{.AttachmentName}}</a></p>
|
||||||
|
{{end}}
|
||||||
|
</section>
|
||||||
|
{{if .Replied}}
|
||||||
|
<section class="panel"><h2>Current reply</h2>
|
||||||
|
<div class="msgbody">{{.ReplyBody}}</div>
|
||||||
|
<p class="note">sent {{.RepliedAt}}</p>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
<section class="panel"><h2>{{if .Replied}}Re-reply{{else}}Reply{{end}}</h2>
|
||||||
|
<form class="form col" method="post" action="/_gm/feedback/{{.ID}}/reply">
|
||||||
|
<label>Reply <textarea name="reply" required></textarea></label>
|
||||||
|
<div><button type="submit">Send reply</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Actions</h2>
|
||||||
|
{{if not .Read}}<form class="form" method="post" action="/_gm/feedback/{{.ID}}/read"><button type="submit">Mark read</button></form>{{end}}
|
||||||
|
{{if not .Archived}}<form class="form" method="post" action="/_gm/feedback/{{.ID}}/archive"><button type="submit">Archive</button></form>{{end}}
|
||||||
|
<form class="form col" method="post" action="/_gm/feedback/{{.ID}}/delete">
|
||||||
|
<label><input type="checkbox" name="block" value="1"> ban the player from feedback</label>
|
||||||
|
<div>
|
||||||
|
<button type="submit">Delete</button>
|
||||||
|
<button type="submit" formaction="/_gm/feedback/{{.ID}}/delete-all">Delete all from this player</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
<li><b>Variant</b> {{.Variant}}</li>
|
<li><b>Variant</b> {{.Variant}}</li>
|
||||||
<li><b>Dictionary</b> {{.DictVersion}}</li>
|
<li><b>Dictionary</b> {{.DictVersion}}</li>
|
||||||
<li><b>Status</b> {{.Status}}{{if .EndReason}} ({{.EndReason}}){{end}}</li>
|
<li><b>Status</b> {{.Status}}{{if .EndReason}} ({{.EndReason}}){{end}}</li>
|
||||||
|
<li><b>AI game</b> {{if .VsAI}}🤖 yes{{else}}no{{end}}</li>
|
||||||
<li><b>Players</b> {{.Players}}</li>
|
<li><b>Players</b> {{.Players}}</li>
|
||||||
<li><b>To move</b> seat {{.ToMove}}</li>
|
<li><b>To move</b> seat {{.ToMove}}</li>
|
||||||
<li><b>Moves</b> {{.MoveCount}}</li>
|
<li><b>Moves</b> {{.MoveCount}}</li>
|
||||||
@@ -26,5 +27,87 @@
|
|||||||
</table>
|
</table>
|
||||||
{{if .HasRobot}}<p><small>Play-to-win is decided once per game from the bag seed; robots play to win in ~{{.RobotTargetPct}}% of games.</small></p>{{end}}
|
{{if .HasRobot}}<p><small>Play-to-win is decided once per game from the bag seed; robots play to win in ~{{.RobotTargetPct}}% of games.</small></p>{{end}}
|
||||||
</section>
|
</section>
|
||||||
|
{{if .SetupDraws}}
|
||||||
|
<section class="panel"><h2>First-move draw</h2>
|
||||||
|
<p class="note">Each player draws a tile; the one closest to “A” moves first (a blank beats every letter), ties re-drawing until a single leader remains.{{if .FirstMover}} <b>{{.FirstMover}}</b> leads.{{end}}</p>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Round</th><th>Player</th><th>Tile</th><th>Rank</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .SetupDraws}}
|
||||||
|
<tr><td>{{.Round}}</td><td>{{if .AccountID}}<a href="/_gm/users/{{.AccountID}}">{{.Name}}</a>{{else}}{{.Name}}{{end}}</td><td>{{.Letter}}{{if .Blank}} <small>(blank)</small>{{end}}</td><td>{{.Rank}}</td></tr>
|
||||||
|
{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{if .HasReplay}}
|
||||||
|
<section class="panel"><h2>Replay</h2>
|
||||||
|
<div class="replay-stage">
|
||||||
|
<div class="rack-slot rack-top" data-seat="0"></div>
|
||||||
|
<div class="rack-slot rack-left" data-seat="2"></div>
|
||||||
|
<div class="replay-board" id="replay-board"></div>
|
||||||
|
<div class="rack-slot rack-right" data-seat="3"></div>
|
||||||
|
<div class="rack-slot rack-bottom" data-seat="1"></div>
|
||||||
|
</div>
|
||||||
|
<div class="replay-controls">
|
||||||
|
<button type="button" id="replay-prev">◀ prev</button>
|
||||||
|
<span class="replay-pos" id="replay-pos"></span>
|
||||||
|
<button type="button" id="replay-next">next ▶</button>
|
||||||
|
</div>
|
||||||
|
<ol class="replay-log" id="replay-log"></ol>
|
||||||
|
<script>
|
||||||
|
const REPLAY = {{.ReplayJSON}};
|
||||||
|
(function(){
|
||||||
|
if(!REPLAY||!REPLAY.steps){return;}
|
||||||
|
const N=15, COLS="ABCDEFGHIJKLMNO", PREM={tw:"3W",dw:"2W",tl:"3L",dl:"2L"};
|
||||||
|
const boardEl=document.getElementById("replay-board"), logEl=document.getElementById("replay-log");
|
||||||
|
const posEl=document.getElementById("replay-pos"), prevBtn=document.getElementById("replay-prev"), nextBtn=document.getElementById("replay-next");
|
||||||
|
let step=0;
|
||||||
|
function esc(s){const d=document.createElement("div");d.textContent=s==null?"":s;return d.innerHTML;}
|
||||||
|
function tileHTML(t){const sub=(t.v&&t.v>0)?"<sub>"+t.v+"<\/sub>":"";return "<span class=\"tile"+(t.b?" blank":"")+"\">"+esc(t.l)+sub+"<\/span>";}
|
||||||
|
function placedAt(k){const m={};for(let s=1;s<=k;s++){const mv=REPLAY.steps[s]&&REPLAY.steps[s].move;if(mv&&mv.placements){for(const p of mv.placements){m[p.r+","+p.c]=p;}}}return m;}
|
||||||
|
function renderBoard(){
|
||||||
|
const placed=placedAt(step);let h="<div class=\"board-grid\"><div class=\"bh corner\"><\/div>";
|
||||||
|
for(let c=0;c<N;c++){h+="<div class=\"bh\">"+COLS[c]+"<\/div>";}
|
||||||
|
for(let r=0;r<N;r++){h+="<div class=\"bh\">"+(r+1)+"<\/div>";
|
||||||
|
for(let c=0;c<N;c++){const p=placed[r+","+c];
|
||||||
|
if(p){h+="<div class=\"cell filled\">"+tileHTML(p)+"<\/div>";continue;}
|
||||||
|
const prem=REPLAY.premium[r][c], centre=(r===REPLAY.centre[0]&&c===REPLAY.centre[1]);
|
||||||
|
const label=centre?"★":(prem?PREM[prem]:"");
|
||||||
|
h+="<div class=\"cell "+(prem||"")+(centre?" centre":"")+"\">"+(label?"<span class=\"prem\">"+label+"<\/span>":"")+"<\/div>";}}
|
||||||
|
h+="<\/div>";boardEl.innerHTML=h;
|
||||||
|
}
|
||||||
|
function renderRacks(){
|
||||||
|
const st=REPLAY.steps[step];
|
||||||
|
document.querySelectorAll(".rack-slot").forEach(function(slot){
|
||||||
|
const seat=parseInt(slot.dataset.seat,10), info=REPLAY.seats.find(function(s){return s.seat===seat;}), rack=st.racks[seat];
|
||||||
|
if(!info||!rack){slot.style.display="none";slot.innerHTML="";return;}
|
||||||
|
slot.style.display="";slot.classList.toggle("active",st.toMove===seat);
|
||||||
|
const nm=info.accountId?"<a href=\"/_gm/users/"+info.accountId+"\">"+esc(info.name)+"<\/a>":esc(info.name||("seat "+seat));
|
||||||
|
slot.innerHTML="<div class=\"rack-name\">"+nm+" · "+(st.scores[seat]||0)+"<\/div><div class=\"rack-tiles\">"+rack.map(tileHTML).join("")+"<\/div>";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function renderLog(){
|
||||||
|
let h="";
|
||||||
|
for(let s=1;s<=step;s++){const st=REPLAY.steps[s], m=st.move;if(!m){continue;}
|
||||||
|
const who=((REPLAY.seats.find(function(x){return x.seat===m.seat;})||{}).name)||("seat "+m.seat);
|
||||||
|
let desc;
|
||||||
|
if(m.action==="play"){desc="played "+((m.words&&m.words.length)?m.words.join(", "):"")+" for "+m.score;}
|
||||||
|
else if(m.action==="exchange"){desc="exchanged "+((m.exchanged&&m.exchanged.length)||0)+" tiles";}
|
||||||
|
else if(m.action==="pass"){desc="passed";}
|
||||||
|
else{desc=m.action;}
|
||||||
|
const drew=(st.drawn&&st.drawn.length)?" · drew "+st.drawn.map(function(t){return t.l;}).join(""):"";
|
||||||
|
h+="<li class=\""+(s===step?"cur":"")+"\">"+esc(who)+" "+esc(desc)+drew+" · bag "+st.bagLen+"<\/li>";}
|
||||||
|
logEl.innerHTML=h||"<li class=\"note\">opening position<\/li>";
|
||||||
|
}
|
||||||
|
function render(){renderBoard();renderRacks();renderLog();posEl.textContent=step+" / "+(REPLAY.steps.length-1);prevBtn.disabled=step<=0;nextBtn.disabled=step>=REPLAY.steps.length-1;}
|
||||||
|
prevBtn.onclick=function(){if(step>0){step--;render();}};
|
||||||
|
nextBtn.onclick=function(){if(step<REPLAY.steps.length-1){step++;render();}};
|
||||||
|
document.addEventListener("keydown",function(e){if(e.key==="ArrowLeft"){prevBtn.click();}else if(e.key==="ArrowRight"){nextBtn.click();}});
|
||||||
|
render();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
{{end}}
|
{{end}}
|
||||||
{{- end}}
|
{{- end}}
|
||||||
|
|||||||
@@ -8,11 +8,11 @@
|
|||||||
<a href="/_gm/games?status=finished"{{if eq .Status "finished"}} class="active"{{end}}>finished</a>
|
<a href="/_gm/games?status=finished"{{if eq .Status "finished"}} class="active"{{end}}>finished</a>
|
||||||
</nav>
|
</nav>
|
||||||
<table class="list">
|
<table class="list">
|
||||||
<thead><tr><th>Game</th><th>Variant</th><th>Status</th><th class="num">Players</th><th>Updated</th></tr></thead>
|
<thead><tr><th>Game</th><th>Variant</th><th>Status</th><th>🤖</th><th class="num">Players</th><th>Updated</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{{range .Items}}
|
{{range .Items}}
|
||||||
<tr><td><a href="/_gm/games/{{.ID}}">{{.ID}}</a></td><td>{{.Variant}}</td><td>{{.Status}}</td><td class="num">{{.Players}}</td><td>{{.UpdatedAt}}</td></tr>
|
<tr><td><a href="/_gm/games/{{.ID}}">{{.ID}}</a></td><td>{{.Variant}}</td><td>{{.Status}}</td><td>{{if .VsAI}}🤖{{end}}</td><td class="num">{{.Players}}</td><td>{{.UpdatedAt}}</td></tr>
|
||||||
{{else}}<tr><td colspan="5"><span class="note">no games</span></td></tr>{{end}}
|
{{else}}<tr><td colspan="6"><span class="note">no games</span></td></tr>{{end}}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<nav class="pager">
|
<nav class="pager">
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
{{if .UserID}}<input type="hidden" name="user" value="{{.UserID}}">{{end}}
|
{{if .UserID}}<input type="hidden" name="user" value="{{.UserID}}">{{end}}
|
||||||
<input name="name" value="{{.NameMask}}" placeholder="sender name mask (* ?)">
|
<input name="name" value="{{.NameMask}}" placeholder="sender name mask (* ?)">
|
||||||
<input name="ext" value="{{.ExtMask}}" placeholder="sender external id mask (* ?)">
|
<input name="ext" value="{{.ExtMask}}" placeholder="sender external id mask (* ?)">
|
||||||
|
<label class="check"><input type="checkbox" name="unread" value="1"{{if .UnreadOnly}} checked{{end}}> unread only</label>
|
||||||
<button type="submit">Filter</button>
|
<button type="submit">Filter</button>
|
||||||
<a class="export" href="/_gm/messages.csv?{{.FilterQuery}}">Export CSV ↓</a>
|
<a class="export" href="/_gm/messages.csv?{{.FilterQuery}}">Export CSV ↓</a>
|
||||||
</form>
|
</form>
|
||||||
@@ -13,19 +14,20 @@
|
|||||||
<p class="note">Filtered{{if .GameID}} to game <a href="/_gm/games/{{.GameID}}">{{.GameID}}</a>{{end}}{{if .UserID}} from <a href="/_gm/users/{{.UserID}}">sender</a>{{end}} · <a href="/_gm/messages">clear</a></p>
|
<p class="note">Filtered{{if .GameID}} to game <a href="/_gm/games/{{.GameID}}">{{.GameID}}</a>{{end}}{{if .UserID}} from <a href="/_gm/users/{{.UserID}}">sender</a>{{end}} · <a href="/_gm/messages">clear</a></p>
|
||||||
{{end}}
|
{{end}}
|
||||||
<table class="list">
|
<table class="list">
|
||||||
<thead><tr><th>Time</th><th>Source</th><th>Sender</th><th>IP</th><th>Message</th><th>Game</th></tr></thead>
|
<thead><tr><th>Time</th><th>Source</th><th>Sender</th><th>IP</th><th>Message</th><th>Read</th><th>Game</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{{range .Items}}
|
{{range .Items}}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{.CreatedAt}}</td>
|
<td><a href="/_gm/messages/{{.ID}}">{{.CreatedAt}}</a></td>
|
||||||
<td>{{.Source}}</td>
|
<td>{{.Source}}</td>
|
||||||
<td><a href="/_gm/users/{{.SenderID}}">{{.SenderName}}</a></td>
|
<td><a href="/_gm/users/{{.SenderID}}">{{.SenderName}}</a></td>
|
||||||
<td>{{.IP}}</td>
|
<td>{{.IP}}</td>
|
||||||
<td>{{.Body}}</td>
|
<td>{{.Body}}</td>
|
||||||
|
<td>{{if .Unread}}unread{{else}}read{{end}}</td>
|
||||||
<td><a href="/_gm/games/{{.GameID}}">game</a></td>
|
<td><a href="/_gm/games/{{.GameID}}">game</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
{{else}}
|
{{else}}
|
||||||
<tr><td colspan="6"><span class="note">no messages</span></td></tr>
|
<tr><td colspan="7"><span class="note">no messages</span></td></tr>
|
||||||
{{end}}
|
{{end}}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{{define "content" -}}
|
||||||
|
<h1>Suspension reasons</h1>
|
||||||
|
{{with .Data}}
|
||||||
|
<p class="note">Reasons offered when blocking a user; each is shown to the blocked player in their own language. Editing or deleting a reason does not change a reason already shown to a currently-blocked player (blocks snapshot the text).</p>
|
||||||
|
<section class="panel"><h2>Add reason</h2>
|
||||||
|
<form class="form col" method="post" action="/_gm/reasons">
|
||||||
|
<label>English <input type="text" name="text_en" required></label>
|
||||||
|
<label>Russian <input type="text" name="text_ru" required></label>
|
||||||
|
<div><button type="submit">Add</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Existing reasons</h2>
|
||||||
|
{{range .Items}}
|
||||||
|
<div class="row">
|
||||||
|
<form class="form" method="post" action="/_gm/reasons/{{.ID}}/update">
|
||||||
|
<input type="text" name="text_en" value="{{.TextEn}}" aria-label="English" required>
|
||||||
|
<input type="text" name="text_ru" value="{{.TextRu}}" aria-label="Russian" required>
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</form>
|
||||||
|
<form class="form" method="post" action="/_gm/reasons/{{.ID}}/delete">
|
||||||
|
<button type="submit">Delete</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{{else}}<p class="note">no reasons yet</p>{{end}}
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{- end}}
|
||||||
@@ -5,6 +5,26 @@
|
|||||||
list is in-memory and resets on a backend restart. An account sustaining
|
list is in-memory and resets on a backend restart. An account sustaining
|
||||||
{{.FlagThreshold}}+ rejected calls within {{.FlagWindow}} is soft-flagged for review
|
{{.FlagThreshold}}+ rejected calls within {{.FlagWindow}} is soft-flagged for review
|
||||||
below — never banned automatically; clear the flag on the user card.</p>
|
below — never banned automatically; clear the flag on the user card.</p>
|
||||||
|
<section class="panel"><h2>Active IP bans</h2>
|
||||||
|
<p class="note">Temporary IP bans the gateway is currently enforcing (in-memory, prod-only;
|
||||||
|
reset on a gateway restart). Unban applies on the gateway's next sync.</p>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>IP</th><th>Reason</th><th>Since</th><th>Expires</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Bans}}
|
||||||
|
<tr>
|
||||||
|
<td><code>{{.IP}}</code></td>
|
||||||
|
<td>{{.Reason}}</td>
|
||||||
|
<td>{{.Since}}</td>
|
||||||
|
<td>{{.Expires}}</td>
|
||||||
|
<td><form class="form" method="post" action="/_gm/bans/unban"><input type="hidden" name="ip" value="{{.IP}}"><button type="submit">Unban</button></form></td>
|
||||||
|
</tr>
|
||||||
|
{{else}}
|
||||||
|
<tr><td colspan="5"><span class="note">no active bans</span></td></tr>
|
||||||
|
{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
<section class="panel"><h2>Recent episodes</h2>
|
<section class="panel"><h2>Recent episodes</h2>
|
||||||
<table class="list">
|
<table class="list">
|
||||||
<thead><tr><th>Class</th><th>Key</th><th class="num">Rejected</th><th>First seen</th><th>Last seen</th></tr></thead>
|
<thead><tr><th>Class</th><th>Key</th><th class="num">Rejected</th><th>First seen</th><th>Last seen</th></tr></thead>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{{define "content" -}}
|
{{define "content" -}}
|
||||||
{{with .Data}}
|
{{with .Data}}
|
||||||
<h1>{{.DisplayName}}</h1>
|
<h1>{{.DisplayName}}</h1>
|
||||||
<nav class="subnav"><a href="/_gm/users">« users</a> · <a href="/_gm/messages?user={{.ID}}">messages</a></nav>
|
<nav class="subnav"><a href="/_gm/users">« users</a> · <a href="/_gm/messages?user={{.ID}}">messages</a> · <a href="/_gm/feedback?user={{.ID}}">feedback</a></nav>
|
||||||
<div class="cards">
|
<div class="cards">
|
||||||
<section class="panel"><h2>Account</h2>
|
<section class="panel"><h2>Account</h2>
|
||||||
<ul class="kv">
|
<ul class="kv">
|
||||||
@@ -21,6 +21,10 @@
|
|||||||
<button type="submit">Clear high-rate flag</button>
|
<button type="submit">Clear high-rate flag</button>
|
||||||
</form>
|
</form>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
<form class="form" method="post" action="/_gm/users/{{.ID}}/grant-hints">
|
||||||
|
<label>Add hints <input type="number" name="amount" min="1" max="{{.HintGrantMax}}" value="1"></label>
|
||||||
|
<button type="submit">Grant</button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
<section class="panel"><h2>Statistics</h2>
|
<section class="panel"><h2>Statistics</h2>
|
||||||
{{if .HasStats}}
|
{{if .HasStats}}
|
||||||
@@ -28,12 +32,60 @@
|
|||||||
<li><b>Wins</b> {{.Stats.Wins}}</li>
|
<li><b>Wins</b> {{.Stats.Wins}}</li>
|
||||||
<li><b>Losses</b> {{.Stats.Losses}}</li>
|
<li><b>Losses</b> {{.Stats.Losses}}</li>
|
||||||
<li><b>Draws</b> {{.Stats.Draws}}</li>
|
<li><b>Draws</b> {{.Stats.Draws}}</li>
|
||||||
|
<li><b>Moves</b> {{.Stats.Moves}}</li>
|
||||||
|
<li><b>Hints used</b> {{.Stats.HintsUsed}}</li>
|
||||||
<li><b>Best game</b> {{.Stats.MaxGamePoints}}</li>
|
<li><b>Best game</b> {{.Stats.MaxGamePoints}}</li>
|
||||||
<li><b>Best move</b> {{.Stats.MaxWordPoints}}</li>
|
<li><b>Best move</b> {{.Stats.MaxWordPoints}}</li>
|
||||||
</ul>
|
</ul>
|
||||||
{{else}}<p class="note">no statistics</p>{{end}}
|
{{else}}<p class="note">no statistics</p>{{end}}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
<section class="panel"><h2>Account block</h2>
|
||||||
|
{{$uid := .ID}}
|
||||||
|
{{with .Suspension}}{{if .Blocked}}
|
||||||
|
<ul class="kv">
|
||||||
|
<li><b>Status</b> <span class="warn">{{if .Permanent}}blocked (permanent){{else}}blocked until {{.Until}} (UTC){{end}}</span></li>
|
||||||
|
{{if .BlockedAt}}<li><b>Since</b> {{.BlockedAt}}</li>{{end}}
|
||||||
|
{{if .ReasonEn}}<li><b>Reason</b> {{.ReasonEn}} / {{.ReasonRu}}</li>{{end}}
|
||||||
|
</ul>
|
||||||
|
<form class="form" method="post" action="/_gm/users/{{$uid}}/unblock">
|
||||||
|
<button type="submit">Unblock</button>
|
||||||
|
</form>
|
||||||
|
{{else}}<p class="note">not blocked</p>{{end}}{{end}}
|
||||||
|
<form class="form col" method="post" action="/_gm/users/{{.ID}}/block">
|
||||||
|
<label>Duration <select name="duration">
|
||||||
|
<option value="permanent">permanent</option>
|
||||||
|
<option value="1d">1 day</option>
|
||||||
|
<option value="3d">3 days</option>
|
||||||
|
<option value="1w">1 week</option>
|
||||||
|
<option value="1m">1 month</option>
|
||||||
|
<option value="custom">custom date (UTC)</option>
|
||||||
|
</select></label>
|
||||||
|
<label>Custom until (UTC; used when duration is "custom") <input type="datetime-local" name="until"></label>
|
||||||
|
<label>Reason <select name="reason">
|
||||||
|
<option value="">— none —</option>
|
||||||
|
{{range .Reasons}}<option value="{{.ID}}">{{.TextEn}}</option>{{end}}
|
||||||
|
</select></label>
|
||||||
|
<div><button type="submit">{{if .Suspension.Blocked}}Re-block{{else}}Block{{end}}</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Roles</h2>
|
||||||
|
{{$id := .ID}}
|
||||||
|
{{if .Roles}}
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Role</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Roles}}
|
||||||
|
<tr><td><code>{{.}}</code></td><td><form class="form" method="post" action="/_gm/users/{{$id}}/revoke-role"><input type="hidden" name="role" value="{{.}}"><button type="submit">Revoke</button></form></td></tr>
|
||||||
|
{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{{else}}<p class="note">no roles</p>{{end}}
|
||||||
|
<form class="form col" method="post" action="/_gm/users/{{$id}}/grant-role">
|
||||||
|
<label>Grant role <select name="role">{{range .KnownRoles}}<option value="{{.}}">{{.}}</option>{{end}}</select></label>
|
||||||
|
<div><button type="submit">Grant</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
{{if .MoveChart}}
|
{{if .MoveChart}}
|
||||||
<section class="panel"><h2>Move timing</h2>
|
<section class="panel"><h2>Move timing</h2>
|
||||||
<p class="note">Think time per move number across all games — <span class="lg lg-min">min</span> · <span class="lg lg-avg">mean</span> · <span class="lg lg-max">max</span>.</p>
|
<p class="note">Think time per move number across all games — <span class="lg lg-min">min</span> · <span class="lg lg-avg">mean</span> · <span class="lg lg-max">max</span>.</p>
|
||||||
@@ -50,12 +102,41 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
<section class="panel"><h2>Friends</h2>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Account</th><th>Friends since</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Friends}}
|
||||||
|
<tr><td><a href="/_gm/users/{{.AccountID}}">{{.DisplayName}}</a></td><td>{{.Date}}</td></tr>
|
||||||
|
{{else}}<tr><td colspan="2"><span class="note">no friends</span></td></tr>{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Blocks</h2>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Account</th><th>Blocked at</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .Blocks}}
|
||||||
|
<tr><td><a href="/_gm/users/{{.AccountID}}">{{.DisplayName}}</a></td><td>{{.Date}}</td></tr>
|
||||||
|
{{else}}<tr><td colspan="2"><span class="note">blocks no one</span></td></tr>{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><h2>Blocked by</h2>
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Account</th><th>Blocked at</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{range .BlockedBy}}
|
||||||
|
<tr><td><a href="/_gm/users/{{.AccountID}}">{{.DisplayName}}</a></td><td>{{.Date}}</td></tr>
|
||||||
|
{{else}}<tr><td colspan="2"><span class="note">blocked by no one</span></td></tr>{{end}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
{{if .TelegramID}}
|
{{if .TelegramID}}
|
||||||
<section class="panel"><h2>Send Telegram message</h2>
|
<section class="panel"><h2>Send Telegram message</h2>
|
||||||
{{if .ConnectorEnabled}}
|
{{if .ConnectorEnabled}}
|
||||||
<form class="form col" method="post" action="/_gm/users/{{.ID}}/message">
|
<form class="form col" method="post" action="/_gm/users/{{.ID}}/message">
|
||||||
<label>Message <textarea name="text" required></textarea></label>
|
<label>Message <textarea name="text" required></textarea></label>
|
||||||
<label>Bot language <select name="language"><option value="en">en</option><option value="ru">ru</option></select></label>
|
|
||||||
<div><button type="submit">Send to user</button></div>
|
<div><button type="submit">Send to user</button></div>
|
||||||
</form>
|
</form>
|
||||||
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ type DashboardView struct {
|
|||||||
Games int
|
Games int
|
||||||
ActiveGames int
|
ActiveGames int
|
||||||
OpenComplaints int
|
OpenComplaints int
|
||||||
|
OpenFeedback int
|
||||||
PendingChanges int
|
PendingChanges int
|
||||||
// ActiveVersion is the dictionary version new games pin (the persisted active
|
// ActiveVersion is the dictionary version new games pin (the persisted active
|
||||||
// version), distinct from the per-variant resident versions.
|
// version), distinct from the per-variant resident versions.
|
||||||
@@ -93,11 +94,13 @@ type MessagesView struct {
|
|||||||
ExtMask string
|
ExtMask string
|
||||||
GameID string
|
GameID string
|
||||||
UserID string
|
UserID string
|
||||||
|
UnreadOnly bool
|
||||||
FilterQuery template.URL
|
FilterQuery template.URL
|
||||||
}
|
}
|
||||||
|
|
||||||
// MessageRow is one chat message in the moderation list: its sender (linked to the user
|
// MessageRow is one chat message in the moderation list: its sender (linked to the user
|
||||||
// card), source, IP, body, game (linked to the game card) and time.
|
// card), source, IP, body, game (linked to the game card), time, and whether it is still
|
||||||
|
// unread by at least one recipient.
|
||||||
type MessageRow struct {
|
type MessageRow struct {
|
||||||
ID string
|
ID string
|
||||||
SenderID string
|
SenderID string
|
||||||
@@ -107,6 +110,32 @@ type MessageRow struct {
|
|||||||
Body string
|
Body string
|
||||||
GameID string
|
GameID string
|
||||||
CreatedAt string
|
CreatedAt string
|
||||||
|
Unread bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatMessageDetailView is one chat message with its per-seat read breakdown, for the
|
||||||
|
// console message card.
|
||||||
|
type ChatMessageDetailView struct {
|
||||||
|
ID string
|
||||||
|
GameID string
|
||||||
|
SenderID string
|
||||||
|
SenderName string
|
||||||
|
Source string
|
||||||
|
Kind string
|
||||||
|
Body string
|
||||||
|
IP string
|
||||||
|
CreatedAt string
|
||||||
|
Unread bool
|
||||||
|
Seats []ChatSeatStatusRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChatSeatStatusRow is one seat's read status on the message card: the seat index, the
|
||||||
|
// occupant (linked to the user card) and its role ("sender", "read" or "unread").
|
||||||
|
type ChatSeatStatusRow struct {
|
||||||
|
Seat int
|
||||||
|
AccountID string
|
||||||
|
DisplayName string
|
||||||
|
Role string
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserDetailView is one account with its stats, identities and recent games.
|
// UserDetailView is one account with its stats, identities and recent games.
|
||||||
@@ -125,6 +154,9 @@ type UserDetailView struct {
|
|||||||
// empty for an unflagged account; the card shows it with the Clear action.
|
// empty for an unflagged account; the card shows it with the Clear action.
|
||||||
FlaggedHighRateAt string
|
FlaggedHighRateAt string
|
||||||
HintBalance int
|
HintBalance int
|
||||||
|
// HintGrantMax is the per-grant cap the operator's "add hints" form enforces (it mirrors the
|
||||||
|
// server's maxHintGrant), passed through so the policy value lives in one place.
|
||||||
|
HintGrantMax int
|
||||||
CreatedAt string
|
CreatedAt string
|
||||||
HasStats bool
|
HasStats bool
|
||||||
Stats StatsRow
|
Stats StatsRow
|
||||||
@@ -135,6 +167,48 @@ type UserDetailView struct {
|
|||||||
// MoveChart is the pre-rendered inline SVG of the account's per-move-number think
|
// MoveChart is the pre-rendered inline SVG of the account's per-move-number think
|
||||||
// time (min/mean/max), empty when the account has no timed move.
|
// time (min/mean/max), empty when the account has no timed move.
|
||||||
MoveChart template.HTML
|
MoveChart template.HTML
|
||||||
|
// Suspension is the account's current manual-block state, shown with the block/unblock
|
||||||
|
// form; Reasons is the operator-editable reason picklist offered in the block form.
|
||||||
|
Suspension SuspensionView
|
||||||
|
Reasons []ReasonOption
|
||||||
|
// Roles is the account's current roles (each revocable); KnownRoles is the set the
|
||||||
|
// grant form offers. The first role is the feedback ban (see internal/account).
|
||||||
|
Roles []string
|
||||||
|
KnownRoles []string
|
||||||
|
// Blocks, BlockedBy and Friends are the social graph on the card: who this account has
|
||||||
|
// blocked, who currently blocks it, and its mutual friendships — each cross-linked to the
|
||||||
|
// other account with the date it happened. They are the full truth; the asymmetric block
|
||||||
|
// suppression that hides relationships from players never applies to the console.
|
||||||
|
Blocks []RelationRow
|
||||||
|
BlockedBy []RelationRow
|
||||||
|
Friends []RelationRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// RelationRow is one cross-linked account in the user card's blocks / blocked-by / friends
|
||||||
|
// lists: the other account's id (the link target), its display name, and the pre-formatted date.
|
||||||
|
type RelationRow struct {
|
||||||
|
AccountID string
|
||||||
|
DisplayName string
|
||||||
|
Date string
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuspensionView is an account's current manual-block state shown on the user card: whether it
|
||||||
|
// is blocked, whether the block is permanent, the pre-formatted expiry (empty when permanent),
|
||||||
|
// when it was applied, and the reason snapshot in both languages (empty when none was cited).
|
||||||
|
type SuspensionView struct {
|
||||||
|
Blocked bool
|
||||||
|
Permanent bool
|
||||||
|
Until string
|
||||||
|
BlockedAt string
|
||||||
|
ReasonEn string
|
||||||
|
ReasonRu string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReasonOption is one suspension-reason picklist entry offered in the block form's dropdown.
|
||||||
|
type ReasonOption struct {
|
||||||
|
ID string
|
||||||
|
TextEn string
|
||||||
|
TextRu string
|
||||||
}
|
}
|
||||||
|
|
||||||
// StatsRow is an account's lifetime statistics.
|
// StatsRow is an account's lifetime statistics.
|
||||||
@@ -144,6 +218,8 @@ type StatsRow struct {
|
|||||||
Draws int
|
Draws int
|
||||||
MaxGamePoints int
|
MaxGamePoints int
|
||||||
MaxWordPoints int
|
MaxWordPoints int
|
||||||
|
Moves int
|
||||||
|
HintsUsed int
|
||||||
}
|
}
|
||||||
|
|
||||||
// IdentityRow is one platform/email identity of an account.
|
// IdentityRow is one platform/email identity of an account.
|
||||||
@@ -161,6 +237,8 @@ type GameRow struct {
|
|||||||
Status string
|
Status string
|
||||||
Players int
|
Players int
|
||||||
UpdatedAt string
|
UpdatedAt string
|
||||||
|
// VsAI marks an honest-AI game (rendered as 🤖 in the list's AI column).
|
||||||
|
VsAI bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// GamesView is the paginated games list, optionally filtered by status.
|
// GamesView is the paginated games list, optionally filtered by status.
|
||||||
@@ -183,11 +261,34 @@ type GameDetailView struct {
|
|||||||
CreatedAt string
|
CreatedAt string
|
||||||
UpdatedAt string
|
UpdatedAt string
|
||||||
FinishedAt string
|
FinishedAt string
|
||||||
|
// VsAI marks an honest-AI game (shown as a 🤖 flag in the summary).
|
||||||
|
VsAI bool
|
||||||
Seats []SeatRow
|
Seats []SeatRow
|
||||||
// HasRobot is true when any seat is a robot, gating the robot-target caption;
|
// HasRobot is true when any seat is a robot, gating the robot-target caption;
|
||||||
// RobotTargetPct is the configured global play-to-win rate, in percent.
|
// RobotTargetPct is the configured global play-to-win rate, in percent.
|
||||||
HasRobot bool
|
HasRobot bool
|
||||||
RobotTargetPct int
|
RobotTargetPct int
|
||||||
|
// ReplayJSON is the game-replay payload (board, seats, per-step racks/scores/bag) the
|
||||||
|
// game_detail page feeds to its vanilla-JS stepper; HasReplay gates the replay section.
|
||||||
|
ReplayJSON template.JS
|
||||||
|
HasReplay bool
|
||||||
|
// SetupDraws is the first-move draw — one row per tile drawn (docs/ARCHITECTURE.md §6) —
|
||||||
|
// and FirstMover is the resolved name of the seat-0 player the draw elected.
|
||||||
|
SetupDraws []SetupDrawRow
|
||||||
|
FirstMover string
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetupDrawRow is one tile drawn in the first-move seeding (docs/ARCHITECTURE.md §6): the
|
||||||
|
// round, the player (Name/AccountID, or "(opponent)" with an empty AccountID for an
|
||||||
|
// auto-match synthetic draw not yet back-filled), the drawn letter (upper-cased; "?" for a
|
||||||
|
// blank) and its draw rank.
|
||||||
|
type SetupDrawRow struct {
|
||||||
|
Round int
|
||||||
|
Name string
|
||||||
|
AccountID string
|
||||||
|
Letter string
|
||||||
|
Blank bool
|
||||||
|
Rank int
|
||||||
}
|
}
|
||||||
|
|
||||||
// SeatRow is one seat of a game. For a robot seat (IsRobot) RobotIntent is the game's
|
// SeatRow is one seat of a game. For a robot seat (IsRobot) RobotIntent is the game's
|
||||||
@@ -288,17 +389,27 @@ type BroadcastView struct {
|
|||||||
ConnectorEnabled bool
|
ConnectorEnabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ThrottledView is the rate-limit observability page: the recent gateway-reported
|
// ThrottledView is the rate-limit observability page: the temporary IP bans the
|
||||||
// throttle episodes (in-memory, reset on restart) and the accounts currently
|
// gateway is currently enforcing, the recent gateway-reported throttle episodes
|
||||||
// carrying the high-rate flag. FlagThreshold and FlagWindow caption the active
|
// (in-memory, reset on restart) and the accounts currently carrying the high-rate
|
||||||
// auto-flag tuning.
|
// flag. FlagThreshold and FlagWindow caption the active auto-flag tuning.
|
||||||
type ThrottledView struct {
|
type ThrottledView struct {
|
||||||
|
Bans []BanRow
|
||||||
Episodes []ThrottleEpisodeRow
|
Episodes []ThrottleEpisodeRow
|
||||||
Flagged []FlaggedAccountRow
|
Flagged []FlaggedAccountRow
|
||||||
FlagThreshold int
|
FlagThreshold int
|
||||||
FlagWindow string
|
FlagWindow string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BanRow is one temporary IP ban the gateway is enforcing, with its reason and its
|
||||||
|
// since/expiry timestamps; the row carries an unban action.
|
||||||
|
type BanRow struct {
|
||||||
|
IP string
|
||||||
|
Reason string
|
||||||
|
Since string
|
||||||
|
Expires string
|
||||||
|
}
|
||||||
|
|
||||||
// ThrottleEpisodeRow is one recently throttled limiter key. UserID links to the
|
// ThrottleEpisodeRow is one recently throttled limiter key. UserID links to the
|
||||||
// user card and is set only for the user class (the other classes key by IP).
|
// user card and is set only for the user class (the other classes key by IP).
|
||||||
type ThrottleEpisodeRow struct {
|
type ThrottleEpisodeRow struct {
|
||||||
@@ -317,9 +428,131 @@ type FlaggedAccountRow struct {
|
|||||||
FlaggedAt string
|
FlaggedAt string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ReasonsView is the suspension-reason picklist management page: every editable reason entry.
|
||||||
|
type ReasonsView struct {
|
||||||
|
Items []ReasonRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReasonRow is one editable suspension-reason entry, with its English and Russian text.
|
||||||
|
type ReasonRow struct {
|
||||||
|
ID string
|
||||||
|
TextEn string
|
||||||
|
TextRu string
|
||||||
|
CreatedAt string
|
||||||
|
}
|
||||||
|
|
||||||
// MessageView is the result page shown after a POST action.
|
// MessageView is the result page shown after a POST action.
|
||||||
type MessageView struct {
|
type MessageView struct {
|
||||||
Heading string
|
Heading string
|
||||||
Body string
|
Body string
|
||||||
Back string
|
Back string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BannersView is the advertising-campaign list page.
|
||||||
|
type BannersView struct {
|
||||||
|
Items []BannerCampaignRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// BannerCampaignRow is one campaign in the list. Window is a human-readable
|
||||||
|
// validity window ("perpetual" for the default); ActiveNow reports whether it
|
||||||
|
// would rotate right now (enabled and within its window).
|
||||||
|
type BannerCampaignRow struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
Weight int
|
||||||
|
IsDefault bool
|
||||||
|
Enabled bool
|
||||||
|
Window string
|
||||||
|
Messages int
|
||||||
|
ActiveNow bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// BannerDetailView is the campaign detail/edit page. StartsAt/EndsAt are the
|
||||||
|
// "YYYY-MM-DDTHH:MM" (UTC) values for the datetime-local inputs, empty when open.
|
||||||
|
type BannerDetailView struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
Weight int
|
||||||
|
IsDefault bool
|
||||||
|
Enabled bool
|
||||||
|
StartsAt string
|
||||||
|
EndsAt string
|
||||||
|
Messages []BannerMessageRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// BannerMessageRow is one bilingual message of a campaign. First/Last drive the
|
||||||
|
// reorder buttons (disabled at the ends).
|
||||||
|
type BannerMessageRow struct {
|
||||||
|
ID string
|
||||||
|
BodyEn string
|
||||||
|
BodyRu string
|
||||||
|
First bool
|
||||||
|
Last bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// BannerSettingsView is the global display-timings form.
|
||||||
|
type BannerSettingsView struct {
|
||||||
|
HoldMs int
|
||||||
|
EdgePauseMs int
|
||||||
|
ScrollPxPerSec int
|
||||||
|
FadeOutMs int
|
||||||
|
GapMs int
|
||||||
|
FadeInMs int
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeedbackView is the paginated user-feedback queue. Status is the active
|
||||||
|
// unread/read/archived filter; NameMask/ExtMask are the sender glob filters;
|
||||||
|
// UserID pins the list to one account (the per-user link from /users);
|
||||||
|
// FilterQuery is the active filters URL-encoded for the pager links (already
|
||||||
|
// escaped, hence template.URL — see UsersView.FilterQuery).
|
||||||
|
type FeedbackView struct {
|
||||||
|
Items []FeedbackRow
|
||||||
|
Status string
|
||||||
|
NameMask string
|
||||||
|
ExtMask string
|
||||||
|
UserID string
|
||||||
|
Pager Pager
|
||||||
|
FilterQuery template.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeedbackRow is one feedback message in the queue: its sender (linked to the user
|
||||||
|
// card), source, channel, whether it has an attachment / a reply, its state and
|
||||||
|
// time.
|
||||||
|
type FeedbackRow struct {
|
||||||
|
ID string
|
||||||
|
AccountID string
|
||||||
|
SenderName string
|
||||||
|
Source string
|
||||||
|
Channel string
|
||||||
|
HasAttachment bool
|
||||||
|
Read bool
|
||||||
|
Replied bool
|
||||||
|
Archived bool
|
||||||
|
CreatedAt string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FeedbackDetailView is one feedback message with its body, attachment, state and
|
||||||
|
// the reply / archive / delete forms. Body, AttachmentName, SenderName and IP are
|
||||||
|
// user-controlled and rendered as plain auto-escaped text. IsImage gates the inline
|
||||||
|
// <img> preview; Banned shows whether the sender already holds the feedback ban.
|
||||||
|
type FeedbackDetailView struct {
|
||||||
|
ID string
|
||||||
|
AccountID string
|
||||||
|
SenderName string
|
||||||
|
Source string
|
||||||
|
Channel string
|
||||||
|
// InterfaceLanguage is the sender's interface language (account preference).
|
||||||
|
InterfaceLanguage string
|
||||||
|
IP string
|
||||||
|
Body string
|
||||||
|
HasAttachment bool
|
||||||
|
AttachmentName string
|
||||||
|
IsImage bool
|
||||||
|
Read bool
|
||||||
|
Archived bool
|
||||||
|
Replied bool
|
||||||
|
ReplyBody string
|
||||||
|
RepliedAt string
|
||||||
|
CreatedAt string
|
||||||
|
Banned bool
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// Package ads owns the server-driven advertising banner ("advertising network"):
|
||||||
|
// operator-managed campaigns, their bilingual messages and the global display
|
||||||
|
// timings the client's one-line announcement strip rotates through.
|
||||||
|
//
|
||||||
|
// A campaign is one placement order with a show weight (an integer percent).
|
||||||
|
// Simultaneously active campaigns compete for display slots in proportion to
|
||||||
|
// their weights; the single perpetual default campaign fills the unsold
|
||||||
|
// remainder up to 100%. The actual rotation runs client-side (a smooth weighted
|
||||||
|
// round-robin over campaigns, round-robin over a campaign's messages); the server
|
||||||
|
// only computes the effective weighted, language-resolved set a viewer should
|
||||||
|
// rotate, via ActiveSet. Who sees a banner at all is decided by Eligible.
|
||||||
|
package ads
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNotFound is returned when a campaign or message does not exist.
|
||||||
|
var ErrNotFound = errors.New("ads: not found")
|
||||||
|
|
||||||
|
// ErrDefaultImmutable is returned when an operation is refused on the perpetual
|
||||||
|
// default campaign (it cannot be deleted, disabled, windowed, or have its
|
||||||
|
// weight or default flag changed).
|
||||||
|
var ErrDefaultImmutable = errors.New("ads: the default campaign cannot be modified that way")
|
||||||
|
|
||||||
|
// ErrValidation wraps an operator-facing validation failure (a bad weight,
|
||||||
|
// window or message body).
|
||||||
|
var ErrValidation = errors.New("ads: validation")
|
||||||
|
|
||||||
|
// Campaign is one advertising placement order with its messages.
|
||||||
|
type Campaign struct {
|
||||||
|
ID uuid.UUID // uuid.Nil on create
|
||||||
|
Name string
|
||||||
|
Weight int // show percent, 1..100; nominal (ignored) for the default
|
||||||
|
IsDefault bool
|
||||||
|
Enabled bool
|
||||||
|
StartsAt *time.Time // nil = open-ended start; always nil for the default
|
||||||
|
EndsAt *time.Time // nil = open-ended end; always nil for the default
|
||||||
|
Messages []Message
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message is one bilingual creative of a campaign. Both bodies are mandatory;
|
||||||
|
// the client shows the variant for the viewer's bot (service) language. Position
|
||||||
|
// orders the messages within a campaign (the round-robin order).
|
||||||
|
type Message struct {
|
||||||
|
ID uuid.UUID // uuid.Nil on create
|
||||||
|
CampaignID uuid.UUID
|
||||||
|
Position int
|
||||||
|
BodyEn string
|
||||||
|
BodyRu string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timings are the global banner display timings, in milliseconds except
|
||||||
|
// ScrollPxPerSec. HoldMs is how long one message shows; EdgePauseMs and
|
||||||
|
// ScrollPxPerSec drive the scroll of a message wider than the strip; a
|
||||||
|
// transition between messages is FadeOutMs then GapMs then FadeInMs.
|
||||||
|
type Timings struct {
|
||||||
|
HoldMs int
|
||||||
|
EdgePauseMs int
|
||||||
|
ScrollPxPerSec int
|
||||||
|
FadeOutMs int
|
||||||
|
GapMs int
|
||||||
|
FadeInMs int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActiveCampaign is one campaign in the resolved rotation feed sent to a client:
|
||||||
|
// its GCD-reduced show weight and its messages, already resolved to the viewer's
|
||||||
|
// language and in display (round-robin) order.
|
||||||
|
type ActiveCampaign struct {
|
||||||
|
Weight int
|
||||||
|
Messages []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Eligible reports whether an account should be shown the advertising banner: a
|
||||||
|
// free account (not paid) with an empty hint wallet and without the no_banner
|
||||||
|
// role. The no_banner role suppresses the banner unconditionally; buying a paid
|
||||||
|
// account or any hints also removes it.
|
||||||
|
func Eligible(paidAccount bool, hintBalance int, hasNoBanner bool) bool {
|
||||||
|
return !paidAccount && hintBalance <= 0 && !hasNoBanner
|
||||||
|
}
|
||||||
|
|
||||||
|
// computeActiveSet builds the resolved rotation feed from the enabled campaigns
|
||||||
|
// at time now, in language lang. Campaigns outside their validity window, and
|
||||||
|
// campaigns with no messages, are dropped. The default campaign's effective
|
||||||
|
// weight is the remainder up to 100% — max(0, 100 - sum of active timed
|
||||||
|
// weights) — so it fills unsold inventory and is dropped entirely when timed
|
||||||
|
// campaigns already reach 100%. Weights are then reduced by their GCD so the
|
||||||
|
// fair rotation cycle stays short. The input is expected to be the enabled
|
||||||
|
// campaigns (ActiveCampaigns); disabled ones must already be excluded.
|
||||||
|
func computeActiveSet(campaigns []Campaign, now time.Time, lang string) []ActiveCampaign {
|
||||||
|
var timed []Campaign
|
||||||
|
var def *Campaign
|
||||||
|
for i := range campaigns {
|
||||||
|
c := campaigns[i]
|
||||||
|
if len(c.Messages) == 0 {
|
||||||
|
continue // a campaign with no creative cannot fill a slot
|
||||||
|
}
|
||||||
|
if c.IsDefault {
|
||||||
|
def = &campaigns[i]
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if withinWindow(c, now) {
|
||||||
|
timed = append(timed, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sumTimed := 0
|
||||||
|
for _, c := range timed {
|
||||||
|
sumTimed += c.Weight
|
||||||
|
}
|
||||||
|
out := make([]ActiveCampaign, 0, len(timed)+1)
|
||||||
|
for _, c := range timed {
|
||||||
|
out = append(out, ActiveCampaign{Weight: c.Weight, Messages: resolveBodies(c.Messages, lang)})
|
||||||
|
}
|
||||||
|
if def != nil {
|
||||||
|
if dw := 100 - sumTimed; dw > 0 {
|
||||||
|
out = append(out, ActiveCampaign{Weight: dw, Messages: resolveBodies(def.Messages, lang)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reduceByGCD(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActiveAt reports whether the campaign would rotate at time now: enabled, and
|
||||||
|
// either the perpetual default or within its validity window. It mirrors the
|
||||||
|
// filter computeActiveSet applies (a campaign with no messages still reports
|
||||||
|
// active here — that is a content gap the console surfaces, not an inactive
|
||||||
|
// campaign).
|
||||||
|
func (c Campaign) ActiveAt(now time.Time) bool {
|
||||||
|
return c.Enabled && (c.IsDefault || withinWindow(c, now))
|
||||||
|
}
|
||||||
|
|
||||||
|
// withinWindow reports whether now lies inside the campaign's validity window. A
|
||||||
|
// nil bound is open-ended on that side.
|
||||||
|
func withinWindow(c Campaign, now time.Time) bool {
|
||||||
|
if c.StartsAt != nil && now.Before(*c.StartsAt) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if c.EndsAt != nil && now.After(*c.EndsAt) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveBodies projects each message to the body for lang ("ru" picks the
|
||||||
|
// Russian body; anything else picks English), preserving display order.
|
||||||
|
func resolveBodies(msgs []Message, lang string) []string {
|
||||||
|
out := make([]string, len(msgs))
|
||||||
|
for i, m := range msgs {
|
||||||
|
if lang == "ru" {
|
||||||
|
out[i] = m.BodyRu
|
||||||
|
} else {
|
||||||
|
out[i] = m.BodyEn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// reduceByGCD divides every weight by the greatest common divisor of all weights
|
||||||
|
// (in place), shrinking a {50,30,20} set to {5,3,2} and a lone {100} to {1}. A
|
||||||
|
// no-op when the set is empty or already coprime.
|
||||||
|
func reduceByGCD(cs []ActiveCampaign) {
|
||||||
|
g := 0
|
||||||
|
for _, c := range cs {
|
||||||
|
g = gcd(g, c.Weight)
|
||||||
|
}
|
||||||
|
if g <= 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i := range cs {
|
||||||
|
cs[i].Weight /= g
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// gcd returns the greatest common divisor of a and b (gcd(0, n) == n).
|
||||||
|
func gcd(a, b int) int {
|
||||||
|
for b != 0 {
|
||||||
|
a, b = b, a%b
|
||||||
|
}
|
||||||
|
if a < 0 {
|
||||||
|
return -a
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package ads
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEligible(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
paidAccount bool
|
||||||
|
hintBalance int
|
||||||
|
hasNoBanner bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "free, empty wallet, no role", want: true},
|
||||||
|
{name: "paid", paidAccount: true, want: false},
|
||||||
|
{name: "has hints", hintBalance: 3, want: false},
|
||||||
|
{name: "no_banner role", hasNoBanner: true, want: false},
|
||||||
|
{name: "paid and has hints", paidAccount: true, hintBalance: 5, want: false},
|
||||||
|
{name: "no_banner overrides everything", hasNoBanner: true, want: false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := Eligible(tt.paidAccount, tt.hintBalance, tt.hasNoBanner); got != tt.want {
|
||||||
|
t.Errorf("Eligible(%v,%d,%v) = %v, want %v", tt.paidAccount, tt.hintBalance, tt.hasNoBanner, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComputeActiveSet(t *testing.T) {
|
||||||
|
now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.UTC)
|
||||||
|
past := now.Add(-24 * time.Hour)
|
||||||
|
future := now.Add(24 * time.Hour)
|
||||||
|
|
||||||
|
// msg builds a one-message slice with distinct bodies so resolution and
|
||||||
|
// campaign identity are visible in assertions.
|
||||||
|
msg := func(tag string) []Message {
|
||||||
|
return []Message{{BodyEn: tag + "-en", BodyRu: tag + "-ru"}}
|
||||||
|
}
|
||||||
|
def := func(msgs []Message) Campaign {
|
||||||
|
return Campaign{Name: "default", Weight: 100, IsDefault: true, Enabled: true, Messages: msgs}
|
||||||
|
}
|
||||||
|
timed := func(name string, weight int, starts, ends *time.Time, msgs []Message) Campaign {
|
||||||
|
return Campaign{Name: name, Weight: weight, Enabled: true, StartsAt: starts, EndsAt: ends, Messages: msgs}
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
campaigns []Campaign
|
||||||
|
lang string
|
||||||
|
want []ActiveCampaign
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "default only reduces to weight 1",
|
||||||
|
campaigns: []Campaign{def(msg("house"))},
|
||||||
|
lang: "en",
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"house-en"}}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default fills the remainder",
|
||||||
|
campaigns: []Campaign{def(msg("house")), timed("promo", 30, nil, nil, msg("promo"))},
|
||||||
|
lang: "en",
|
||||||
|
// timed 30, default 100-30=70; gcd 10 -> 3 and 7; timed first, default last.
|
||||||
|
want: []ActiveCampaign{
|
||||||
|
{Weight: 3, Messages: []string{"promo-en"}},
|
||||||
|
{Weight: 7, Messages: []string{"house-en"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "timed fills 100, default dropped",
|
||||||
|
campaigns: []Campaign{def(msg("house")), timed("promo", 100, nil, nil, msg("promo"))},
|
||||||
|
lang: "en",
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"promo-en"}}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "timed over 100, default dropped, proportional",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def(msg("house")),
|
||||||
|
timed("a", 60, nil, nil, msg("a")),
|
||||||
|
timed("b", 80, nil, nil, msg("b")),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
// default dropped (sum 140 >= 100); gcd(60,80)=20 -> 3 and 4.
|
||||||
|
want: []ActiveCampaign{
|
||||||
|
{Weight: 3, Messages: []string{"a-en"}},
|
||||||
|
{Weight: 4, Messages: []string{"b-en"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "future and past windows exclude timed",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def(msg("house")),
|
||||||
|
timed("future", 50, &future, nil, msg("future")),
|
||||||
|
timed("past", 50, nil, &past, msg("past")),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"house-en"}}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "active window included",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def(msg("house")),
|
||||||
|
timed("live", 25, &past, &future, msg("live")),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
// timed 25, default 75; gcd 25 -> 1 and 3.
|
||||||
|
want: []ActiveCampaign{
|
||||||
|
{Weight: 1, Messages: []string{"live-en"}},
|
||||||
|
{Weight: 3, Messages: []string{"house-en"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "campaign without messages is skipped and not counted",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def(msg("house")),
|
||||||
|
timed("empty", 40, nil, nil, nil),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
// empty campaign skipped; default fills full 100 -> reduced to 1.
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"house-en"}}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "russian bodies resolved",
|
||||||
|
campaigns: []Campaign{def(msg("house"))},
|
||||||
|
lang: "ru",
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"house-ru"}}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "three timed split by gcd",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def(msg("house")),
|
||||||
|
timed("a", 50, nil, nil, msg("a")),
|
||||||
|
timed("b", 30, nil, nil, msg("b")),
|
||||||
|
timed("c", 20, nil, nil, msg("c")),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
// sum 100, default dropped; gcd 10 -> 5,3,2.
|
||||||
|
want: []ActiveCampaign{
|
||||||
|
{Weight: 5, Messages: []string{"a-en"}},
|
||||||
|
{Weight: 3, Messages: []string{"b-en"}},
|
||||||
|
{Weight: 2, Messages: []string{"c-en"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "campaign with multiple messages keeps order",
|
||||||
|
campaigns: []Campaign{
|
||||||
|
def([]Message{{BodyEn: "one-en", BodyRu: "one-ru"}, {BodyEn: "two-en", BodyRu: "two-ru"}}),
|
||||||
|
},
|
||||||
|
lang: "en",
|
||||||
|
want: []ActiveCampaign{{Weight: 1, Messages: []string{"one-en", "two-en"}}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := computeActiveSet(tt.campaigns, now, tt.lang)
|
||||||
|
if !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Errorf("computeActiveSet() =\n %#v\nwant\n %#v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComputeActiveSetEmpty(t *testing.T) {
|
||||||
|
// No campaigns at all yields an empty (non-nil-or-nil) feed without panicking.
|
||||||
|
if got := computeActiveSet(nil, time.Now(), "en"); len(got) != 0 {
|
||||||
|
t.Errorf("computeActiveSet(nil) = %#v, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGCD(t *testing.T) {
|
||||||
|
tests := []struct{ a, b, want int }{
|
||||||
|
{0, 5, 5}, {5, 0, 5}, {12, 18, 6}, {100, 100, 100}, {7, 13, 1},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := gcd(tt.a, tt.b); got != tt.want {
|
||||||
|
t.Errorf("gcd(%d,%d) = %d, want %d", tt.a, tt.b, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
package ads
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Operator-input bounds and the display-timing clamps. The timings are clamped
|
||||||
|
// (not rejected) on update so the client rotator can never be driven into a
|
||||||
|
// broken state by a typo in the console.
|
||||||
|
const (
|
||||||
|
maxCampaignName = 80
|
||||||
|
maxMessageBody = 500
|
||||||
|
|
||||||
|
minHoldMs = 3000 // 3s — below this the fade transition would dominate
|
||||||
|
maxHoldMs = 600000 // 10 min
|
||||||
|
|
||||||
|
maxEdgePauseMs = 60000
|
||||||
|
|
||||||
|
minScrollPxPerSec = 5
|
||||||
|
maxScrollPxPerSec = 1000
|
||||||
|
|
||||||
|
maxFadeMs = 5000
|
||||||
|
)
|
||||||
|
|
||||||
|
// Service is the domain layer over Store: it validates operator input, enforces
|
||||||
|
// the default campaign's invariants, clamps the display timings, and assembles
|
||||||
|
// the resolved rotation feed (ActiveSet) for a viewer.
|
||||||
|
type Service struct {
|
||||||
|
store *Store
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewService constructs a Service over store.
|
||||||
|
func NewService(store *Store) *Service { return &Service{store: store} }
|
||||||
|
|
||||||
|
// ActiveSet returns the resolved rotation feed for a viewer in language lang
|
||||||
|
// (en/ru) together with the global display timings: the currently-active
|
||||||
|
// campaigns, each with its GCD-reduced show weight and its messages resolved to
|
||||||
|
// lang, ready for the client's weighted round-robin.
|
||||||
|
func (s *Service) ActiveSet(ctx context.Context, lang string) ([]ActiveCampaign, Timings, error) {
|
||||||
|
campaigns, err := s.store.ActiveCampaigns(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, Timings{}, err
|
||||||
|
}
|
||||||
|
timings, err := s.store.Settings(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, Timings{}, err
|
||||||
|
}
|
||||||
|
return computeActiveSet(campaigns, time.Now().UTC(), lang), timings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListCampaigns returns every campaign with its messages, for the admin console.
|
||||||
|
func (s *Service) ListCampaigns(ctx context.Context) ([]Campaign, error) {
|
||||||
|
return s.store.ListCampaigns(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Campaign returns one campaign with its messages, or ErrNotFound.
|
||||||
|
func (s *Service) Campaign(ctx context.Context, id uuid.UUID) (Campaign, error) {
|
||||||
|
return s.store.Campaign(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCampaign validates and creates a new time-limited campaign (never the
|
||||||
|
// default) and returns its id.
|
||||||
|
func (s *Service) CreateCampaign(ctx context.Context, c Campaign) (uuid.UUID, error) {
|
||||||
|
name, err := validName(c.Name)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
if err := validWeight(c.Weight); err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
if err := validWindow(c.StartsAt, c.EndsAt); err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
return s.store.CreateCampaign(ctx, Campaign{
|
||||||
|
Name: name, Weight: c.Weight, Enabled: c.Enabled, StartsAt: c.StartsAt, EndsAt: c.EndsAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCampaign validates and updates a campaign. The default campaign keeps its
|
||||||
|
// weight (nominal), enabled flag and (empty) window — only its name is editable;
|
||||||
|
// any submitted weight/window/enabled are ignored for it.
|
||||||
|
func (s *Service) UpdateCampaign(ctx context.Context, c Campaign) error {
|
||||||
|
existing, err := s.store.Campaign(ctx, c.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
name, err := validName(c.Name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
upd := Campaign{ID: existing.ID, Name: name}
|
||||||
|
if existing.IsDefault {
|
||||||
|
upd.Weight = existing.Weight
|
||||||
|
upd.Enabled = true
|
||||||
|
upd.StartsAt = nil
|
||||||
|
upd.EndsAt = nil
|
||||||
|
} else {
|
||||||
|
if err := validWeight(c.Weight); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := validWindow(c.StartsAt, c.EndsAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
upd.Weight = c.Weight
|
||||||
|
upd.Enabled = c.Enabled
|
||||||
|
upd.StartsAt = c.StartsAt
|
||||||
|
upd.EndsAt = c.EndsAt
|
||||||
|
}
|
||||||
|
return s.store.UpdateCampaign(ctx, upd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCampaign removes a campaign, refusing the perpetual default.
|
||||||
|
func (s *Service) DeleteCampaign(ctx context.Context, id uuid.UUID) error {
|
||||||
|
existing, err := s.store.Campaign(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existing.IsDefault {
|
||||||
|
return ErrDefaultImmutable
|
||||||
|
}
|
||||||
|
return s.store.DeleteCampaign(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMessage validates a bilingual message and appends it to a campaign.
|
||||||
|
func (s *Service) AddMessage(ctx context.Context, campaignID uuid.UUID, bodyEn, bodyRu string) (uuid.UUID, error) {
|
||||||
|
en, ru, err := validBodies(bodyEn, bodyRu)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
c, err := s.store.Campaign(ctx, campaignID)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, err
|
||||||
|
}
|
||||||
|
return s.store.AddMessage(ctx, Message{CampaignID: campaignID, Position: len(c.Messages), BodyEn: en, BodyRu: ru})
|
||||||
|
}
|
||||||
|
|
||||||
|
// EditMessage validates and updates the bilingual bodies of a message that
|
||||||
|
// belongs to campaignID (its position is unchanged). It returns ErrNotFound when
|
||||||
|
// the message is not part of that campaign, so a mismatched campaign/message pair
|
||||||
|
// never edits an unrelated campaign's message.
|
||||||
|
func (s *Service) EditMessage(ctx context.Context, campaignID, messageID uuid.UUID, bodyEn, bodyRu string) error {
|
||||||
|
en, ru, err := validBodies(bodyEn, bodyRu)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c, err := s.store.Campaign(ctx, campaignID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !campaignOwnsMessage(c, messageID) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return s.store.UpdateMessageBodies(ctx, messageID, en, ru)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MoveMessage reorders a message within its campaign by swapping its position
|
||||||
|
// with the adjacent message in direction dir (-1 up, +1 down). A move past an
|
||||||
|
// edge is a no-op.
|
||||||
|
func (s *Service) MoveMessage(ctx context.Context, campaignID, messageID uuid.UUID, dir int) error {
|
||||||
|
c, err := s.store.Campaign(ctx, campaignID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
idx := -1
|
||||||
|
for i, m := range c.Messages {
|
||||||
|
if m.ID == messageID {
|
||||||
|
idx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx < 0 {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
j := idx + dir
|
||||||
|
if j < 0 || j >= len(c.Messages) {
|
||||||
|
return nil // already at the edge
|
||||||
|
}
|
||||||
|
a, b := c.Messages[idx], c.Messages[j]
|
||||||
|
if err := s.store.SetMessagePosition(ctx, a.ID, j); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.store.SetMessagePosition(ctx, b.ID, idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteMessage removes a message that belongs to campaignID, refusing to remove
|
||||||
|
// the default campaign's last remaining message (the default must always have a
|
||||||
|
// creative to show). It returns ErrNotFound when the message is not part of that
|
||||||
|
// campaign — so a mismatched campaign/message pair can neither delete an
|
||||||
|
// unrelated campaign's message nor bypass the default's last-message guard.
|
||||||
|
func (s *Service) DeleteMessage(ctx context.Context, campaignID, messageID uuid.UUID) error {
|
||||||
|
c, err := s.store.Campaign(ctx, campaignID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !campaignOwnsMessage(c, messageID) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
if c.IsDefault && len(c.Messages) <= 1 {
|
||||||
|
return fmt.Errorf("%w: the default campaign must keep at least one message", ErrValidation)
|
||||||
|
}
|
||||||
|
return s.store.DeleteMessage(ctx, messageID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// campaignOwnsMessage reports whether messageID is one of the campaign's messages.
|
||||||
|
func campaignOwnsMessage(c Campaign, messageID uuid.UUID) bool {
|
||||||
|
for _, m := range c.Messages {
|
||||||
|
if m.ID == messageID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings returns the global display timings.
|
||||||
|
func (s *Service) Settings(ctx context.Context) (Timings, error) {
|
||||||
|
return s.store.Settings(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettings clamps every timing into its safe range and stores them.
|
||||||
|
func (s *Service) UpdateSettings(ctx context.Context, t Timings) error {
|
||||||
|
return s.store.UpdateSettings(ctx, clampTimings(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
// validName trims and bounds a campaign name.
|
||||||
|
func validName(name string) (string, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
return "", fmt.Errorf("%w: the campaign name is required", ErrValidation)
|
||||||
|
}
|
||||||
|
if len([]rune(name)) > maxCampaignName {
|
||||||
|
return "", fmt.Errorf("%w: the campaign name must be at most %d characters", ErrValidation, maxCampaignName)
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validWeight bounds a campaign show weight to the 1..100 percent range.
|
||||||
|
func validWeight(w int) error {
|
||||||
|
if w < 1 || w > 100 {
|
||||||
|
return fmt.Errorf("%w: the weight must be a percent between 1 and 100", ErrValidation)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validWindow rejects an inverted validity window.
|
||||||
|
func validWindow(starts, ends *time.Time) error {
|
||||||
|
if starts != nil && ends != nil && ends.Before(*starts) {
|
||||||
|
return fmt.Errorf("%w: the end must not precede the start", ErrValidation)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validBodies trims and bounds both mandatory language bodies of a message.
|
||||||
|
func validBodies(bodyEn, bodyRu string) (string, string, error) {
|
||||||
|
en := strings.TrimSpace(bodyEn)
|
||||||
|
ru := strings.TrimSpace(bodyRu)
|
||||||
|
if en == "" || ru == "" {
|
||||||
|
return "", "", fmt.Errorf("%w: both the English and Russian message bodies are required", ErrValidation)
|
||||||
|
}
|
||||||
|
if len([]rune(en)) > maxMessageBody || len([]rune(ru)) > maxMessageBody {
|
||||||
|
return "", "", fmt.Errorf("%w: a message body must be at most %d characters", ErrValidation, maxMessageBody)
|
||||||
|
}
|
||||||
|
return en, ru, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// clampTimings forces every display timing into its safe range.
|
||||||
|
func clampTimings(t Timings) Timings {
|
||||||
|
return Timings{
|
||||||
|
HoldMs: clampInt(t.HoldMs, minHoldMs, maxHoldMs),
|
||||||
|
EdgePauseMs: clampInt(t.EdgePauseMs, 0, maxEdgePauseMs),
|
||||||
|
ScrollPxPerSec: clampInt(t.ScrollPxPerSec, minScrollPxPerSec, maxScrollPxPerSec),
|
||||||
|
FadeOutMs: clampInt(t.FadeOutMs, 0, maxFadeMs),
|
||||||
|
GapMs: clampInt(t.GapMs, 0, maxFadeMs),
|
||||||
|
FadeInMs: clampInt(t.FadeInMs, 0, maxFadeMs),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clampInt(v, lo, hi int) int {
|
||||||
|
if v < lo {
|
||||||
|
return lo
|
||||||
|
}
|
||||||
|
if v > hi {
|
||||||
|
return hi
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
package ads
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-jet/jet/v2/postgres"
|
||||||
|
"github.com/go-jet/jet/v2/qrm"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||||
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store is the Postgres-backed query surface for advertising campaigns, their
|
||||||
|
// messages and the single global display-settings row.
|
||||||
|
type Store struct {
|
||||||
|
db *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStore constructs a Store wrapping db.
|
||||||
|
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
|
||||||
|
|
||||||
|
// ListCampaigns returns every campaign with its messages, the default first then
|
||||||
|
// by creation time, for the admin console.
|
||||||
|
func (s *Store) ListCampaigns(ctx context.Context) ([]Campaign, error) {
|
||||||
|
return s.loadCampaigns(ctx, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActiveCampaigns returns the enabled campaigns with their messages, the default
|
||||||
|
// first then by creation time. Window filtering and the default-remainder weight
|
||||||
|
// are applied by the Service (ActiveSet), not here.
|
||||||
|
func (s *Store) ActiveCampaigns(ctx context.Context) ([]Campaign, error) {
|
||||||
|
return s.loadCampaigns(ctx, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadCampaigns reads campaigns (optionally only the enabled ones) and attaches
|
||||||
|
// each one's messages in display order, with a single messages query (the table
|
||||||
|
// is small, so this avoids both an N+1 and a join projection).
|
||||||
|
func (s *Store) loadCampaigns(ctx context.Context, enabledOnly bool) ([]Campaign, error) {
|
||||||
|
sel := postgres.SELECT(table.AdCampaigns.AllColumns).FROM(table.AdCampaigns)
|
||||||
|
if enabledOnly {
|
||||||
|
sel = sel.WHERE(table.AdCampaigns.Enabled.EQ(postgres.Bool(true)))
|
||||||
|
}
|
||||||
|
sel = sel.ORDER_BY(table.AdCampaigns.IsDefault.DESC(), table.AdCampaigns.CreatedAt.ASC())
|
||||||
|
|
||||||
|
var rows []model.AdCampaigns
|
||||||
|
if err := sel.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return nil, fmt.Errorf("ads: list campaigns: %w", err)
|
||||||
|
}
|
||||||
|
byID, err := s.messagesByCampaign(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]Campaign, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
c := modelToCampaign(r)
|
||||||
|
c.Messages = byID[r.CampaignID]
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Campaign returns one campaign with its messages, or ErrNotFound.
|
||||||
|
func (s *Store) Campaign(ctx context.Context, id uuid.UUID) (Campaign, error) {
|
||||||
|
sel := postgres.SELECT(table.AdCampaigns.AllColumns).
|
||||||
|
FROM(table.AdCampaigns).
|
||||||
|
WHERE(table.AdCampaigns.CampaignID.EQ(postgres.UUID(id))).
|
||||||
|
LIMIT(1)
|
||||||
|
var row model.AdCampaigns
|
||||||
|
if err := sel.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return Campaign{}, ErrNotFound
|
||||||
|
}
|
||||||
|
return Campaign{}, fmt.Errorf("ads: get campaign %s: %w", id, err)
|
||||||
|
}
|
||||||
|
c := modelToCampaign(row)
|
||||||
|
msgs, err := s.messagesFor(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return Campaign{}, err
|
||||||
|
}
|
||||||
|
c.Messages = msgs
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCampaign inserts a campaign (always non-default) and returns its new id.
|
||||||
|
func (s *Store) CreateCampaign(ctx context.Context, c Campaign) (uuid.UUID, error) {
|
||||||
|
id := uuid.New()
|
||||||
|
now := time.Now().UTC()
|
||||||
|
stmt := table.AdCampaigns.INSERT(
|
||||||
|
table.AdCampaigns.CampaignID, table.AdCampaigns.Name, table.AdCampaigns.Weight,
|
||||||
|
table.AdCampaigns.IsDefault, table.AdCampaigns.Enabled,
|
||||||
|
table.AdCampaigns.StartsAt, table.AdCampaigns.EndsAt,
|
||||||
|
table.AdCampaigns.CreatedAt, table.AdCampaigns.UpdatedAt,
|
||||||
|
).VALUES(
|
||||||
|
postgres.UUID(id), postgres.String(c.Name), postgres.Int(int64(c.Weight)),
|
||||||
|
postgres.Bool(false), postgres.Bool(c.Enabled),
|
||||||
|
tsOrNull(c.StartsAt), tsOrNull(c.EndsAt),
|
||||||
|
postgres.TimestampzT(now), postgres.TimestampzT(now),
|
||||||
|
)
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("ads: create campaign: %w", err)
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCampaign updates a campaign's name, weight, enabled flag and validity
|
||||||
|
// window. The default flag is never touched here. Returns ErrNotFound when no
|
||||||
|
// campaign matches.
|
||||||
|
func (s *Store) UpdateCampaign(ctx context.Context, c Campaign) error {
|
||||||
|
stmt := table.AdCampaigns.UPDATE(
|
||||||
|
table.AdCampaigns.Name, table.AdCampaigns.Weight, table.AdCampaigns.Enabled,
|
||||||
|
table.AdCampaigns.StartsAt, table.AdCampaigns.EndsAt, table.AdCampaigns.UpdatedAt,
|
||||||
|
).SET(
|
||||||
|
postgres.String(c.Name), postgres.Int(int64(c.Weight)), postgres.Bool(c.Enabled),
|
||||||
|
tsOrNull(c.StartsAt), tsOrNull(c.EndsAt), postgres.TimestampzT(time.Now().UTC()),
|
||||||
|
).WHERE(table.AdCampaigns.CampaignID.EQ(postgres.UUID(c.ID)))
|
||||||
|
return execOne(ctx, s.db, stmt, "update campaign")
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCampaign removes a campaign (its messages cascade). Returns ErrNotFound
|
||||||
|
// when no campaign matches. The Service refuses to delete the default.
|
||||||
|
func (s *Store) DeleteCampaign(ctx context.Context, id uuid.UUID) error {
|
||||||
|
stmt := table.AdCampaigns.DELETE().WHERE(table.AdCampaigns.CampaignID.EQ(postgres.UUID(id)))
|
||||||
|
return execOne(ctx, s.db, stmt, "delete campaign")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMessage inserts a message into a campaign and returns its new id.
|
||||||
|
func (s *Store) AddMessage(ctx context.Context, m Message) (uuid.UUID, error) {
|
||||||
|
id := uuid.New()
|
||||||
|
now := time.Now().UTC()
|
||||||
|
stmt := table.AdMessages.INSERT(
|
||||||
|
table.AdMessages.MessageID, table.AdMessages.CampaignID, table.AdMessages.Position,
|
||||||
|
table.AdMessages.BodyEn, table.AdMessages.BodyRu,
|
||||||
|
table.AdMessages.CreatedAt, table.AdMessages.UpdatedAt,
|
||||||
|
).VALUES(
|
||||||
|
postgres.UUID(id), postgres.UUID(m.CampaignID), postgres.Int(int64(m.Position)),
|
||||||
|
postgres.String(m.BodyEn), postgres.String(m.BodyRu),
|
||||||
|
postgres.TimestampzT(now), postgres.TimestampzT(now),
|
||||||
|
)
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("ads: add message: %w", err)
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateMessageBodies updates a message's bilingual bodies (its position is
|
||||||
|
// unchanged). Returns ErrNotFound when no message matches.
|
||||||
|
func (s *Store) UpdateMessageBodies(ctx context.Context, id uuid.UUID, bodyEn, bodyRu string) error {
|
||||||
|
stmt := table.AdMessages.UPDATE(
|
||||||
|
table.AdMessages.BodyEn, table.AdMessages.BodyRu, table.AdMessages.UpdatedAt,
|
||||||
|
).SET(
|
||||||
|
postgres.String(bodyEn), postgres.String(bodyRu), postgres.TimestampzT(time.Now().UTC()),
|
||||||
|
).WHERE(table.AdMessages.MessageID.EQ(postgres.UUID(id)))
|
||||||
|
return execOne(ctx, s.db, stmt, "update message")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMessagePosition updates only a message's position (used to reorder).
|
||||||
|
func (s *Store) SetMessagePosition(ctx context.Context, id uuid.UUID, position int) error {
|
||||||
|
stmt := table.AdMessages.UPDATE(table.AdMessages.Position, table.AdMessages.UpdatedAt).
|
||||||
|
SET(postgres.Int(int64(position)), postgres.TimestampzT(time.Now().UTC())).
|
||||||
|
WHERE(table.AdMessages.MessageID.EQ(postgres.UUID(id)))
|
||||||
|
return execOne(ctx, s.db, stmt, "reorder message")
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteMessage removes a message. Returns ErrNotFound when no message matches.
|
||||||
|
func (s *Store) DeleteMessage(ctx context.Context, id uuid.UUID) error {
|
||||||
|
stmt := table.AdMessages.DELETE().WHERE(table.AdMessages.MessageID.EQ(postgres.UUID(id)))
|
||||||
|
return execOne(ctx, s.db, stmt, "delete message")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings returns the global display timings.
|
||||||
|
func (s *Store) Settings(ctx context.Context) (Timings, error) {
|
||||||
|
sel := postgres.SELECT(table.AdSettings.AllColumns).FROM(table.AdSettings).LIMIT(1)
|
||||||
|
var row model.AdSettings
|
||||||
|
if err := sel.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
return Timings{}, fmt.Errorf("ads: get settings: %w", err)
|
||||||
|
}
|
||||||
|
return Timings{
|
||||||
|
HoldMs: int(row.HoldMs),
|
||||||
|
EdgePauseMs: int(row.EdgePauseMs),
|
||||||
|
ScrollPxPerSec: int(row.ScrollPxPerSec),
|
||||||
|
FadeOutMs: int(row.FadeOutMs),
|
||||||
|
GapMs: int(row.GapMs),
|
||||||
|
FadeInMs: int(row.FadeInMs),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettings overwrites the single global display-settings row.
|
||||||
|
func (s *Store) UpdateSettings(ctx context.Context, t Timings) error {
|
||||||
|
stmt := table.AdSettings.UPDATE(
|
||||||
|
table.AdSettings.HoldMs, table.AdSettings.EdgePauseMs, table.AdSettings.ScrollPxPerSec,
|
||||||
|
table.AdSettings.FadeOutMs, table.AdSettings.GapMs, table.AdSettings.FadeInMs, table.AdSettings.UpdatedAt,
|
||||||
|
).SET(
|
||||||
|
postgres.Int(int64(t.HoldMs)), postgres.Int(int64(t.EdgePauseMs)), postgres.Int(int64(t.ScrollPxPerSec)),
|
||||||
|
postgres.Int(int64(t.FadeOutMs)), postgres.Int(int64(t.GapMs)), postgres.Int(int64(t.FadeInMs)),
|
||||||
|
postgres.TimestampzT(time.Now().UTC()),
|
||||||
|
).WHERE(table.AdSettings.ID.EQ(postgres.Bool(true)))
|
||||||
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
|
return fmt.Errorf("ads: update settings: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// messagesByCampaign loads every message grouped by campaign id, in display order.
|
||||||
|
func (s *Store) messagesByCampaign(ctx context.Context) (map[uuid.UUID][]Message, error) {
|
||||||
|
sel := postgres.SELECT(table.AdMessages.AllColumns).
|
||||||
|
FROM(table.AdMessages).
|
||||||
|
ORDER_BY(table.AdMessages.CampaignID.ASC(), table.AdMessages.Position.ASC(), table.AdMessages.CreatedAt.ASC())
|
||||||
|
var rows []model.AdMessages
|
||||||
|
if err := sel.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return nil, fmt.Errorf("ads: list messages: %w", err)
|
||||||
|
}
|
||||||
|
out := make(map[uuid.UUID][]Message, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.CampaignID] = append(out[r.CampaignID], modelToMessage(r))
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// messagesFor loads one campaign's messages in display order.
|
||||||
|
func (s *Store) messagesFor(ctx context.Context, campaignID uuid.UUID) ([]Message, error) {
|
||||||
|
sel := postgres.SELECT(table.AdMessages.AllColumns).
|
||||||
|
FROM(table.AdMessages).
|
||||||
|
WHERE(table.AdMessages.CampaignID.EQ(postgres.UUID(campaignID))).
|
||||||
|
ORDER_BY(table.AdMessages.Position.ASC(), table.AdMessages.CreatedAt.ASC())
|
||||||
|
var rows []model.AdMessages
|
||||||
|
if err := sel.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return nil, fmt.Errorf("ads: list messages for %s: %w", campaignID, err)
|
||||||
|
}
|
||||||
|
out := make([]Message, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out = append(out, modelToMessage(r))
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// execOne runs a statement expected to touch exactly one row, mapping a zero
|
||||||
|
// row-count to ErrNotFound.
|
||||||
|
func execOne(ctx context.Context, db qrm.Executable, stmt postgres.Statement, what string) error {
|
||||||
|
res, err := stmt.ExecContext(ctx, db)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("ads: %s: %w", what, err)
|
||||||
|
}
|
||||||
|
n, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("ads: %s rows: %w", what, err)
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func modelToCampaign(r model.AdCampaigns) Campaign {
|
||||||
|
return Campaign{
|
||||||
|
ID: r.CampaignID,
|
||||||
|
Name: r.Name,
|
||||||
|
Weight: int(r.Weight),
|
||||||
|
IsDefault: r.IsDefault,
|
||||||
|
Enabled: r.Enabled,
|
||||||
|
StartsAt: r.StartsAt,
|
||||||
|
EndsAt: r.EndsAt,
|
||||||
|
CreatedAt: r.CreatedAt,
|
||||||
|
UpdatedAt: r.UpdatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func modelToMessage(r model.AdMessages) Message {
|
||||||
|
return Message{
|
||||||
|
ID: r.MessageID,
|
||||||
|
CampaignID: r.CampaignID,
|
||||||
|
Position: int(r.Position),
|
||||||
|
BodyEn: r.BodyEn,
|
||||||
|
BodyRu: r.BodyRu,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tsOrNull renders a nullable validity-window bound: NULL for a nil pointer,
|
||||||
|
// otherwise the UTC timestamp.
|
||||||
|
func tsOrNull(t *time.Time) postgres.Expression {
|
||||||
|
if t == nil {
|
||||||
|
return postgres.NULL
|
||||||
|
}
|
||||||
|
return postgres.TimestampzT(t.UTC())
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// Package banview mirrors the gateway's active IP bans for the admin console and
|
||||||
|
// collects operator unban requests for the gateway to apply. Like ratewatch it is
|
||||||
|
// in-memory, single-instance and resets on a backend restart by design — the
|
||||||
|
// gateway re-reports its active set on the next sync, and the durable effect (the
|
||||||
|
// ban itself) lives in the gateway, not here.
|
||||||
|
package banview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Ban is one active IP ban as reported by the gateway.
|
||||||
|
type Ban struct {
|
||||||
|
IP string
|
||||||
|
Reason string
|
||||||
|
Since time.Time
|
||||||
|
Expires time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// View holds the last-reported active bans and the operator's pending unbans.
|
||||||
|
type View struct {
|
||||||
|
now func() time.Time
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
bans map[string]Ban // last reported active set, keyed by IP
|
||||||
|
unban map[string]struct{} // IPs an operator marked for unban
|
||||||
|
}
|
||||||
|
|
||||||
|
// New constructs an empty View.
|
||||||
|
func New() *View {
|
||||||
|
return &View{now: time.Now, bans: make(map[string]Ban), unban: make(map[string]struct{})}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ingest replaces the mirrored active set with the gateway's latest report,
|
||||||
|
// skipping entries with an empty IP or one that has already expired.
|
||||||
|
func (v *View) Ingest(active []Ban) {
|
||||||
|
now := v.now()
|
||||||
|
v.mu.Lock()
|
||||||
|
defer v.mu.Unlock()
|
||||||
|
v.bans = make(map[string]Ban, len(active))
|
||||||
|
for _, b := range active {
|
||||||
|
if b.IP == "" || !now.Before(b.Expires) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
v.bans[b.IP] = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recent returns the mirrored active bans, most recently banned first.
|
||||||
|
func (v *View) Recent() []Ban {
|
||||||
|
now := v.now()
|
||||||
|
v.mu.Lock()
|
||||||
|
defer v.mu.Unlock()
|
||||||
|
out := make([]Ban, 0, len(v.bans))
|
||||||
|
for _, b := range v.bans {
|
||||||
|
if now.Before(b.Expires) {
|
||||||
|
out = append(out, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return out[i].Since.After(out[j].Since) })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestUnban records an operator request to lift the ban on ip; the gateway
|
||||||
|
// applies it on its next sync (so the console reflects it within the sync
|
||||||
|
// interval). An empty ip is ignored.
|
||||||
|
func (v *View) RequestUnban(ip string) {
|
||||||
|
if ip == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
v.mu.Lock()
|
||||||
|
defer v.mu.Unlock()
|
||||||
|
v.unban[ip] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrainUnbans returns and clears the IPs operators have marked for unban since the
|
||||||
|
// previous drain. It returns nil when there are none.
|
||||||
|
func (v *View) DrainUnbans() []string {
|
||||||
|
v.mu.Lock()
|
||||||
|
defer v.mu.Unlock()
|
||||||
|
if len(v.unban) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(v.unban))
|
||||||
|
for ip := range v.unban {
|
||||||
|
out = append(out, ip)
|
||||||
|
}
|
||||||
|
clear(v.unban)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package banview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func viewAt(clk *time.Time) *View {
|
||||||
|
v := New()
|
||||||
|
v.now = func() time.Time { return *clk }
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIngestRecentDropsExpired(t *testing.T) {
|
||||||
|
clk := time.Date(2026, 6, 21, 12, 0, 0, 0, time.UTC)
|
||||||
|
v := viewAt(&clk)
|
||||||
|
v.Ingest([]Ban{
|
||||||
|
{IP: "1.1.1.1", Reason: "tripwire", Since: clk, Expires: clk.Add(time.Hour)},
|
||||||
|
{IP: "2.2.2.2", Reason: "rejections", Since: clk.Add(-2 * time.Hour), Expires: clk.Add(-time.Hour)}, // expired
|
||||||
|
{IP: "", Reason: "x", Since: clk, Expires: clk.Add(time.Hour)}, // empty IP
|
||||||
|
})
|
||||||
|
got := v.Recent()
|
||||||
|
if len(got) != 1 || got[0].IP != "1.1.1.1" || got[0].Reason != "tripwire" {
|
||||||
|
t.Fatalf("Recent = %+v, want one live ban for 1.1.1.1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIngestReplaces(t *testing.T) {
|
||||||
|
clk := time.Date(2026, 6, 21, 12, 0, 0, 0, time.UTC)
|
||||||
|
v := viewAt(&clk)
|
||||||
|
v.Ingest([]Ban{{IP: "1.1.1.1", Since: clk, Expires: clk.Add(time.Hour)}})
|
||||||
|
v.Ingest([]Ban{{IP: "2.2.2.2", Since: clk, Expires: clk.Add(time.Hour)}})
|
||||||
|
got := v.Recent()
|
||||||
|
if len(got) != 1 || got[0].IP != "2.2.2.2" {
|
||||||
|
t.Fatalf("Recent = %+v, want only the latest report (2.2.2.2)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecentOrdersBySince(t *testing.T) {
|
||||||
|
clk := time.Date(2026, 6, 21, 12, 0, 0, 0, time.UTC)
|
||||||
|
v := viewAt(&clk)
|
||||||
|
v.Ingest([]Ban{
|
||||||
|
{IP: "old", Since: clk.Add(-10 * time.Minute), Expires: clk.Add(time.Hour)},
|
||||||
|
{IP: "new", Since: clk.Add(-1 * time.Minute), Expires: clk.Add(time.Hour)},
|
||||||
|
})
|
||||||
|
got := v.Recent()
|
||||||
|
if len(got) != 2 || got[0].IP != "new" || got[1].IP != "old" {
|
||||||
|
t.Fatalf("Recent order = %+v, want most recent first", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnbanRoundTrip(t *testing.T) {
|
||||||
|
clk := time.Date(2026, 6, 21, 12, 0, 0, 0, time.UTC)
|
||||||
|
v := viewAt(&clk)
|
||||||
|
v.RequestUnban("3.3.3.3")
|
||||||
|
v.RequestUnban("") // ignored
|
||||||
|
drained := v.DrainUnbans()
|
||||||
|
if len(drained) != 1 || drained[0] != "3.3.3.3" {
|
||||||
|
t.Fatalf("DrainUnbans = %v, want [3.3.3.3]", drained)
|
||||||
|
}
|
||||||
|
if again := v.DrainUnbans(); again != nil {
|
||||||
|
t.Fatalf("second DrainUnbans = %v, want nil (cleared)", again)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
// Package connector is the backend's gRPC client for the Telegram platform
|
// Package connector is the backend's gRPC client for operator broadcasts: a direct
|
||||||
// connector side-service. The admin console uses it to send operator broadcasts:
|
// message to one user, or a post to the game channel. It calls the gateway's
|
||||||
// a direct message to one user, or a post to a game channel. Each broadcast
|
// bot-link relay (which forwards the send to the remote bot over the reverse mTLS
|
||||||
// selects the delivering bot by language (an operator choice, since the connector
|
// link and reports back whether it was delivered). The relay lives on the trusted
|
||||||
// hosts one bot per service language). The connector lives on the trusted internal
|
// internal network, so the connection uses insecure (plaintext) transport
|
||||||
// network, so the connection uses insecure (plaintext) transport credentials
|
// credentials (docs/ARCHITECTURE.md §12). It speaks the Telegram service contract,
|
||||||
// (docs/ARCHITECTURE.md §12). It mirrors gateway/internal/connector, narrowed to
|
// narrowed to the two broadcast methods the admin surface needs.
|
||||||
// the two broadcast methods the admin surface needs.
|
|
||||||
package connector
|
package connector
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -37,22 +36,21 @@ func New(addr string) (*Client, error) {
|
|||||||
func (c *Client) Close() error { return c.conn.Close() }
|
func (c *Client) Close() error { return c.conn.Close() }
|
||||||
|
|
||||||
// SendToUser sends an operator text message to one user, addressed by their
|
// SendToUser sends an operator text message to one user, addressed by their
|
||||||
// platform external_id, through the bot for the given language. delivered reports
|
// platform external_id, through the bot. delivered reports whether the connector
|
||||||
// whether the connector actually sent it (false when the user has not started that
|
// actually sent it (false when the user has not started the bot).
|
||||||
// bot).
|
func (c *Client) SendToUser(ctx context.Context, externalID, text string) (bool, error) {
|
||||||
func (c *Client) SendToUser(ctx context.Context, externalID, text, language string) (bool, error) {
|
resp, err := c.c.SendToUser(ctx, &telegramv1.SendToUserRequest{ExternalId: externalID, Text: text})
|
||||||
resp, err := c.c.SendToUser(ctx, &telegramv1.SendToUserRequest{ExternalId: externalID, Text: text, Language: language})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
return resp.GetDelivered(), nil
|
return resp.GetDelivered(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendToGameChannel posts an operator text message to the game channel of the bot
|
// SendToGameChannel posts an operator text message to the bot's game channel.
|
||||||
// for the given language. delivered reports whether the connector sent it (false
|
// delivered reports whether the connector sent it (false when the bot has no
|
||||||
// when that bot has no channel configured).
|
// channel configured).
|
||||||
func (c *Client) SendToGameChannel(ctx context.Context, text, language string) (bool, error) {
|
func (c *Client) SendToGameChannel(ctx context.Context, text string) (bool, error) {
|
||||||
resp, err := c.c.SendToGameChannel(ctx, &telegramv1.SendToGameChannelRequest{Text: text, Language: language})
|
resp, err := c.c.SendToGameChannel(ctx, &telegramv1.SendToGameChannelRequest{Text: text})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,11 +70,21 @@ func Open(dir, version string, variants ...Variant) (*Registry, error) {
|
|||||||
// immediate subdirectory of dir: a subdirectory named V contributes, under
|
// immediate subdirectory of dir: a subdirectory named V contributes, under
|
||||||
// version V, the variants whose committed DAWG it carries. This is the
|
// version V, the variants whose committed DAWG it carries. This is the
|
||||||
// restart-side of the admin dictionary reload — a version reloaded into dir/<V>/
|
// restart-side of the admin dictionary reload — a version reloaded into dir/<V>/
|
||||||
// at runtime is resident again after a restart. A subdirectory named like the
|
// at runtime is resident again after a restart. The flat dir's version is resolved
|
||||||
// boot version is skipped (the flat dir already is the boot version). A partially
|
// from its .seed_version marker (see resolveSeedVersion): a fresh dir records
|
||||||
// loaded registry is closed before any error is returned.
|
// bootVersion, an already-seeded dir keeps its recorded label and ignores bootVersion,
|
||||||
|
// so a bumped build seed never relabels live bytes. A subdirectory named like the
|
||||||
|
// resolved seed version is skipped (the flat dir already is it). A partially loaded
|
||||||
|
// registry is closed before any error is returned.
|
||||||
func OpenWithVersions(dir, bootVersion string) (*Registry, error) {
|
func OpenWithVersions(dir, bootVersion string) (*Registry, error) {
|
||||||
r, err := Open(dir, bootVersion)
|
// Resolve the flat dir's version from its seed marker first: on an already-seeded
|
||||||
|
// volume the marker wins and bootVersion is ignored, so a bumped build seed cannot
|
||||||
|
// relabel live bytes (see resolveSeedVersion).
|
||||||
|
seed, err := resolveSeedVersion(dir, bootVersion)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
r, err := Open(dir, seed)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -84,9 +94,9 @@ func OpenWithVersions(dir, bootVersion string) (*Registry, error) {
|
|||||||
return nil, fmt.Errorf("engine: scan dictionary dir %s: %w", dir, err)
|
return nil, fmt.Errorf("engine: scan dictionary dir %s: %w", dir, err)
|
||||||
}
|
}
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
// Skip non-directories, the boot version (already loaded as the flat dir)
|
// Skip non-directories, the resolved seed version (already loaded as the flat
|
||||||
// and dot-prefixed directories (the upload staging area, dir/.staging/).
|
// dir) and dot-prefixed directories (the upload staging area, dir/.staging/).
|
||||||
if !e.IsDir() || e.Name() == bootVersion || strings.HasPrefix(e.Name(), ".") {
|
if !e.IsDir() || e.Name() == seed || strings.HasPrefix(e.Name(), ".") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if _, err := r.LoadAvailable(filepath.Join(dir, e.Name()), e.Name()); err != nil {
|
if _, err := r.LoadAvailable(filepath.Join(dir, e.Name()), e.Name()); err != nil {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -112,6 +113,103 @@ func TestOpenWithVersionsSkipsDotDirs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestOpenWithVersionsRecordsSeedMarker verifies the first boot records the seed
|
||||||
|
// version in the flat dir's marker, the marker is not mistaken for a version, and a
|
||||||
|
// reboot at the same seed version succeeds.
|
||||||
|
func TestOpenWithVersionsRecordsSeedMarker(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, v := range Variants() {
|
||||||
|
copyDawg(t, testDictDir(), dir, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
reg, err := OpenWithVersions(dir, "v1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first open: %v", err)
|
||||||
|
}
|
||||||
|
if got := reg.Versions(VariantEnglish); len(got) != 1 || got[0] != "v1" {
|
||||||
|
t.Errorf("versions = %v, want only [v1] (marker not a version)", got)
|
||||||
|
}
|
||||||
|
_ = reg.Close()
|
||||||
|
|
||||||
|
data, err := os.ReadFile(filepath.Join(dir, seedMarkerFile))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read seed marker: %v", err)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(string(data)); got != "v1" {
|
||||||
|
t.Fatalf("seed marker = %q, want v1", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
reg2, err := OpenWithVersions(dir, "v1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reboot at same seed: %v", err)
|
||||||
|
}
|
||||||
|
_ = reg2.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenWithVersionsMarkerWinsOverBoot verifies the recorded .seed_version marker
|
||||||
|
// is authoritative: once a directory is seeded, a different bootVersion
|
||||||
|
// (BACKEND_DICT_VERSION) is ignored — the flat dir keeps its recorded label — so a
|
||||||
|
// bumped build seed on a live volume cannot relabel the already-seeded bytes.
|
||||||
|
func TestOpenWithVersionsMarkerWinsOverBoot(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, v := range Variants() {
|
||||||
|
copyDawg(t, testDictDir(), dir, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
reg, err := OpenWithVersions(dir, "v1") // seeds the marker = v1
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seed open: %v", err)
|
||||||
|
}
|
||||||
|
_ = reg.Close()
|
||||||
|
|
||||||
|
// Reboot with a bumped boot version: the marker (v1) wins, no error, v2 ignored.
|
||||||
|
reg2, err := OpenWithVersions(dir, "v2")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reboot with bumped boot version: %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = reg2.Close() }()
|
||||||
|
if got := reg2.Versions(VariantEnglish); len(got) != 1 || got[0] != "v1" {
|
||||||
|
t.Errorf("versions = %v, want [v1] (marker wins, v2 ignored)", got)
|
||||||
|
}
|
||||||
|
if _, err := reg2.Solver(VariantEnglish, "v2"); !errors.Is(err, ErrUnknownVersion) {
|
||||||
|
t.Errorf("v2 must not be resident: got %v", err)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(filepath.Join(dir, seedMarkerFile))
|
||||||
|
if got := strings.TrimSpace(string(data)); got != "v1" {
|
||||||
|
t.Errorf("marker = %q, want v1 (unchanged)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenWithVersionsBumpedBootKeepsSubdir mirrors the live-contour case: a volume
|
||||||
|
// seeded as v1 with a v2 subdirectory (uploaded via the console), booted with a bumped
|
||||||
|
// build seed bootVersion=v2. The marker (v1) wins for the flat dir, and the v2
|
||||||
|
// subdirectory is still loaded — not skipped as "the boot version" — so both versions
|
||||||
|
// stay resident. (Skipping it would silently leave only the flat v1 bytes under v2.)
|
||||||
|
func TestOpenWithVersionsBumpedBootKeepsSubdir(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, v := range Variants() {
|
||||||
|
copyDawg(t, testDictDir(), dir, v)
|
||||||
|
}
|
||||||
|
reg0, err := OpenWithVersions(dir, "v1") // seed marker = v1
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seed: %v", err)
|
||||||
|
}
|
||||||
|
_ = reg0.Close()
|
||||||
|
copyDawg(t, testDictDir(), filepath.Join(dir, "v2"), VariantEnglish) // console upload
|
||||||
|
|
||||||
|
reg, err := OpenWithVersions(dir, "v2") // bumped build seed
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("boot v2: %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = reg.Close() }()
|
||||||
|
if _, err := reg.Solver(VariantEnglish, "v1"); err != nil {
|
||||||
|
t.Errorf("flat v1 must stay resident: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := reg.Solver(VariantEnglish, "v2"); err != nil {
|
||||||
|
t.Errorf("v2 subdir must be resident (not skipped): %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestReloadRegistersNewVersion verifies Load adds a second version to a variant
|
// TestReloadRegistersNewVersion verifies Load adds a second version to a variant
|
||||||
// already resident, moves the latest pointer and keeps the earlier version.
|
// already resident, moves the latest pointer and keeps the earlier version.
|
||||||
func TestReloadRegistersNewVersion(t *testing.T) {
|
func TestReloadRegistersNewVersion(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// seedMarkerFile names the file, in the flat dictionary directory, that records the
|
||||||
|
// version the directory was first seeded as. It is dot-prefixed so OpenWithVersions'
|
||||||
|
// version scan skips it (like the .staging upload area).
|
||||||
|
const seedMarkerFile = ".seed_version"
|
||||||
|
|
||||||
|
// resolveSeedVersion returns the version label the flat dictionary directory is
|
||||||
|
// addressed by, recording it on first use.
|
||||||
|
//
|
||||||
|
// The contour's dictionary lives on a named volume seeded from the image once and
|
||||||
|
// never re-seeded (deploy/docker-compose.yml). The flat DAWGs carry no embedded
|
||||||
|
// version, so the version a volume was first seeded as is recorded in a
|
||||||
|
// .seed_version marker and is **authoritative** from then on:
|
||||||
|
//
|
||||||
|
// - fresh directory (no marker): record bootVersion (the build's
|
||||||
|
// BACKEND_DICT_VERSION) and return it — the seed of a fresh volume;
|
||||||
|
// - already-seeded directory: return the recorded marker and ignore bootVersion.
|
||||||
|
//
|
||||||
|
// So bumping the build seed on a live volume is a harmless no-op (it only takes
|
||||||
|
// effect on a future fresh volume) instead of relabelling the already-seeded bytes —
|
||||||
|
// which would void games pinned to the prior label and mis-serve new ones. New games
|
||||||
|
// still pin the active version (DB-persisted, set by the admin console), which is the
|
||||||
|
// real way a running contour moves to a new release.
|
||||||
|
//
|
||||||
|
// A directory that cannot be written makes the first record fail; that also breaks
|
||||||
|
// the admin console (which writes version subdirectories here), so the error is
|
||||||
|
// returned rather than swallowed, matching the package's fail-loud dictionary setup.
|
||||||
|
func resolveSeedVersion(dir, bootVersion string) (string, error) {
|
||||||
|
path := filepath.Join(dir, seedMarkerFile)
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", fmt.Errorf("engine: read dictionary seed marker %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
if recorded := strings.TrimSpace(string(data)); recorded != "" {
|
||||||
|
return recorded, nil
|
||||||
|
}
|
||||||
|
// An empty/corrupt marker falls through and is rewritten from bootVersion.
|
||||||
|
}
|
||||||
|
if werr := os.WriteFile(path, []byte(bootVersion+"\n"), 0o644); werr != nil {
|
||||||
|
return "", fmt.Errorf("engine: record dictionary seed marker %s: %w", path, werr)
|
||||||
|
}
|
||||||
|
return bootVersion, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// SetupTile is one tile of a variant's full bag, decoded for the first-move draw
|
||||||
|
// (docs/ARCHITECTURE.md §6): its concrete letter (or the blank marker), a blank
|
||||||
|
// flag, and its draw rank. Lower rank wins the draw — a blank ranks above every
|
||||||
|
// letter, and letters rank by alphabet index, so the tile closest to the start of
|
||||||
|
// the alphabet ("A") wins. It is dictionary-independent, built from the variant's
|
||||||
|
// solver ruleset alone.
|
||||||
|
type SetupTile struct {
|
||||||
|
// Letter is the concrete character (the case the solver ruleset emits), or
|
||||||
|
// the blank marker "?" for a blank.
|
||||||
|
Letter string
|
||||||
|
// Blank reports whether the tile is a blank.
|
||||||
|
Blank bool
|
||||||
|
// Rank orders the draw: BlankRank for a blank (best), else the letter's
|
||||||
|
// alphabet index (0 = closest to "A").
|
||||||
|
Rank int
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlankRank is the first-move draw rank of a blank: below every letter index, so a
|
||||||
|
// blank always beats a lettered tile, matching the official rule that a blank
|
||||||
|
// supersedes all letters.
|
||||||
|
const BlankRank = -1
|
||||||
|
|
||||||
|
// SetupBag returns variant's full tile bag — every lettered tile expanded by its
|
||||||
|
// count, plus one entry per blank — decoded for the first-move seeding draw. The
|
||||||
|
// order is deterministic (alphabet order, blanks last); callers shuffle it with
|
||||||
|
// their own entropy. It needs no dictionary, so it is built from the variant's
|
||||||
|
// ruleset alone and reports ErrUnknownVariant for an unrecognised variant.
|
||||||
|
func SetupBag(v Variant) ([]SetupTile, error) {
|
||||||
|
rs, ok := v.ruleset()
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%w: %d", ErrUnknownVariant, v)
|
||||||
|
}
|
||||||
|
bag := make([]SetupTile, 0, 128)
|
||||||
|
for i, n := range rs.Counts {
|
||||||
|
ch, err := rs.Alphabet.Character(byte(i))
|
||||||
|
if err != nil {
|
||||||
|
// An offered variant's alphabet never yields a bad index; skip defensively.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for range n {
|
||||||
|
bag = append(bag, SetupTile{Letter: ch, Rank: i})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for range rs.Blanks {
|
||||||
|
bag = append(bag, SetupTile{Letter: blankLetter, Blank: true, Rank: BlankRank})
|
||||||
|
}
|
||||||
|
return bag, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetupBagEnglish(t *testing.T) {
|
||||||
|
bag, err := SetupBag(VariantEnglish)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SetupBag: %v", err)
|
||||||
|
}
|
||||||
|
// English Scrabble: 98 lettered tiles + 2 blanks = 100.
|
||||||
|
if len(bag) != 100 {
|
||||||
|
t.Fatalf("bag size = %d, want 100", len(bag))
|
||||||
|
}
|
||||||
|
blanks, aCount := 0, 0
|
||||||
|
for _, tl := range bag {
|
||||||
|
switch {
|
||||||
|
case tl.Blank:
|
||||||
|
blanks++
|
||||||
|
if tl.Rank != BlankRank {
|
||||||
|
t.Errorf("blank rank = %d, want %d", tl.Rank, BlankRank)
|
||||||
|
}
|
||||||
|
if tl.Letter != blankLetter {
|
||||||
|
t.Errorf("blank letter = %q, want %q", tl.Letter, blankLetter)
|
||||||
|
}
|
||||||
|
case tl.Letter == "a":
|
||||||
|
aCount++
|
||||||
|
if tl.Rank != 0 {
|
||||||
|
t.Errorf("'a' rank = %d, want 0 (closest to A)", tl.Rank)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if blanks != 2 {
|
||||||
|
t.Errorf("blanks = %d, want 2", blanks)
|
||||||
|
}
|
||||||
|
if aCount != 9 {
|
||||||
|
t.Errorf("'a' count = %d, want 9", aCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetupBagUnknownVariant(t *testing.T) {
|
||||||
|
if _, err := SetupBag(Variant(99)); !errors.Is(err, ErrUnknownVariant) {
|
||||||
|
t.Fatalf("err = %v, want ErrUnknownVariant", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package feedback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxAttachmentBytes caps a single attachment's raw size. Chosen to fit, with the
|
||||||
|
// message text and the FlatBuffers framing, under the gateway's 1 MiB edge body
|
||||||
|
// cap, so the whole submit request passes without weakening that cap.
|
||||||
|
const maxAttachmentBytes = 1_000_000
|
||||||
|
|
||||||
|
// allowedExt is the attachment extension allow-list. It is mirrored on the UI as a
|
||||||
|
// pre-upload gate; the server re-checks here as the trust boundary (metadata only,
|
||||||
|
// the file content is never parsed). Images render inline in the console; the rest
|
||||||
|
// are download-only.
|
||||||
|
var allowedExt = map[string]bool{
|
||||||
|
"png": true, "jpg": true, "jpeg": true, "webp": true, "gif": true, // images
|
||||||
|
"pdf": true, "txt": true, "log": true, "doc": true, "docx": true,
|
||||||
|
"rtf": true, "zip": true, "gz": true, "7z": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageType maps an image extension to the content-type the console serves it with
|
||||||
|
// (loaded only via <img>, which never executes, so a renamed non-image is inert).
|
||||||
|
var imageType = map[string]string{
|
||||||
|
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg",
|
||||||
|
"webp": "image/webp", "gif": "image/gif",
|
||||||
|
}
|
||||||
|
|
||||||
|
// ext returns name's lower-cased extension without the leading dot.
|
||||||
|
func ext(name string) string {
|
||||||
|
return strings.ToLower(strings.TrimPrefix(filepath.Ext(name), "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowedAttachment reports whether name's extension is on the allow-list.
|
||||||
|
func AllowedAttachment(name string) bool {
|
||||||
|
return allowedExt[ext(name)]
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsImage reports whether name is an inline-previewable image by its extension.
|
||||||
|
func IsImage(name string) bool {
|
||||||
|
_, ok := imageType[ext(name)]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ContentType returns the safe content-type the console serves the attachment
|
||||||
|
// with: the matching image type for an image, else application/octet-stream so a
|
||||||
|
// non-image is downloaded rather than rendered.
|
||||||
|
func ContentType(name string) string {
|
||||||
|
if t, ok := imageType[ext(name)]; ok {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
return "application/octet-stream"
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package feedback
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestAllowedAttachment(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
file string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"png image", "shot.png", true},
|
||||||
|
{"jpeg upper-case ext", "Photo.JPG", true},
|
||||||
|
{"pdf doc", "report.pdf", true},
|
||||||
|
{"archive 7z", "logs.7z", true},
|
||||||
|
{"doc with dotted name", "my.notes.docx", true},
|
||||||
|
{"disallowed exe", "evil.exe", false},
|
||||||
|
{"disallowed svg (xss vector)", "x.svg", false},
|
||||||
|
{"disallowed html", "x.html", false},
|
||||||
|
{"no extension", "README", false},
|
||||||
|
{"empty name", "", false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := AllowedAttachment(tt.file); got != tt.want {
|
||||||
|
t.Errorf("AllowedAttachment(%q) = %v, want %v", tt.file, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsImageAndContentType(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
file string
|
||||||
|
isImage bool
|
||||||
|
ctype string
|
||||||
|
}{
|
||||||
|
{"a.png", true, "image/png"},
|
||||||
|
{"a.jpg", true, "image/jpeg"},
|
||||||
|
{"a.jpeg", true, "image/jpeg"},
|
||||||
|
{"a.webp", true, "image/webp"},
|
||||||
|
{"a.gif", true, "image/gif"},
|
||||||
|
{"a.pdf", false, "application/octet-stream"},
|
||||||
|
{"a.zip", false, "application/octet-stream"},
|
||||||
|
{"a.svg", false, "application/octet-stream"}, // even if it slipped past, never image/svg+xml
|
||||||
|
{"noext", false, "application/octet-stream"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.file, func(t *testing.T) {
|
||||||
|
if got := IsImage(tt.file); got != tt.isImage {
|
||||||
|
t.Errorf("IsImage(%q) = %v, want %v", tt.file, got, tt.isImage)
|
||||||
|
}
|
||||||
|
if got := ContentType(tt.file); got != tt.ctype {
|
||||||
|
t.Errorf("ContentType(%q) = %q, want %q", tt.file, got, tt.ctype)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeChannel(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
in string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"telegram", "telegram"},
|
||||||
|
{"ios", "ios"},
|
||||||
|
{"android", "android"},
|
||||||
|
{"web", "web"},
|
||||||
|
{" iOS ", "ios"}, // trimmed + lower-cased
|
||||||
|
{"TELEGRAM", "telegram"},
|
||||||
|
{"", "web"}, // unknown -> web
|
||||||
|
{"windows", "web"}, // unknown -> web
|
||||||
|
{"'; DROP", "web"}, // junk -> web
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.in, func(t *testing.T) {
|
||||||
|
if got := normalizeChannel(tt.in); got != tt.want {
|
||||||
|
t.Errorf("normalizeChannel(%q) = %q, want %q", tt.in, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package feedback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/notify"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// maxBodyRunes caps a feedback message (and an operator reply) length.
|
||||||
|
maxBodyRunes = 1024
|
||||||
|
// replyVisibleFor is how long an operator reply stays shown to the player after
|
||||||
|
// it is delivered (read).
|
||||||
|
replyVisibleFor = 7 * 24 * time.Hour
|
||||||
|
)
|
||||||
|
|
||||||
|
// Submit / reply validation errors. The transport layer maps them to stable result
|
||||||
|
// codes; the UI maps those to the messages shown on the feedback screen.
|
||||||
|
var (
|
||||||
|
ErrEmptyMessage = errors.New("feedback: empty message")
|
||||||
|
ErrMessageTooLong = errors.New("feedback: message too long")
|
||||||
|
ErrAttachmentTooLarge = errors.New("feedback: attachment too large")
|
||||||
|
ErrAttachmentType = errors.New("feedback: attachment type not allowed")
|
||||||
|
ErrGuestForbidden = errors.New("feedback: guests cannot submit feedback")
|
||||||
|
ErrBanned = errors.New("feedback: account is banned from feedback")
|
||||||
|
ErrPendingReview = errors.New("feedback: previous message still pending review")
|
||||||
|
)
|
||||||
|
|
||||||
|
// validChannels enumerates the submitting platforms a client may report; anything
|
||||||
|
// else is normalised to "web" (the channel is informational, never a gate).
|
||||||
|
var validChannels = map[string]bool{"telegram": true, "ios": true, "android": true, "web": true}
|
||||||
|
|
||||||
|
// Service is the feedback domain: the only writer of feedback_messages. It reads
|
||||||
|
// accounts for the guest/role gates and publishes the reply notification.
|
||||||
|
type Service struct {
|
||||||
|
store *Store
|
||||||
|
accounts *account.Store
|
||||||
|
pub notify.Publisher
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewService constructs a Service. store owns feedback_messages; accounts supplies
|
||||||
|
// the guest flag and the feedback-ban role.
|
||||||
|
func NewService(store *Store, accounts *account.Store) *Service {
|
||||||
|
return &Service{
|
||||||
|
store: store,
|
||||||
|
accounts: accounts,
|
||||||
|
pub: notify.Nop{},
|
||||||
|
now: func() time.Time { return time.Now().UTC() },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetNotifier installs the live-event publisher used to push the "you have a reply"
|
||||||
|
// signal to the player. It must be called during startup wiring; the default is
|
||||||
|
// notify.Nop (no live events).
|
||||||
|
func (svc *Service) SetNotifier(p notify.Publisher) {
|
||||||
|
if p != nil {
|
||||||
|
svc.pub = p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Submit stores a feedback message from accountID. It rejects guests, feedback-
|
||||||
|
// banned accounts and a sender who still has a message pending review, then
|
||||||
|
// validates the body (non-empty, within the rune limit) and the optional
|
||||||
|
// attachment (size and extension allow-list). senderIP is the gateway-forwarded
|
||||||
|
// client IP (validated); channel is the submitting platform.
|
||||||
|
func (svc *Service) Submit(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, senderIP string) error {
|
||||||
|
acc, err := svc.accounts.GetByID(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if acc.IsGuest {
|
||||||
|
return ErrGuestForbidden
|
||||||
|
}
|
||||||
|
banned, err := svc.accounts.HasRole(ctx, accountID, account.RoleFeedbackBanned)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if banned {
|
||||||
|
return ErrBanned
|
||||||
|
}
|
||||||
|
pending, err := svc.store.HasUnread(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if pending {
|
||||||
|
return ErrPendingReview
|
||||||
|
}
|
||||||
|
body = strings.TrimSpace(body)
|
||||||
|
if body == "" {
|
||||||
|
return ErrEmptyMessage
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(body) > maxBodyRunes {
|
||||||
|
return ErrMessageTooLong
|
||||||
|
}
|
||||||
|
if len(attachment) > 0 {
|
||||||
|
if len(attachment) > maxAttachmentBytes {
|
||||||
|
return ErrAttachmentTooLarge
|
||||||
|
}
|
||||||
|
if !AllowedAttachment(attachmentName) {
|
||||||
|
return ErrAttachmentType
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
attachmentName = "" // a name without bytes carries no attachment
|
||||||
|
}
|
||||||
|
ch := normalizeChannel(channel)
|
||||||
|
// Snapshot the sender's interface language at submit time (acc is already loaded
|
||||||
|
// for the guest check) so the operator later sees the state as it was.
|
||||||
|
_, err = svc.store.Insert(ctx, accountID, body, attachment, attachmentName, ch, acc.PreferredLanguage, parseIP(senderIP))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// State is the player's feedback screen state. Reason is "" (can send), "pending"
|
||||||
|
// (a previous message is unreviewed) or "banned". Reply is the operator's answer to
|
||||||
|
// show, or nil. Fetching it delivers any pending replies (delivery counts as read),
|
||||||
|
// clearing the badge.
|
||||||
|
type State struct {
|
||||||
|
CanSend bool
|
||||||
|
BlockedReason string
|
||||||
|
Reply *Reply
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply is the operator's answer shown back to the player.
|
||||||
|
type Reply struct {
|
||||||
|
Body string
|
||||||
|
RepliedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// State computes the feedback screen state for accountID and marks any pending
|
||||||
|
// replies delivered.
|
||||||
|
func (svc *Service) State(ctx context.Context, accountID uuid.UUID) (State, error) {
|
||||||
|
banned, err := svc.accounts.HasRole(ctx, accountID, account.RoleFeedbackBanned)
|
||||||
|
if err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
pending, err := svc.store.HasUnread(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
st := State{CanSend: !banned && !pending}
|
||||||
|
switch {
|
||||||
|
case banned:
|
||||||
|
st.BlockedReason = "banned"
|
||||||
|
case pending:
|
||||||
|
st.BlockedReason = "pending"
|
||||||
|
}
|
||||||
|
vr, ok, err := svc.store.LatestVisibleReply(ctx, accountID, svc.now().Add(-replyVisibleFor))
|
||||||
|
if err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
st.Reply = &Reply{Body: vr.Body, RepliedAt: vr.RepliedAt}
|
||||||
|
}
|
||||||
|
// Opening the screen delivers every pending reply; mark them read to clear the
|
||||||
|
// badge (only the latest is shown, but all are now delivered).
|
||||||
|
if err := svc.store.MarkRepliesDelivered(ctx, accountID, svc.now()); err != nil {
|
||||||
|
return State{}, err
|
||||||
|
}
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplyUnread reports whether the account has an operator reply not yet delivered —
|
||||||
|
// the lobby/Info badge condition. It has no side effect (the lobby may poll it).
|
||||||
|
func (svc *Service) ReplyUnread(ctx context.Context, accountID uuid.UUID) (bool, error) {
|
||||||
|
return svc.store.HasUnreadReply(ctx, accountID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminList returns the filtered console feedback list, paginated.
|
||||||
|
func (svc *Service) AdminList(ctx context.Context, f AdminFilter, limit, offset int) ([]AdminRow, error) {
|
||||||
|
return svc.store.AdminList(ctx, f, limit, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminCount counts the filtered console feedback list.
|
||||||
|
func (svc *Service) AdminCount(ctx context.Context, f AdminFilter) (int, error) {
|
||||||
|
return svc.store.AdminCount(ctx, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminGet loads one message for the console detail view, or ErrNotFound.
|
||||||
|
func (svc *Service) AdminGet(ctx context.Context, id uuid.UUID) (AdminMessage, error) {
|
||||||
|
return svc.store.AdminGet(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountUnread counts the active (unread, not archived) feedback queue for the
|
||||||
|
// dashboard.
|
||||||
|
func (svc *Service) CountUnread(ctx context.Context) (int, error) {
|
||||||
|
return svc.store.CountUnread(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attachment returns a message's file name and bytes, reporting false when absent.
|
||||||
|
func (svc *Service) Attachment(ctx context.Context, id uuid.UUID) (string, []byte, bool, error) {
|
||||||
|
return svc.store.Attachment(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkRead marks a message dealt-with (the manual "read" action).
|
||||||
|
func (svc *Service) MarkRead(ctx context.Context, id uuid.UUID) error {
|
||||||
|
return svc.store.MarkRead(ctx, id, svc.now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply sets the operator reply on a message (marking it read), then pushes the
|
||||||
|
// "you have a reply" notification to the player.
|
||||||
|
func (svc *Service) Reply(ctx context.Context, id uuid.UUID, body string) error {
|
||||||
|
body = strings.TrimSpace(body)
|
||||||
|
if body == "" {
|
||||||
|
return ErrEmptyMessage
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(body) > maxBodyRunes {
|
||||||
|
return ErrMessageTooLong
|
||||||
|
}
|
||||||
|
accountID, err := svc.store.Reply(ctx, id, body, svc.now())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
svc.pub.Publish(notify.Notification(accountID, notify.NotifyAdminReply))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Archive files a handled message away (marking it read).
|
||||||
|
func (svc *Service) Archive(ctx context.Context, id uuid.UUID) error {
|
||||||
|
return svc.store.Archive(ctx, id, svc.now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete physically removes a message and its attachment.
|
||||||
|
func (svc *Service) Delete(ctx context.Context, id uuid.UUID) error {
|
||||||
|
return svc.store.Delete(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAllByAccount physically removes every message of an account.
|
||||||
|
func (svc *Service) DeleteAllByAccount(ctx context.Context, accountID uuid.UUID) error {
|
||||||
|
return svc.store.DeleteAllByAccount(ctx, accountID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseIP returns a validated canonical IP string, or nil when raw is empty or not
|
||||||
|
// a valid address.
|
||||||
|
func parseIP(raw string) *string {
|
||||||
|
addr, err := netip.ParseAddr(strings.TrimSpace(raw))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
canon := addr.String()
|
||||||
|
return &canon
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeChannel lower-cases and validates the client-reported channel, falling
|
||||||
|
// back to "web" for anything unrecognised.
|
||||||
|
func normalizeChannel(c string) string {
|
||||||
|
c = strings.ToLower(strings.TrimSpace(c))
|
||||||
|
if validChannels[c] {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
return "web"
|
||||||
|
}
|
||||||
@@ -0,0 +1,380 @@
|
|||||||
|
// Package feedback owns user feedback: the flat list of messages a registered
|
||||||
|
// player sends to the operators (each with an optional single attachment), the
|
||||||
|
// anti-spam "one pending message at a time" gate, and the operator's inline reply
|
||||||
|
// delivered back to the player's app. It is modelled on the admin chat-moderation
|
||||||
|
// surface (internal/social/adminchat.go) and uses raw SQL throughout for the
|
||||||
|
// attachment bytea, the COALESCE-based "set once" stamps, and the reply-visibility
|
||||||
|
// window.
|
||||||
|
package feedback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNotFound is returned when no feedback message matches the lookup.
|
||||||
|
var ErrNotFound = errors.New("feedback: not found")
|
||||||
|
|
||||||
|
// Store is the Postgres-backed query surface for feedback_messages.
|
||||||
|
type Store struct {
|
||||||
|
db *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStore constructs a Store wrapping db.
|
||||||
|
func NewStore(db *sql.DB) *Store {
|
||||||
|
return &Store{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert stores one feedback message from accountID and returns its id. attachment
|
||||||
|
// is the raw file bytes (nil for none); attachmentName, ip and a non-default
|
||||||
|
// channel are stored as given. lang (the sender's interface language) is a snapshot
|
||||||
|
// taken now, so the operator later sees the state at submit time. created_at defaults
|
||||||
|
// to now() in the database.
|
||||||
|
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, lang string, ip *string) (uuid.UUID, error) {
|
||||||
|
id, err := uuid.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("feedback: new message id: %w", err)
|
||||||
|
}
|
||||||
|
var att []byte // a nil []byte binds as bytea NULL
|
||||||
|
if len(attachment) > 0 {
|
||||||
|
att = attachment
|
||||||
|
}
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`INSERT INTO backend.feedback_messages
|
||||||
|
(message_id, account_id, body, attachment, attachment_name, channel, lang, sender_ip)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||||
|
id, accountID, body, att, nullStr(attachmentName), channel, nullStr(lang), ip); err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("feedback: insert: %w", err)
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nullStr maps an empty string to a NULL text bind, else the value.
|
||||||
|
func nullStr(s string) *string {
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &s
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasUnread reports whether the account has any message the operator has not yet
|
||||||
|
// dealt with (read_at IS NULL) — the anti-spam gate's condition.
|
||||||
|
func (s *Store) HasUnread(ctx context.Context, accountID uuid.UUID) (bool, error) {
|
||||||
|
var ok bool
|
||||||
|
if err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT EXISTS (SELECT 1 FROM backend.feedback_messages WHERE account_id = $1 AND read_at IS NULL)`,
|
||||||
|
accountID).Scan(&ok); err != nil {
|
||||||
|
return false, fmt.Errorf("feedback: has-unread %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
return ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasUnreadReply reports whether the account has an operator reply not yet
|
||||||
|
// delivered to its app (reply_read_at IS NULL) — the badge's condition.
|
||||||
|
func (s *Store) HasUnreadReply(ctx context.Context, accountID uuid.UUID) (bool, error) {
|
||||||
|
var ok bool
|
||||||
|
if err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT EXISTS (SELECT 1 FROM backend.feedback_messages
|
||||||
|
WHERE account_id = $1 AND reply_body IS NOT NULL AND reply_read_at IS NULL)`,
|
||||||
|
accountID).Scan(&ok); err != nil {
|
||||||
|
return false, fmt.Errorf("feedback: has-unread-reply %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
return ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VisibleReply is the operator reply shown back to the player: the reply on their
|
||||||
|
// most recent replied message still inside the visibility window.
|
||||||
|
type VisibleReply struct {
|
||||||
|
Body string
|
||||||
|
RepliedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// LatestVisibleReply returns the reply on the account's **most recent** message, if
|
||||||
|
// that message carries one still visible to the player — not yet delivered, or
|
||||||
|
// delivered after cutoff (one week ago). Binding it to the single latest message
|
||||||
|
// means that the moment the player sends a newer message the previous reply stops
|
||||||
|
// showing (the new message has no reply yet). Reports false when there is none.
|
||||||
|
func (s *Store) LatestVisibleReply(ctx context.Context, accountID uuid.UUID, cutoff time.Time) (VisibleReply, bool, error) {
|
||||||
|
var vr VisibleReply
|
||||||
|
var repliedAt sql.NullTime
|
||||||
|
err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT COALESCE(reply_body, ''), replied_at FROM (
|
||||||
|
SELECT reply_body, replied_at, reply_read_at FROM backend.feedback_messages
|
||||||
|
WHERE account_id = $1 ORDER BY created_at DESC LIMIT 1
|
||||||
|
) latest
|
||||||
|
WHERE reply_body IS NOT NULL AND (reply_read_at IS NULL OR reply_read_at > $2)`,
|
||||||
|
accountID, cutoff).Scan(&vr.Body, &repliedAt)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return VisibleReply{}, false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return VisibleReply{}, false, fmt.Errorf("feedback: latest visible reply %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
if repliedAt.Valid {
|
||||||
|
vr.RepliedAt = repliedAt.Time
|
||||||
|
}
|
||||||
|
return vr, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkRepliesDelivered stamps reply_read_at on every not-yet-delivered reply of the
|
||||||
|
// account (delivery counts as read), clearing the badge when the player opens the
|
||||||
|
// feedback screen.
|
||||||
|
func (s *Store) MarkRepliesDelivered(ctx context.Context, accountID uuid.UUID, at time.Time) error {
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`UPDATE backend.feedback_messages SET reply_read_at = $2
|
||||||
|
WHERE account_id = $1 AND reply_body IS NOT NULL AND reply_read_at IS NULL`,
|
||||||
|
accountID, at); err != nil {
|
||||||
|
return fmt.Errorf("feedback: mark replies delivered %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkRead stamps read_at the first time, marking the message dealt-with without any
|
||||||
|
// other action; a re-mark keeps the original time.
|
||||||
|
func (s *Store) MarkRead(ctx context.Context, id uuid.UUID, at time.Time) error {
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`UPDATE backend.feedback_messages SET read_at = COALESCE(read_at, $2) WHERE message_id = $1`,
|
||||||
|
id, at); err != nil {
|
||||||
|
return fmt.Errorf("feedback: mark read %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply sets (or replaces) the operator reply on a message, marks it read, and
|
||||||
|
// resets its delivery so the player is notified again. Returns the message's
|
||||||
|
// account_id for the live notification, or ErrNotFound.
|
||||||
|
func (s *Store) Reply(ctx context.Context, id uuid.UUID, body string, at time.Time) (uuid.UUID, error) {
|
||||||
|
var accountID uuid.UUID
|
||||||
|
err := s.db.QueryRowContext(ctx,
|
||||||
|
`UPDATE backend.feedback_messages
|
||||||
|
SET reply_body = $2, replied_at = $3, reply_read_at = NULL, read_at = COALESCE(read_at, $3)
|
||||||
|
WHERE message_id = $1
|
||||||
|
RETURNING account_id`,
|
||||||
|
id, body, at).Scan(&accountID)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return uuid.Nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil, fmt.Errorf("feedback: reply %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return accountID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Archive files a handled message away and marks it read.
|
||||||
|
func (s *Store) Archive(ctx context.Context, id uuid.UUID, at time.Time) error {
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`UPDATE backend.feedback_messages
|
||||||
|
SET archived_at = COALESCE(archived_at, $2), read_at = COALESCE(read_at, $2)
|
||||||
|
WHERE message_id = $1`,
|
||||||
|
id, at); err != nil {
|
||||||
|
return fmt.Errorf("feedback: archive %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete physically removes a message (with its attachment).
|
||||||
|
func (s *Store) Delete(ctx context.Context, id uuid.UUID) error {
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`DELETE FROM backend.feedback_messages WHERE message_id = $1`, id); err != nil {
|
||||||
|
return fmt.Errorf("feedback: delete %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAllByAccount physically removes every message of an account.
|
||||||
|
func (s *Store) DeleteAllByAccount(ctx context.Context, accountID uuid.UUID) error {
|
||||||
|
if _, err := s.db.ExecContext(ctx,
|
||||||
|
`DELETE FROM backend.feedback_messages WHERE account_id = $1`, accountID); err != nil {
|
||||||
|
return fmt.Errorf("feedback: delete all %s: %w", accountID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attachment returns a message's stored file name and bytes, reporting false when
|
||||||
|
// the message has no attachment or does not exist.
|
||||||
|
func (s *Store) Attachment(ctx context.Context, id uuid.UUID) (string, []byte, bool, error) {
|
||||||
|
var name string
|
||||||
|
var data []byte
|
||||||
|
err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT COALESCE(attachment_name, ''), attachment FROM backend.feedback_messages WHERE message_id = $1`,
|
||||||
|
id).Scan(&name, &data)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return "", nil, false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, false, fmt.Errorf("feedback: attachment %s: %w", id, err)
|
||||||
|
}
|
||||||
|
if data == nil {
|
||||||
|
return "", nil, false, nil
|
||||||
|
}
|
||||||
|
return name, data, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminMessage is one feedback message in the operator console detail view: the
|
||||||
|
// message with its sender's resolved display name and source. The attachment bytes
|
||||||
|
// are not loaded here (served separately); only their presence and name are.
|
||||||
|
type AdminMessage struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
AccountID uuid.UUID
|
||||||
|
SenderName string
|
||||||
|
Source string
|
||||||
|
Body string
|
||||||
|
Channel string
|
||||||
|
// Lang is the sender's interface language, snapshotted at submit time.
|
||||||
|
Lang string
|
||||||
|
SenderIP string
|
||||||
|
HasAttachment bool
|
||||||
|
AttachmentName string
|
||||||
|
Read bool
|
||||||
|
Archived bool
|
||||||
|
Replied bool
|
||||||
|
ReplyBody string
|
||||||
|
RepliedAt time.Time
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminRow is one feedback message in the console list (a lighter projection).
|
||||||
|
type AdminRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
AccountID uuid.UUID
|
||||||
|
SenderName string
|
||||||
|
Source string
|
||||||
|
Channel string
|
||||||
|
HasAttachment bool
|
||||||
|
Read bool
|
||||||
|
Replied bool
|
||||||
|
Archived bool
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminFilter narrows the console feedback list. Status is one of "unread"
|
||||||
|
// (default), "read" or "archived". NameMask/ExtMask are glob masks
|
||||||
|
// (account.LikePattern) on the sender's display name / any identity's external id;
|
||||||
|
// AccountID, when set, restricts to one account (the per-user link from /users).
|
||||||
|
type AdminFilter struct {
|
||||||
|
Status string
|
||||||
|
NameMask string
|
||||||
|
ExtMask string
|
||||||
|
AccountID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
// feedbackSource projects a sender's source: guest, robot, or its oldest identity
|
||||||
|
// kind ("—" when it has none). Mirrors social.adminMessageSource.
|
||||||
|
const feedbackSource = `CASE
|
||||||
|
WHEN a.is_guest THEN 'guest'
|
||||||
|
WHEN EXISTS (SELECT 1 FROM backend.identities i WHERE i.account_id = a.account_id AND i.kind = 'robot') THEN 'robot'
|
||||||
|
ELSE COALESCE((SELECT i2.kind FROM backend.identities i2 WHERE i2.account_id = a.account_id ORDER BY i2.created_at ASC LIMIT 1), '—')
|
||||||
|
END`
|
||||||
|
|
||||||
|
// adminWhere builds the shared WHERE clause and its positional args (from $1).
|
||||||
|
func adminWhere(f AdminFilter) (string, []any) {
|
||||||
|
var where string
|
||||||
|
switch f.Status {
|
||||||
|
case "archived":
|
||||||
|
where = `m.archived_at IS NOT NULL`
|
||||||
|
case "read":
|
||||||
|
where = `m.read_at IS NOT NULL AND m.archived_at IS NULL`
|
||||||
|
default: // unread
|
||||||
|
where = `m.read_at IS NULL AND m.archived_at IS NULL`
|
||||||
|
}
|
||||||
|
var args []any
|
||||||
|
if f.AccountID != uuid.Nil {
|
||||||
|
args = append(args, f.AccountID)
|
||||||
|
where += fmt.Sprintf(` AND m.account_id = $%d`, len(args))
|
||||||
|
}
|
||||||
|
if name := account.LikePattern(f.NameMask); name != "" {
|
||||||
|
args = append(args, name)
|
||||||
|
where += fmt.Sprintf(` AND a.display_name ILIKE $%d ESCAPE '\'`, len(args))
|
||||||
|
}
|
||||||
|
if ext := account.LikePattern(f.ExtMask); ext != "" {
|
||||||
|
args = append(args, ext)
|
||||||
|
where += fmt.Sprintf(` AND EXISTS (SELECT 1 FROM backend.identities ie WHERE ie.account_id = a.account_id AND ie.external_id ILIKE $%d ESCAPE '\')`, len(args))
|
||||||
|
}
|
||||||
|
return where, args
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminList returns the filtered console feedback list, newest first, paginated.
|
||||||
|
func (s *Store) AdminList(ctx context.Context, f AdminFilter, limit, offset int) ([]AdminRow, error) {
|
||||||
|
where, args := adminWhere(f)
|
||||||
|
q := `SELECT m.message_id, m.account_id, a.display_name, ` + feedbackSource + ` AS source, m.channel,
|
||||||
|
(m.attachment IS NOT NULL), (m.read_at IS NOT NULL), (m.reply_body IS NOT NULL), (m.archived_at IS NOT NULL), m.created_at
|
||||||
|
FROM backend.feedback_messages m
|
||||||
|
JOIN backend.accounts a ON a.account_id = m.account_id
|
||||||
|
WHERE ` + where +
|
||||||
|
fmt.Sprintf(` ORDER BY m.created_at DESC LIMIT $%d OFFSET $%d`, len(args)+1, len(args)+2)
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
rows, err := s.db.QueryContext(ctx, q, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("feedback: admin list: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []AdminRow
|
||||||
|
for rows.Next() {
|
||||||
|
var r AdminRow
|
||||||
|
if err := rows.Scan(&r.ID, &r.AccountID, &r.SenderName, &r.Source, &r.Channel,
|
||||||
|
&r.HasAttachment, &r.Read, &r.Replied, &r.Archived, &r.CreatedAt); err != nil {
|
||||||
|
return nil, fmt.Errorf("feedback: scan admin row: %w", err)
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminCount counts the filtered console feedback list, for the pager.
|
||||||
|
func (s *Store) AdminCount(ctx context.Context, f AdminFilter) (int, error) {
|
||||||
|
where, args := adminWhere(f)
|
||||||
|
var n int
|
||||||
|
q := `SELECT COUNT(*) FROM backend.feedback_messages m JOIN backend.accounts a ON a.account_id = m.account_id WHERE ` + where
|
||||||
|
if err := s.db.QueryRowContext(ctx, q, args...).Scan(&n); err != nil {
|
||||||
|
return 0, fmt.Errorf("feedback: admin count: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminGet loads one message for the console detail view, or ErrNotFound.
|
||||||
|
func (s *Store) AdminGet(ctx context.Context, id uuid.UUID) (AdminMessage, error) {
|
||||||
|
var m AdminMessage
|
||||||
|
var repliedAt sql.NullTime
|
||||||
|
q := `SELECT m.message_id, m.account_id, a.display_name, ` + feedbackSource + ` AS source, m.body, m.channel,
|
||||||
|
COALESCE(m.lang, ''),
|
||||||
|
COALESCE(m.sender_ip, ''), (m.attachment IS NOT NULL), COALESCE(m.attachment_name, ''),
|
||||||
|
(m.read_at IS NOT NULL), (m.archived_at IS NOT NULL), (m.reply_body IS NOT NULL),
|
||||||
|
COALESCE(m.reply_body, ''), m.replied_at, m.created_at
|
||||||
|
FROM backend.feedback_messages m
|
||||||
|
JOIN backend.accounts a ON a.account_id = m.account_id
|
||||||
|
WHERE m.message_id = $1`
|
||||||
|
err := s.db.QueryRowContext(ctx, q, id).Scan(
|
||||||
|
&m.ID, &m.AccountID, &m.SenderName, &m.Source, &m.Body, &m.Channel,
|
||||||
|
&m.Lang,
|
||||||
|
&m.SenderIP, &m.HasAttachment, &m.AttachmentName,
|
||||||
|
&m.Read, &m.Archived, &m.Replied, &m.ReplyBody, &repliedAt, &m.CreatedAt)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return AdminMessage{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return AdminMessage{}, fmt.Errorf("feedback: admin get %s: %w", id, err)
|
||||||
|
}
|
||||||
|
if repliedAt.Valid {
|
||||||
|
m.RepliedAt = repliedAt.Time
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountUnread counts the active (unread, not archived) feedback queue, for the
|
||||||
|
// console dashboard.
|
||||||
|
func (s *Store) CountUnread(ctx context.Context) (int, error) {
|
||||||
|
var n int
|
||||||
|
if err := s.db.QueryRowContext(ctx,
|
||||||
|
`SELECT COUNT(*) FROM backend.feedback_messages WHERE read_at IS NULL AND archived_at IS NULL`,
|
||||||
|
).Scan(&n); err != nil {
|
||||||
|
return 0, fmt.Errorf("feedback: count unread: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
@@ -63,6 +63,7 @@ type gameCache struct {
|
|||||||
|
|
||||||
type cachedGame struct {
|
type cachedGame struct {
|
||||||
game *engine.Game
|
game *engine.Game
|
||||||
|
seats []Seat
|
||||||
variant string
|
variant string
|
||||||
lastAccess time.Time
|
lastAccess time.Time
|
||||||
}
|
}
|
||||||
@@ -71,24 +72,27 @@ func newGameCache(ttl time.Duration, now func() time.Time) *gameCache {
|
|||||||
return &gameCache{entries: make(map[uuid.UUID]*cachedGame), ttl: ttl, now: now}
|
return &gameCache{entries: make(map[uuid.UUID]*cachedGame), ttl: ttl, now: now}
|
||||||
}
|
}
|
||||||
|
|
||||||
// get returns the live game for id and refreshes its idle timer, or (nil, false).
|
// get returns the live game and its immutable seat list for id and refreshes its idle
|
||||||
func (c *gameCache) get(id uuid.UUID) (*engine.Game, bool) {
|
// timer, or (nil, nil, false). The seats let a read check membership (and label seats)
|
||||||
|
// without re-loading the game from the store, since seats never change after a game starts.
|
||||||
|
func (c *gameCache) get(id uuid.UUID) (*engine.Game, []Seat, bool) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
e, ok := c.entries[id]
|
e, ok := c.entries[id]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, false
|
return nil, nil, false
|
||||||
}
|
}
|
||||||
e.lastAccess = c.now()
|
e.lastAccess = c.now()
|
||||||
return e.game, true
|
return e.game, e.seats, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// put stores g as the live game for id. variant labels the entry so the active-
|
// put stores g as the live game for id together with its seat list. variant labels the
|
||||||
// games gauge can report counts by variant without inspecting engine internals.
|
// entry so the active-games gauge can report counts by variant without inspecting engine
|
||||||
func (c *gameCache) put(id uuid.UUID, g *engine.Game, variant string) {
|
// internals; seats are the game's immutable seat standings for the membership fast path.
|
||||||
|
func (c *gameCache) put(id uuid.UUID, g *engine.Game, variant string, seats []Seat) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
c.entries[id] = &cachedGame{game: g, variant: variant, lastAccess: c.now()}
|
c.entries[id] = &cachedGame{game: g, seats: seats, variant: variant, lastAccess: c.now()}
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove drops id from the cache (used on a finished game and after a failed
|
// remove drops id from the cache (used on a finished game and after a failed
|
||||||
|
|||||||
@@ -68,10 +68,6 @@ func TestEmitMoveNotifiesActor(t *testing.T) {
|
|||||||
if got := string(yt.ScoreLine()); got != "13:19" { // seat 1 (recipient) first, then seat 0
|
if got := string(yt.ScoreLine()); got != "13:19" { // seat 1 (recipient) first, then seat 0
|
||||||
t.Errorf("your_turn score_line = %q, want 13:19", got)
|
t.Errorf("your_turn score_line = %q, want 13:19", got)
|
||||||
}
|
}
|
||||||
// Routed out-of-app by the game's language (the default Variant is English).
|
|
||||||
if yourTurn.Language != "en" {
|
|
||||||
t.Errorf("your_turn language = %q, want en", yourTurn.Language)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestEmitMoveAnnouncesGameOver checks the closing move sends a game_over push to every seat,
|
// TestEmitMoveAnnouncesGameOver checks the closing move sends a game_over push to every seat,
|
||||||
@@ -106,7 +102,4 @@ func TestEmitMoveAnnouncesGameOver(t *testing.T) {
|
|||||||
if string(l.Result()) != "lost" || string(l.ScoreLine()) != "95:120" {
|
if string(l.Result()) != "lost" || string(l.ScoreLine()) != "95:120" {
|
||||||
t.Errorf("loser game_over = %q / %q, want lost / 95:120", l.Result(), l.ScoreLine())
|
t.Errorf("loser game_over = %q / %q, want lost / 95:120", l.Result(), l.ScoreLine())
|
||||||
}
|
}
|
||||||
if over[winner].Language != "en" || over[loser].Language != "en" {
|
|
||||||
t.Errorf("game_over languages = %q/%q, want en/en", over[winner].Language, over[loser].Language)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ func gameSummary(g Game, names []string) notify.GameSummary {
|
|||||||
ToMove: g.ToMove,
|
ToMove: g.ToMove,
|
||||||
TurnTimeoutSecs: int(g.TurnTimeout.Seconds()),
|
TurnTimeoutSecs: int(g.TurnTimeout.Seconds()),
|
||||||
MultipleWordsPerTurn: g.MultipleWordsPerTurn,
|
MultipleWordsPerTurn: g.MultipleWordsPerTurn,
|
||||||
|
VsAI: g.VsAI,
|
||||||
MoveCount: g.MoveCount,
|
MoveCount: g.MoveCount,
|
||||||
EndReason: g.EndReason,
|
EndReason: g.EndReason,
|
||||||
Seats: seats,
|
Seats: seats,
|
||||||
@@ -73,6 +74,7 @@ func playerState(v StateView, names []string, includeAlphabet bool) (notify.Play
|
|||||||
Rack: rack,
|
Rack: rack,
|
||||||
BagLen: v.BagLen,
|
BagLen: v.BagLen,
|
||||||
HintsRemaining: v.HintsRemaining,
|
HintsRemaining: v.HintsRemaining,
|
||||||
|
WalletBalance: v.WalletBalance,
|
||||||
}
|
}
|
||||||
if includeAlphabet {
|
if includeAlphabet {
|
||||||
tab, err := engine.AlphabetTable(v.Game.Variant)
|
tab, err := engine.AlphabetTable(v.Game.Variant)
|
||||||
|
|||||||
@@ -94,8 +94,8 @@ func TestGameCacheEviction(t *testing.T) {
|
|||||||
cur := time.Unix(1_700_000_000, 0)
|
cur := time.Unix(1_700_000_000, 0)
|
||||||
cache := newGameCache(time.Hour, func() time.Time { return cur })
|
cache := newGameCache(time.Hour, func() time.Time { return cur })
|
||||||
id := uuid.New()
|
id := uuid.New()
|
||||||
cache.put(id, nil, "scrabble_en")
|
cache.put(id, nil, "scrabble_en", nil)
|
||||||
if _, ok := cache.get(id); !ok {
|
if _, _, ok := cache.get(id); !ok {
|
||||||
t.Fatal("game must be resident after put")
|
t.Fatal("game must be resident after put")
|
||||||
}
|
}
|
||||||
cur = cur.Add(30 * time.Minute)
|
cur = cur.Add(30 * time.Minute)
|
||||||
@@ -104,7 +104,7 @@ func TestGameCacheEviction(t *testing.T) {
|
|||||||
if n := cache.sweep(); n != 1 {
|
if n := cache.sweep(); n != 1 {
|
||||||
t.Errorf("sweep evicted %d, want 1", n)
|
t.Errorf("sweep evicted %d, want 1", n)
|
||||||
}
|
}
|
||||||
if _, ok := cache.get(id); ok {
|
if _, _, ok := cache.get(id); ok {
|
||||||
t.Error("game must be evicted after idle TTL")
|
t.Error("game must be evicted after idle TTL")
|
||||||
}
|
}
|
||||||
if cache.size() != 0 {
|
if cache.size() != 0 {
|
||||||
|
|||||||
@@ -101,15 +101,22 @@ func phaseOf(moveCount int) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// recordStarted counts one started game of variant.
|
// recordStarted counts one started game of variant, split by whether it is an
|
||||||
func (m *gameMetrics) recordStarted(ctx context.Context, v engine.Variant) {
|
// honest-AI game (the vs_ai attribute), so AI and human games chart separately.
|
||||||
m.started.Add(ctx, 1, variantAttr(v))
|
func (m *gameMetrics) recordStarted(ctx context.Context, v engine.Variant, vsAI bool) {
|
||||||
|
m.started.Add(ctx, 1, gameKindAttr(v, vsAI))
|
||||||
}
|
}
|
||||||
|
|
||||||
// recordAbandoned counts one seat dropped by the turn-timeout sweeper in a game of
|
// recordAbandoned counts one seat dropped by the turn-timeout sweeper in a game of
|
||||||
// variant.
|
// variant, split by the vs_ai attribute (an AI game's abandon is the 7-day rule).
|
||||||
func (m *gameMetrics) recordAbandoned(ctx context.Context, v engine.Variant) {
|
func (m *gameMetrics) recordAbandoned(ctx context.Context, v engine.Variant, vsAI bool) {
|
||||||
m.abandoned.Add(ctx, 1, variantAttr(v))
|
m.abandoned.Add(ctx, 1, gameKindAttr(v, vsAI))
|
||||||
|
}
|
||||||
|
|
||||||
|
// gameKindAttr is the (variant, vs_ai) attribute set shared by the started and
|
||||||
|
// abandoned counters so AI and human games are split on the same labels.
|
||||||
|
func gameKindAttr(v engine.Variant, vsAI bool) metric.MeasurementOption {
|
||||||
|
return metric.WithAttributes(attribute.String("variant", v.String()), attribute.Bool("vs_ai", vsAI))
|
||||||
}
|
}
|
||||||
|
|
||||||
// variantAttr is the shared "variant" attribute option, usable for both Record and
|
// variantAttr is the shared "variant" attribute option, usable for both Record and
|
||||||
|
|||||||
@@ -20,10 +20,12 @@ func TestGameMetrics(t *testing.T) {
|
|||||||
meter := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)).Meter("test")
|
meter := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)).Meter("test")
|
||||||
m := newGameMetrics(meter)
|
m := newGameMetrics(meter)
|
||||||
|
|
||||||
m.recordStarted(ctx, engine.VariantEnglish)
|
m.recordStarted(ctx, engine.VariantEnglish, false)
|
||||||
m.recordStarted(ctx, engine.VariantEnglish)
|
m.recordStarted(ctx, engine.VariantEnglish, false)
|
||||||
m.recordStarted(ctx, engine.VariantRussianScrabble)
|
m.recordStarted(ctx, engine.VariantRussianScrabble, false)
|
||||||
m.recordAbandoned(ctx, engine.VariantErudit)
|
m.recordStarted(ctx, engine.VariantEnglish, true) // an honest-AI game
|
||||||
|
m.recordAbandoned(ctx, engine.VariantErudit, false)
|
||||||
|
m.recordAbandoned(ctx, engine.VariantEnglish, true) // an AI game abandoned (the 7-day rule)
|
||||||
m.recordReplay(ctx, engine.VariantEnglish, time.Now().Add(-time.Millisecond))
|
m.recordReplay(ctx, engine.VariantEnglish, time.Now().Add(-time.Millisecond))
|
||||||
m.recordValidate(ctx, engine.VariantRussianScrabble, time.Now().Add(-time.Millisecond))
|
m.recordValidate(ctx, engine.VariantRussianScrabble, time.Now().Add(-time.Millisecond))
|
||||||
m.recordMoveDuration(ctx, engine.VariantEnglish, 3, 5*time.Second)
|
m.recordMoveDuration(ctx, engine.VariantEnglish, 3, 5*time.Second)
|
||||||
@@ -35,11 +37,15 @@ func TestGameMetrics(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
started := counterByAttr(t, rm, "games_started_total", "variant")
|
started := counterByAttr(t, rm, "games_started_total", "variant")
|
||||||
if started["scrabble_en"] != 2 || started["scrabble_ru"] != 1 {
|
if started["scrabble_en"] != 3 || started["scrabble_ru"] != 1 {
|
||||||
t.Errorf("games_started_total = %v, want scrabble_en:2 scrabble_ru:1", started)
|
t.Errorf("games_started_total = %v, want scrabble_en:3 scrabble_ru:1", started)
|
||||||
}
|
}
|
||||||
if abandoned := counterByAttr(t, rm, "games_abandoned_total", "variant"); abandoned["erudit_ru"] != 1 {
|
// The vs_ai attribute splits AI from human games for the per-kind Grafana panels.
|
||||||
t.Errorf("games_abandoned_total = %v, want erudit_ru:1", abandoned)
|
if byKind := counterByAttr(t, rm, "games_started_total", "vs_ai"); byKind["false"] != 3 || byKind["true"] != 1 {
|
||||||
|
t.Errorf("games_started_total by vs_ai = %v, want false:3 true:1", byKind)
|
||||||
|
}
|
||||||
|
if abandoned := counterByAttr(t, rm, "games_abandoned_total", "vs_ai"); abandoned["false"] != 1 || abandoned["true"] != 1 {
|
||||||
|
t.Errorf("games_abandoned_total by vs_ai = %v, want false:1 true:1", abandoned)
|
||||||
}
|
}
|
||||||
if c := histogramCount(t, rm, "game_replay_duration"); c != 1 {
|
if c := histogramCount(t, rm, "game_replay_duration"); c != 1 {
|
||||||
t.Errorf("game_replay_duration observations = %d, want 1", c)
|
t.Errorf("game_replay_duration observations = %d, want 1", c)
|
||||||
@@ -78,7 +84,7 @@ func counterByAttr(t *testing.T, rm metricdata.ResourceMetrics, name, attr strin
|
|||||||
}
|
}
|
||||||
for _, dp := range sum.DataPoints {
|
for _, dp := range sum.DataPoints {
|
||||||
v, _ := dp.Attributes.Value(attribute.Key(attr))
|
v, _ := dp.Attributes.Value(attribute.Key(attr))
|
||||||
out[v.AsString()] += dp.Value
|
out[v.Emit()] += dp.Value // Emit renders any attribute type (string or bool) to a key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReplayStep is one step of an admin game replay: the move that produced it (nil for the
|
||||||
|
// initial dealt state, step 0) and the resulting position — every seat's rack, the running
|
||||||
|
// scores, whose turn it is and the bag remainder. Step k's board is the union of every
|
||||||
|
// play's placements through step k, which the renderer accumulates onto an empty grid
|
||||||
|
// (docs/ARCHITECTURE.md §9.1 visual replay).
|
||||||
|
type ReplayStep struct {
|
||||||
|
// Move is the journalled move that produced this state, or nil for the initial deal.
|
||||||
|
Move *HistoryMove
|
||||||
|
// Drawn lists the tiles the mover drew from the bag after this move ("?" for a blank);
|
||||||
|
// empty for the initial deal, a pass or a resignation.
|
||||||
|
Drawn []string
|
||||||
|
// Racks holds every seat's rack at this step, indexed by seat ("?" for a blank).
|
||||||
|
Racks [][]string
|
||||||
|
// Scores holds every seat's running score, indexed by seat.
|
||||||
|
Scores []int
|
||||||
|
// ToMove is the seat to move at this step.
|
||||||
|
ToMove int
|
||||||
|
// BagLen is the number of tiles left in the bag at this step.
|
||||||
|
BagLen int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplayTimelineView is the admin replay of a game: the persisted game plus the ordered
|
||||||
|
// replay steps (the initial deal followed by one step per journalled move).
|
||||||
|
type ReplayTimelineView struct {
|
||||||
|
Game Game
|
||||||
|
Steps []ReplayStep
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplayTimeline rebuilds a game from its pinned seed and journal and returns the ordered
|
||||||
|
// replay steps for the admin console: the initial deal (step 0) then one step per
|
||||||
|
// journalled move, each carrying the resulting racks, scores, turn cursor, bag size and the
|
||||||
|
// tiles the mover drew. The deterministic bag makes the reconstruction exact. It needs no
|
||||||
|
// dictionary beyond the engine the seed deals, and — like the live replay — stops early if a
|
||||||
|
// committed move became illegal under tightened rules rather than failing.
|
||||||
|
func (svc *Service) ReplayTimeline(ctx context.Context, gameID uuid.UUID) (ReplayTimelineView, error) {
|
||||||
|
pre, err := svc.store.GetGame(ctx, gameID)
|
||||||
|
if err != nil {
|
||||||
|
return ReplayTimelineView{}, err
|
||||||
|
}
|
||||||
|
seed, err := svc.store.GameSeed(ctx, gameID)
|
||||||
|
if err != nil {
|
||||||
|
return ReplayTimelineView{}, err
|
||||||
|
}
|
||||||
|
g, err := engine.New(svc.registry, engine.Options{
|
||||||
|
Variant: pre.Variant,
|
||||||
|
Version: pre.DictVersion,
|
||||||
|
Players: pre.Players,
|
||||||
|
Seed: seed,
|
||||||
|
DropoutTiles: pre.DropoutTiles,
|
||||||
|
MultipleWordsPerTurn: pre.MultipleWordsPerTurn,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return ReplayTimelineView{}, err
|
||||||
|
}
|
||||||
|
moves, err := svc.store.GetJournal(ctx, gameID)
|
||||||
|
if err != nil {
|
||||||
|
return ReplayTimelineView{}, err
|
||||||
|
}
|
||||||
|
steps := make([]ReplayStep, 0, len(moves)+1)
|
||||||
|
steps = append(steps, snapshotStep(g, nil, nil))
|
||||||
|
for i := range moves {
|
||||||
|
mv := moves[i]
|
||||||
|
before := g.Hand(mv.Seat)
|
||||||
|
if err := replayMove(g, mv); err != nil {
|
||||||
|
if errors.Is(err, engine.ErrIllegalPlay) {
|
||||||
|
g.Abort()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return ReplayTimelineView{}, fmt.Errorf("game: replay-timeline %s move %d: %w", gameID, mv.Seq, err)
|
||||||
|
}
|
||||||
|
moveCopy := mv
|
||||||
|
steps = append(steps, snapshotStep(g, &moveCopy, drawnTiles(before, g.Hand(mv.Seat), usedTiles(mv))))
|
||||||
|
}
|
||||||
|
return ReplayTimelineView{Game: pre, Steps: steps}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// snapshotStep captures the position after applying move (nil for the initial deal): every
|
||||||
|
// seat's rack and score, the turn cursor and the bag size, with the supplied drawn tiles.
|
||||||
|
func snapshotStep(g *engine.Game, move *HistoryMove, drawn []string) ReplayStep {
|
||||||
|
n := g.Players()
|
||||||
|
racks := make([][]string, n)
|
||||||
|
scores := make([]int, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
racks[i] = g.Hand(i)
|
||||||
|
scores[i] = g.Score(i)
|
||||||
|
}
|
||||||
|
return ReplayStep{Move: move, Drawn: drawn, Racks: racks, Scores: scores, ToMove: g.ToMove(), BagLen: g.BagLen()}
|
||||||
|
}
|
||||||
|
|
||||||
|
// usedTiles returns the rack tiles a move consumed ("?" for a blank): the placed tiles of a
|
||||||
|
// play or the swapped tiles of an exchange; a pass or resignation consumes none.
|
||||||
|
func usedTiles(mv HistoryMove) []string {
|
||||||
|
switch mv.Action {
|
||||||
|
case "play":
|
||||||
|
used := make([]string, len(mv.Tiles))
|
||||||
|
for i, t := range mv.Tiles {
|
||||||
|
if t.Blank {
|
||||||
|
used[i] = "?" // a placed blank leaves the rack as the blank marker
|
||||||
|
} else {
|
||||||
|
used[i] = t.Letter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return used
|
||||||
|
case "exchange":
|
||||||
|
return mv.Exchanged
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawnTiles returns the tiles the mover drew from the bag: the post-move rack (after) minus
|
||||||
|
// the tiles kept (before minus used). It compares the racks as multisets, so duplicate
|
||||||
|
// letters are counted correctly.
|
||||||
|
func drawnTiles(before, after, used []string) []string {
|
||||||
|
kept := make(map[string]int, len(before))
|
||||||
|
for _, t := range before {
|
||||||
|
kept[t]++
|
||||||
|
}
|
||||||
|
for _, t := range used {
|
||||||
|
if kept[t] > 0 {
|
||||||
|
kept[t]--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var drawn []string
|
||||||
|
for _, t := range after {
|
||||||
|
if kept[t] > 0 {
|
||||||
|
kept[t]--
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
drawn = append(drawn, t)
|
||||||
|
}
|
||||||
|
return drawn
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUsedTiles(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
mv HistoryMove
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"pass", HistoryMove{Action: "pass"}, nil},
|
||||||
|
{"resign", HistoryMove{Action: "resign"}, nil},
|
||||||
|
{"play with blank", HistoryMove{Action: "play", Tiles: []engine.TileRecord{{Letter: "a"}, {Letter: "b", Blank: true}}}, []string{"a", "?"}},
|
||||||
|
{"exchange", HistoryMove{Action: "exchange", Exchanged: []string{"a", "?"}}, []string{"a", "?"}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := usedTiles(tt.mv); !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Fatalf("usedTiles = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDrawnTiles(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
before, used []string
|
||||||
|
after []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"play refill", []string{"a", "b", "c", "d"}, []string{"a", "b"}, []string{"c", "d", "e", "f"}, []string{"e", "f"}},
|
||||||
|
{"blank played", []string{"?", "a"}, []string{"?"}, []string{"a", "x"}, []string{"x"}},
|
||||||
|
{"pass keeps rack", []string{"a", "b"}, nil, []string{"a", "b"}, nil},
|
||||||
|
{"duplicate letters", []string{"e", "e", "e"}, []string{"e"}, []string{"e", "e", "q"}, []string{"q"}},
|
||||||
|
{"empty bag no refill", []string{"a", "b"}, []string{"a"}, []string{"b"}, nil},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := drawnTiles(tt.before, tt.after, tt.used); !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Fatalf("drawnTiles = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxSeedingRounds caps the first-move draw's tie re-draws. With a real bag a tie
|
||||||
|
// breaks with positive probability each round, so this is reached only by a
|
||||||
|
// degenerate (e.g. test) entropy source that ties forever; the cap turns that into
|
||||||
|
// an error instead of an infinite loop.
|
||||||
|
const maxSeedingRounds = 1000
|
||||||
|
|
||||||
|
// SetupDraw is one recorded tile draw of the first-move seeding — one row of
|
||||||
|
// game_setup_draws (docs/ARCHITECTURE.md §6, §9): the round, the draw order within
|
||||||
|
// it, the seated account that drew, and the decoded tile with its rank. It is
|
||||||
|
// dictionary-independent: the letter, the blank flag and the numeric rank describe
|
||||||
|
// the draw without any alphabet table.
|
||||||
|
type SetupDraw struct {
|
||||||
|
Round int
|
||||||
|
PickNo int
|
||||||
|
Account uuid.UUID
|
||||||
|
Letter string
|
||||||
|
Blank bool
|
||||||
|
Rank int
|
||||||
|
}
|
||||||
|
|
||||||
|
// seedingResult is the outcome of the first-move seeding: the winning account, the
|
||||||
|
// seated accounts rotated so the winner leads (seat 0), and the full draw log to
|
||||||
|
// persist.
|
||||||
|
type seedingResult struct {
|
||||||
|
winner uuid.UUID
|
||||||
|
order []uuid.UUID
|
||||||
|
draws []SetupDraw
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawIntn returns a uniformly random integer in [0, n) for n > 0. It is the
|
||||||
|
// entropy seam of the first-move seeding: production uses crypto/rand (cryptoIntn),
|
||||||
|
// so every draw is honestly random with no single seed; tests inject a
|
||||||
|
// deterministic source.
|
||||||
|
type drawIntn func(n int) (int, error)
|
||||||
|
|
||||||
|
// cryptoIntn draws a uniform integer in [0, n) from crypto/rand — the honest,
|
||||||
|
// seedless entropy the first-move draw requires.
|
||||||
|
func cryptoIntn(n int) (int, error) {
|
||||||
|
v, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("game: first-move draw entropy: %w", err)
|
||||||
|
}
|
||||||
|
return int(v.Int64()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// seedFirstMove runs the official first-move draw over accounts for variant v,
|
||||||
|
// drawing tiles with the entropy source intn. Each round every contender draws one
|
||||||
|
// tile (without replacement) from a fresh full bag; the tile closest to "A" wins, a
|
||||||
|
// blank beating every letter; contenders tied for the best tile re-draw in the next
|
||||||
|
// round until a single leader remains. It returns the leader, the rotation that
|
||||||
|
// seats the leader first (preserving the others' seating order), and every draw for
|
||||||
|
// the record. It performs no I/O beyond calling intn.
|
||||||
|
func seedFirstMove(v engine.Variant, accounts []uuid.UUID, intn drawIntn) (seedingResult, error) {
|
||||||
|
if len(accounts) < 2 {
|
||||||
|
return seedingResult{}, fmt.Errorf("game: first-move seeding needs at least 2 accounts, got %d", len(accounts))
|
||||||
|
}
|
||||||
|
full, err := engine.SetupBag(v)
|
||||||
|
if err != nil {
|
||||||
|
return seedingResult{}, err
|
||||||
|
}
|
||||||
|
contenders := append([]uuid.UUID(nil), accounts...)
|
||||||
|
var draws []SetupDraw
|
||||||
|
for round := 1; ; round++ {
|
||||||
|
if round > maxSeedingRounds {
|
||||||
|
return seedingResult{}, fmt.Errorf("game: first-move seeding unresolved after %d rounds", maxSeedingRounds)
|
||||||
|
}
|
||||||
|
bag := append([]engine.SetupTile(nil), full...)
|
||||||
|
picks := make([]engine.SetupTile, len(contenders))
|
||||||
|
for i, acc := range contenders {
|
||||||
|
tile, rest, err := drawSetupTile(bag, intn)
|
||||||
|
if err != nil {
|
||||||
|
return seedingResult{}, err
|
||||||
|
}
|
||||||
|
bag = rest
|
||||||
|
picks[i] = tile
|
||||||
|
draws = append(draws, SetupDraw{
|
||||||
|
Round: round, PickNo: i, Account: acc,
|
||||||
|
Letter: tile.Letter, Blank: tile.Blank, Rank: tile.Rank,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
winners := bestContenders(contenders, picks)
|
||||||
|
if len(winners) == 1 {
|
||||||
|
return seedingResult{winner: winners[0], order: rotateToFirst(accounts, winners[0]), draws: draws}, nil
|
||||||
|
}
|
||||||
|
contenders = winners
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawSetupTile removes one uniformly random tile from bag using the entropy source
|
||||||
|
// intn and returns it with the shrunk bag (a fresh slice, leaving bag untouched).
|
||||||
|
// It is the per-tile draw primitive — the seam a future manual "player N draws a
|
||||||
|
// tile" tournament API will drive, one call per external request.
|
||||||
|
func drawSetupTile(bag []engine.SetupTile, intn drawIntn) (engine.SetupTile, []engine.SetupTile, error) {
|
||||||
|
if len(bag) == 0 {
|
||||||
|
return engine.SetupTile{}, nil, fmt.Errorf("game: first-move draw from an empty bag")
|
||||||
|
}
|
||||||
|
i, err := intn(len(bag))
|
||||||
|
if err != nil {
|
||||||
|
return engine.SetupTile{}, nil, err
|
||||||
|
}
|
||||||
|
if i < 0 || i >= len(bag) {
|
||||||
|
return engine.SetupTile{}, nil, fmt.Errorf("game: first-move draw index %d out of range %d", i, len(bag))
|
||||||
|
}
|
||||||
|
tile := bag[i]
|
||||||
|
rest := make([]engine.SetupTile, 0, len(bag)-1)
|
||||||
|
rest = append(rest, bag[:i]...)
|
||||||
|
rest = append(rest, bag[i+1:]...)
|
||||||
|
return tile, rest, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bestContenders returns the contenders whose drawn tile has the lowest (best)
|
||||||
|
// rank — the sole winner if one, else the tied set that re-draws. picks is aligned
|
||||||
|
// with contenders by index.
|
||||||
|
func bestContenders(contenders []uuid.UUID, picks []engine.SetupTile) []uuid.UUID {
|
||||||
|
best := picks[0].Rank
|
||||||
|
for _, p := range picks[1:] {
|
||||||
|
if p.Rank < best {
|
||||||
|
best = p.Rank
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var winners []uuid.UUID
|
||||||
|
for i, p := range picks {
|
||||||
|
if p.Rank == best {
|
||||||
|
winners = append(winners, contenders[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return winners
|
||||||
|
}
|
||||||
|
|
||||||
|
// rotateToFirst returns accounts rotated cyclically so winner sits first (seat 0),
|
||||||
|
// preserving the seating order of the rest (docs/ARCHITECTURE.md §6). winner must be
|
||||||
|
// present in accounts.
|
||||||
|
func rotateToFirst(accounts []uuid.UUID, winner uuid.UUID) []uuid.UUID {
|
||||||
|
i := 0
|
||||||
|
for ; i < len(accounts); i++ {
|
||||||
|
if accounts[i] == winner {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]uuid.UUID, 0, len(accounts))
|
||||||
|
out = append(out, accounts[i:]...)
|
||||||
|
out = append(out, accounts[:i]...)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// scriptIntn returns a drawIntn that yields the scripted indices in order, failing
|
||||||
|
// the test if the script is exhausted or an index is out of range. It lets a test
|
||||||
|
// drive the first-move draw deterministically (English SetupBag order: 9 'a' at
|
||||||
|
// 0..8, then 'b' …, blanks last).
|
||||||
|
func scriptIntn(t *testing.T, seq ...int) drawIntn {
|
||||||
|
t.Helper()
|
||||||
|
i := 0
|
||||||
|
return func(n int) (int, error) {
|
||||||
|
if i >= len(seq) {
|
||||||
|
t.Fatalf("intn script exhausted (asked for [0,%d))", n)
|
||||||
|
}
|
||||||
|
v := seq[i]
|
||||||
|
i++
|
||||||
|
if v < 0 || v >= n {
|
||||||
|
t.Fatalf("intn script value %d out of range [0,%d)", v, n)
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeedFirstMoveDirectWinner(t *testing.T) {
|
||||||
|
a, b := uuid.New(), uuid.New()
|
||||||
|
// a draws bag[0]='a' (rank 0); b draws bag[8]='b' (rank 1) → a wins, no tie.
|
||||||
|
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, scriptIntn(t, 0, 8))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seedFirstMove: %v", err)
|
||||||
|
}
|
||||||
|
if res.winner != a {
|
||||||
|
t.Fatalf("winner = %v, want %v", res.winner, a)
|
||||||
|
}
|
||||||
|
if got := res.order; len(got) != 2 || got[0] != a || got[1] != b {
|
||||||
|
t.Fatalf("order = %v, want [a b]", got)
|
||||||
|
}
|
||||||
|
if len(res.draws) != 2 {
|
||||||
|
t.Fatalf("draws = %d, want 2", len(res.draws))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeedFirstMoveBlankSupersedes(t *testing.T) {
|
||||||
|
a, b := uuid.New(), uuid.New()
|
||||||
|
// a draws 'a' (rank 0); after the draw the two blanks sit at 97,98 — b draws
|
||||||
|
// bag[97], a blank, which beats every letter.
|
||||||
|
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, scriptIntn(t, 0, 97))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seedFirstMove: %v", err)
|
||||||
|
}
|
||||||
|
if res.winner != b {
|
||||||
|
t.Fatalf("winner = %v, want %v (blank supersedes)", res.winner, b)
|
||||||
|
}
|
||||||
|
last := res.draws[len(res.draws)-1]
|
||||||
|
if !last.Blank || last.Rank != engine.BlankRank || last.Letter != "?" {
|
||||||
|
t.Fatalf("winning draw = %+v, want a blank (rank %d, '?')", last, engine.BlankRank)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeedFirstMoveTieRedraw(t *testing.T) {
|
||||||
|
a, b, c := uuid.New(), uuid.New(), uuid.New()
|
||||||
|
// Round 1: a→bag[0]='a'(0), b→bag[0]='a'(0), c→bag[7]='b'(1) → a,b tie best.
|
||||||
|
// Round 2 (a,b only): a→bag[0]='a'(0), b→bag[8]='b'(1) → a wins.
|
||||||
|
res, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b, c}, scriptIntn(t, 0, 0, 7, 0, 8))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("seedFirstMove: %v", err)
|
||||||
|
}
|
||||||
|
if res.winner != a {
|
||||||
|
t.Fatalf("winner = %v, want %v", res.winner, a)
|
||||||
|
}
|
||||||
|
if len(res.draws) != 5 {
|
||||||
|
t.Fatalf("draws = %d, want 5 (3 in round 1, 2 in round 2)", len(res.draws))
|
||||||
|
}
|
||||||
|
if res.draws[2].Round != 1 || res.draws[3].Round != 2 {
|
||||||
|
t.Fatalf("round boundaries wrong: %+v", res.draws)
|
||||||
|
}
|
||||||
|
// The full table keeps every account's seating order, winner first.
|
||||||
|
if got := res.order; got[0] != a || got[1] != b || got[2] != c {
|
||||||
|
t.Fatalf("order = %v, want [a b c]", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeedFirstMoveTooFewAccounts(t *testing.T) {
|
||||||
|
if _, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{uuid.New()}, scriptIntn(t)); err == nil {
|
||||||
|
t.Fatal("want error for a single account")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSeedFirstMovePerpetualTieCapped(t *testing.T) {
|
||||||
|
a, b := uuid.New(), uuid.New()
|
||||||
|
// Always drawing bag[0] gives both players an 'a' every round — a tie that never
|
||||||
|
// resolves; the round cap must turn it into an error, not an infinite loop.
|
||||||
|
alwaysZero := drawIntn(func(int) (int, error) { return 0, nil })
|
||||||
|
if _, err := seedFirstMove(engine.VariantEnglish, []uuid.UUID{a, b}, alwaysZero); err == nil {
|
||||||
|
t.Fatal("want error when ties never resolve")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRotateToFirst(t *testing.T) {
|
||||||
|
a, b, c, d := uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
accounts []uuid.UUID
|
||||||
|
winner uuid.UUID
|
||||||
|
want []uuid.UUID
|
||||||
|
}{
|
||||||
|
{"two winner second", []uuid.UUID{a, b}, b, []uuid.UUID{b, a}},
|
||||||
|
{"three winner first", []uuid.UUID{a, b, c}, a, []uuid.UUID{a, b, c}},
|
||||||
|
{"four winner third", []uuid.UUID{a, b, c, d}, c, []uuid.UUID{c, d, a, b}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := rotateToFirst(tt.accounts, tt.winner)
|
||||||
|
if len(got) != len(tt.want) {
|
||||||
|
t.Fatalf("len = %d, want %d", len(got), len(tt.want))
|
||||||
|
}
|
||||||
|
for i := range got {
|
||||||
|
if got[i] != tt.want[i] {
|
||||||
|
t.Fatalf("rotate = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSeatNamesUsesSnapshot checks seatNames returns each seat's stored display-name
|
||||||
|
// snapshot directly, without consulting the account store (svc.accounts is nil here, so
|
||||||
|
// any lookup would be skipped or panic).
|
||||||
|
func TestSeatNamesUsesSnapshot(t *testing.T) {
|
||||||
|
svc := &Service{}
|
||||||
|
g := Game{
|
||||||
|
Players: 2,
|
||||||
|
Seats: []Seat{
|
||||||
|
{Seat: 0, AccountID: uuid.New(), DisplayName: "Аня2007"},
|
||||||
|
{Seat: 1, AccountID: uuid.New(), DisplayName: "DarkWolf"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
got := svc.seatNames(context.Background(), g)
|
||||||
|
want := []string{"Аня2007", "DarkWolf"}
|
||||||
|
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
|
||||||
|
t.Fatalf("seatNames = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSeatDisplayNameFallbackEmpty checks the resolver yields "" — rather than panicking
|
||||||
|
// — for a seat with no snapshot when no account store is available (the empty open seat
|
||||||
|
// and pre-snapshot legacy-row paths).
|
||||||
|
func TestSeatDisplayNameFallbackEmpty(t *testing.T) {
|
||||||
|
svc := &Service{}
|
||||||
|
if got := svc.seatDisplayName(context.Background(), Seat{Seat: 0, AccountID: uuid.New()}); got != "" {
|
||||||
|
t.Errorf("seatDisplayName with no snapshot and no store = %q, want empty", got)
|
||||||
|
}
|
||||||
|
if got := svc.seatDisplayName(context.Background(), Seat{Seat: 1, AccountID: uuid.Nil}); got != "" {
|
||||||
|
t.Errorf("empty-seat name = %q, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,7 +38,22 @@ type Service struct {
|
|||||||
version string
|
version string
|
||||||
clock func() time.Time
|
clock func() time.Time
|
||||||
rng func() int64
|
rng func() int64
|
||||||
|
// firstMoveEntropy returns the entropy source for one game's first-move draw
|
||||||
|
// (docs/ARCHITECTURE.md §6). The default is crypto/rand — an honest, seedless draw;
|
||||||
|
// tests override it via SetFirstMoveEntropy for a deterministic turn order. It is a
|
||||||
|
// factory so a stateful test source restarts cleanly per game.
|
||||||
|
firstMoveEntropy func() drawIntn
|
||||||
pub notify.Publisher
|
pub notify.Publisher
|
||||||
|
// aiTrigger, when set, is called after an honest-AI game is created or advanced and
|
||||||
|
// is still on a robot's potential turn, so the robot replies at once instead of
|
||||||
|
// waiting for the next driver scan. It is fire-and-forget (the robot package wires
|
||||||
|
// its asynchronous TriggerMove); nil disables the fast path (the scan still covers
|
||||||
|
// these games). Kept as a func so the game package never imports the robot package.
|
||||||
|
aiTrigger func(gameID uuid.UUID)
|
||||||
|
// clearNudges, when set, marks the actor's pending nudges in a game read once they
|
||||||
|
// have committed a move (a nudge answered by moving stops counting as unread). It is
|
||||||
|
// best-effort and kept as a func so the game package never imports the social package.
|
||||||
|
clearNudges func(ctx context.Context, gameID, accountID uuid.UUID) error
|
||||||
metrics *gameMetrics
|
metrics *gameMetrics
|
||||||
log *zap.Logger
|
log *zap.Logger
|
||||||
}
|
}
|
||||||
@@ -57,6 +72,7 @@ func NewService(store *Store, accounts *account.Store, registry *engine.Registry
|
|||||||
version: cfg.DictVersion,
|
version: cfg.DictVersion,
|
||||||
clock: clock,
|
clock: clock,
|
||||||
rng: randomSeed,
|
rng: randomSeed,
|
||||||
|
firstMoveEntropy: func() drawIntn { return cryptoIntn },
|
||||||
pub: notify.Nop{},
|
pub: notify.Nop{},
|
||||||
metrics: defaultGameMetrics(),
|
metrics: defaultGameMetrics(),
|
||||||
log: log,
|
log: log,
|
||||||
@@ -75,6 +91,43 @@ func (svc *Service) SetNotifier(p notify.Publisher) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetAITrigger installs the honest-AI fast-move hook called when a vs_ai game is
|
||||||
|
// created or advanced and a robot may now be on the clock. It must be called during
|
||||||
|
// startup wiring; the default (nil) leaves only the periodic driver scan. The robot
|
||||||
|
// package wires its asynchronous TriggerMove here.
|
||||||
|
func (svc *Service) SetAITrigger(trigger func(gameID uuid.UUID)) {
|
||||||
|
svc.aiTrigger = trigger
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetNudgeClearer installs the hook that marks a mover's pending nudges read after
|
||||||
|
// their move commits. It must be called during startup wiring; the default (nil)
|
||||||
|
// leaves nudges to be cleared only when the recipient opens the move history or chat.
|
||||||
|
// The social package wires its ClearNudges here.
|
||||||
|
func (svc *Service) SetNudgeClearer(fn func(ctx context.Context, gameID, accountID uuid.UUID) error) {
|
||||||
|
svc.clearNudges = fn
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetFirstMoveEntropy overrides the entropy source for the first-move draw
|
||||||
|
// (docs/ARCHITECTURE.md §6). It must be called during wiring or test setup before any
|
||||||
|
// game is created; the production default is crypto/rand and is never overridden.
|
||||||
|
// factory returns a fresh draw function per game, so a stateful deterministic test
|
||||||
|
// source restarts cleanly for each game. It exists for deterministic tests.
|
||||||
|
func (svc *Service) SetFirstMoveEntropy(factory func() func(n int) (int, error)) {
|
||||||
|
if factory == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc.firstMoveEntropy = func() drawIntn { return drawIntn(factory()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// triggerAI fires the honest-AI fast-move hook for an active vs_ai game (best-effort,
|
||||||
|
// fire-and-forget). It is a no-op for non-AI games, finished games and when no hook is
|
||||||
|
// installed, so callers can invoke it unconditionally after a create or commit.
|
||||||
|
func (svc *Service) triggerAI(g Game) {
|
||||||
|
if svc.aiTrigger != nil && g.VsAI && g.Status == StatusActive {
|
||||||
|
svc.aiTrigger(g.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// activeVersion returns the dictionary version new games currently pin.
|
// activeVersion returns the dictionary version new games currently pin.
|
||||||
func (svc *Service) activeVersion() string {
|
func (svc *Service) activeVersion() string {
|
||||||
svc.verMu.RLock()
|
svc.verMu.RLock()
|
||||||
@@ -143,24 +196,53 @@ func (svc *Service) Create(ctx context.Context, params CreateParams) (Game, erro
|
|||||||
return Game{}, fmt.Errorf("%w: hints per player must be >= 0", ErrInvalidConfig)
|
return Game{}, fmt.Errorf("%w: hints per player must be >= 0", ErrInvalidConfig)
|
||||||
}
|
}
|
||||||
timeout := params.TurnTimeout
|
timeout := params.TurnTimeout
|
||||||
|
if params.VsAI {
|
||||||
|
// Honest-AI games use the fixed 7-day inactivity clock, not a user-chosen value
|
||||||
|
// from AllowedTurnTimeouts (it is never offered in the creation UI).
|
||||||
|
timeout = AIInactivityTimeout
|
||||||
|
} else {
|
||||||
if timeout == 0 {
|
if timeout == 0 {
|
||||||
timeout = DefaultTurnTimeout
|
timeout = DefaultTurnTimeout
|
||||||
}
|
}
|
||||||
if !allowedTimeout(timeout) {
|
if !allowedTimeout(timeout) {
|
||||||
return Game{}, fmt.Errorf("%w: turn timeout %s not allowed", ErrInvalidConfig, timeout)
|
return Game{}, fmt.Errorf("%w: turn timeout %s not allowed", ErrInvalidConfig, timeout)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
seen := make(map[uuid.UUID]bool, len(params.Seats))
|
seen := make(map[uuid.UUID]bool, len(params.Seats))
|
||||||
for _, id := range params.Seats {
|
for _, id := range params.Seats {
|
||||||
if seen[id] {
|
if seen[id] {
|
||||||
return Game{}, fmt.Errorf("%w: account %s seated twice", ErrInvalidConfig, id)
|
return Game{}, fmt.Errorf("%w: account %s seated twice", ErrInvalidConfig, id)
|
||||||
}
|
}
|
||||||
seen[id] = true
|
seen[id] = true
|
||||||
if _, err := svc.accounts.GetByID(ctx, id); err != nil {
|
}
|
||||||
|
|
||||||
|
// Decide who moves first by the official draw (docs/ARCHITECTURE.md §6): each seated
|
||||||
|
// account draws a tile, the one closest to "A" leads (a blank supersedes all letters),
|
||||||
|
// ties re-drawing until a single leader remains. Each draw uses fresh entropy, not the
|
||||||
|
// game seed, so the recorded draws — persisted with the game — are the only account of
|
||||||
|
// the outcome. The winner takes seat 0; the rest keep their order.
|
||||||
|
seeding, err := seedFirstMove(params.Variant, params.Seats, svc.firstMoveEntropy())
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, engine.ErrUnknownVariant) {
|
||||||
|
return Game{}, fmt.Errorf("%w: %v", ErrInvalidConfig, err)
|
||||||
|
}
|
||||||
|
return Game{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the seats in the drawn turn order, snapshotting each seat's display name. For a
|
||||||
|
// vs-AI game this stamps the robot's seeded account name (unchanged behaviour); a
|
||||||
|
// disguised auto-match robot instead gets a fresh per-game name when the reaper attaches
|
||||||
|
// it (AttachRobot).
|
||||||
|
seats := make([]seatInsert, len(seeding.order))
|
||||||
|
for i, id := range seeding.order {
|
||||||
|
acc, err := svc.accounts.GetByID(ctx, id)
|
||||||
|
if err != nil {
|
||||||
if errors.Is(err, account.ErrNotFound) {
|
if errors.Is(err, account.ErrNotFound) {
|
||||||
return Game{}, fmt.Errorf("%w: account %s not found", ErrInvalidConfig, id)
|
return Game{}, fmt.Errorf("%w: account %s not found", ErrInvalidConfig, id)
|
||||||
}
|
}
|
||||||
return Game{}, err
|
return Game{}, err
|
||||||
}
|
}
|
||||||
|
seats[i] = seatInsert{accountID: id, displayName: acc.DisplayName}
|
||||||
}
|
}
|
||||||
|
|
||||||
seed := params.Seed
|
seed := params.Seed
|
||||||
@@ -200,26 +282,36 @@ func (svc *Service) Create(ctx context.Context, params CreateParams) (Game, erro
|
|||||||
hintsPerPlayer: params.HintsPerPlayer,
|
hintsPerPlayer: params.HintsPerPlayer,
|
||||||
dropoutTiles: params.DropoutTiles.String(),
|
dropoutTiles: params.DropoutTiles.String(),
|
||||||
multipleWordsPerTurn: params.MultipleWordsPerTurn,
|
multipleWordsPerTurn: params.MultipleWordsPerTurn,
|
||||||
|
vsAI: params.VsAI,
|
||||||
}
|
}
|
||||||
if err := svc.store.CreateGame(ctx, ins, params.Seats); err != nil {
|
if err := svc.store.CreateGame(ctx, ins, seats, seeding.draws); err != nil {
|
||||||
return Game{}, err
|
return Game{}, err
|
||||||
}
|
}
|
||||||
svc.cache.put(id, g, params.Variant.String())
|
svc.metrics.recordStarted(ctx, params.Variant, params.VsAI)
|
||||||
svc.metrics.recordStarted(ctx, params.Variant)
|
created, err := svc.store.GetGame(ctx, id)
|
||||||
return svc.store.GetGame(ctx, id)
|
if err != nil {
|
||||||
|
return Game{}, err
|
||||||
|
}
|
||||||
|
svc.cache.put(id, g, params.Variant.String(), created.Seats)
|
||||||
|
// Honest-AI game seated with a robot: if the robot moves first, reply at once
|
||||||
|
// (the periodic driver is the fallback). No-op for every human-only game.
|
||||||
|
svc.triggerAI(created)
|
||||||
|
return created, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenOrJoin enters accountID into auto-match for the variant and per-turn rule in
|
// OpenOrJoin enters accountID into auto-match for the variant and per-turn rule in
|
||||||
// params and returns the game they land in immediately: another waiting player's open
|
// params and returns the game they land in immediately: another waiting player's open
|
||||||
// game (joined=true), the caller's own still-open game on a re-enqueue, or a fresh open
|
// game (joined=true), or a fresh open game seating only the caller with an empty
|
||||||
// game seating only the caller with an empty opponent seat that a human or the reaper's
|
// opponent seat that a human or the reaper's robot fills later. A re-enqueue while the
|
||||||
// robot fills later. openDeadline is when the reaper substitutes a robot into a freshly
|
// caller is already waiting opens another game rather than returning their own.
|
||||||
// opened game (ignored when joining one). The bag seed defaults to random; params.Seed
|
// openDeadline is when the reaper substitutes a robot into a freshly opened game
|
||||||
|
// (ignored when joining one). The bag seed defaults to random; params.Seed
|
||||||
// pins it. First-move fairness comes from seating the caller at seat 0 or seat 1
|
// pins it. First-move fairness comes from seating the caller at seat 0 or seat 1
|
||||||
// (derived from the seed): seated at seat 1, the still-empty seat 0 moves first, so the
|
// (derived from the seed): seated at seat 1, the still-empty seat 0 moves first, so the
|
||||||
// caller just waits for the opponent. It backs the lobby auto-match enqueue.
|
// caller just waits for the opponent. It backs the lobby auto-match enqueue.
|
||||||
func (svc *Service) OpenOrJoin(ctx context.Context, accountID uuid.UUID, params CreateParams, openDeadline time.Time) (Game, bool, error) {
|
func (svc *Service) OpenOrJoin(ctx context.Context, accountID uuid.UUID, params CreateParams, openDeadline time.Time, exclude []uuid.UUID) (Game, bool, error) {
|
||||||
if _, err := svc.accounts.GetByID(ctx, accountID); err != nil {
|
acc, err := svc.accounts.GetByID(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
if errors.Is(err, account.ErrNotFound) {
|
if errors.Is(err, account.ErrNotFound) {
|
||||||
return Game{}, false, fmt.Errorf("%w: account %s not found", ErrInvalidConfig, accountID)
|
return Game{}, false, fmt.Errorf("%w: account %s not found", ErrInvalidConfig, accountID)
|
||||||
}
|
}
|
||||||
@@ -255,18 +347,32 @@ func (svc *Service) OpenOrJoin(ctx context.Context, accountID uuid.UUID, params
|
|||||||
status: StatusOpen,
|
status: StatusOpen,
|
||||||
openDeadline: &deadline,
|
openDeadline: &deadline,
|
||||||
}
|
}
|
||||||
// Seat the caller at seat 0 or seat 1 (seat 0 always moves first); the other seat
|
// Decide the first move now by the official draw, with the not-yet-arrived opponent as a
|
||||||
// is left empty (uuid.Nil) for the opponent.
|
// synthetic placeholder (uuid.Nil): the draw fixes who sits at seat 0 — and so moves
|
||||||
seats := []uuid.UUID{accountID, uuid.Nil}
|
// first — before either player acts (docs/ARCHITECTURE.md §6). The caller takes their
|
||||||
if seed&1 == 1 {
|
// drawn seat; the opponent seat is left empty. The opponent's draw rows are recorded with
|
||||||
seats = []uuid.UUID{uuid.Nil, accountID}
|
// a NULL account and back-filled when a real opponent joins. Each draw uses fresh entropy,
|
||||||
|
// not the game seed. seats/draws are used only when a fresh game is opened.
|
||||||
|
seeding, err := seedFirstMove(params.Variant, []uuid.UUID{accountID, uuid.Nil}, svc.firstMoveEntropy())
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, engine.ErrUnknownVariant) {
|
||||||
|
return Game{}, false, fmt.Errorf("%w: %v", ErrInvalidConfig, err)
|
||||||
}
|
}
|
||||||
gameID, joined, created, err := svc.store.OpenOrJoin(ctx, accountID, ins, seats)
|
return Game{}, false, err
|
||||||
|
}
|
||||||
|
caller := seatInsert{accountID: accountID, displayName: acc.DisplayName}
|
||||||
|
seats := make([]seatInsert, len(seeding.order))
|
||||||
|
for seat, who := range seeding.order {
|
||||||
|
if who == accountID {
|
||||||
|
seats[seat] = caller // the empty opponent seat stays a zero seatInsert
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gameID, joined, created, err := svc.store.OpenOrJoin(ctx, accountID, acc.DisplayName, ins, seats, exclude, seeding.draws)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Game{}, false, err
|
return Game{}, false, err
|
||||||
}
|
}
|
||||||
if created {
|
if created {
|
||||||
svc.metrics.recordStarted(ctx, params.Variant)
|
svc.metrics.recordStarted(ctx, params.Variant, params.VsAI)
|
||||||
}
|
}
|
||||||
g, err := svc.store.GetGame(ctx, gameID)
|
g, err := svc.store.GetGame(ctx, gameID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -275,11 +381,12 @@ func (svc *Service) OpenOrJoin(ctx context.Context, accountID uuid.UUID, params
|
|||||||
return g, joined, nil
|
return g, joined, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AttachRobot seats robotID in the empty opponent seat of open game gameID and flips
|
// AttachRobot seats robotID in the empty opponent seat of open game gameID, stamping
|
||||||
// it to active, returning the now-active game and whether it attached (false, with a
|
// displayName (the robot's fresh per-game name) on the seat, and flips it to active,
|
||||||
// zero Game, when a human joined first). It backs the matchmaking reaper.
|
// returning the now-active game and whether it attached (false, with a zero Game, when a
|
||||||
func (svc *Service) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID) (Game, bool, error) {
|
// human joined first). It backs the matchmaking reaper.
|
||||||
attached, err := svc.store.AttachRobot(ctx, gameID, robotID)
|
func (svc *Service) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID, displayName string) (Game, bool, error) {
|
||||||
|
attached, err := svc.store.AttachRobot(ctx, gameID, robotID, displayName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Game{}, false, err
|
return Game{}, false, err
|
||||||
}
|
}
|
||||||
@@ -368,7 +475,7 @@ func (svc *Service) Resign(ctx context.Context, gameID, accountID uuid.UUID) (Mo
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return MoveResult{}, err
|
return MoveResult{}, err
|
||||||
}
|
}
|
||||||
post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, nil, pre.Seats)
|
post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, nil, pre.Seats, pre.VsAI)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return MoveResult{}, err
|
return MoveResult{}, err
|
||||||
}
|
}
|
||||||
@@ -378,6 +485,68 @@ func (svc *Service) Resign(ctx context.Context, gameID, accountID uuid.UUID) (Mo
|
|||||||
return MoveResult{Move: rec, Game: post}, nil
|
return MoveResult{Move: rec, Game: post}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ForfeitAllForAccount resigns every game the account is currently playing and cancels every game
|
||||||
|
// it has opened but no opponent has joined, returning how many it acted on. It is the game-side
|
||||||
|
// effect of an admin block: the blocked player instantly loses each live game (the opponent
|
||||||
|
// winning, exactly as a manual resignation) and leaves matchmaking so nobody joins a doomed game.
|
||||||
|
// It reuses the per-game resignation path (its lock, commit and live events), so it is safe to
|
||||||
|
// call while play continues and is idempotent — an already-resigned or finished game is skipped.
|
||||||
|
// A per-game failure is logged and skipped so one bad game does not strand the rest; the
|
||||||
|
// turn-timeout sweeper remains the backstop for anything missed in a race.
|
||||||
|
func (svc *Service) ForfeitAllForAccount(ctx context.Context, accountID uuid.UUID) (int, error) {
|
||||||
|
games, err := svc.store.ListGamesForAccount(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
for _, g := range games {
|
||||||
|
if g.Status != StatusActive && g.Status != StatusOpen {
|
||||||
|
continue // a finished game holds no turn to forfeit
|
||||||
|
}
|
||||||
|
acted, err := svc.forfeitOne(ctx, g.ID, accountID)
|
||||||
|
if err != nil {
|
||||||
|
svc.log.Warn("forfeit on block", zap.String("game", g.ID.String()), zap.Error(err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if acted {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// forfeitOne resigns one game on behalf of accountID, or cancels it when it is an open auto-match
|
||||||
|
// game still awaiting an opponent. It reports whether it changed the game. A game that has already
|
||||||
|
// finished, or in which the account no longer holds a seat, is a benign no-op.
|
||||||
|
func (svc *Service) forfeitOne(ctx context.Context, gameID, accountID uuid.UUID) (bool, error) {
|
||||||
|
_, err := svc.Resign(ctx, gameID, accountID)
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
return true, nil
|
||||||
|
case errors.Is(err, ErrNoOpponentYet):
|
||||||
|
// An open game with no opponent cannot be resigned (there is no one to award the win), so
|
||||||
|
// delete it to clear it from the matchmaking pool. If it filled in the race window it is
|
||||||
|
// now active, so resign the seat instead.
|
||||||
|
deleted, derr := svc.store.DeleteOpenGame(ctx, gameID)
|
||||||
|
if derr != nil {
|
||||||
|
return false, derr
|
||||||
|
}
|
||||||
|
if deleted {
|
||||||
|
svc.cache.remove(gameID)
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if _, err := svc.Resign(ctx, gameID, accountID); err != nil &&
|
||||||
|
!errors.Is(err, ErrFinished) && !errors.Is(err, ErrNoOpponentYet) {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
case errors.Is(err, ErrFinished), errors.Is(err, ErrNotAPlayer), errors.Is(err, ErrNotFound):
|
||||||
|
return false, nil
|
||||||
|
default:
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// GameVariant returns just a game's variant. The edge layer uses it to map wire alphabet
|
// GameVariant returns just a game's variant. The edge layer uses it to map wire alphabet
|
||||||
// indices to concrete letters before delegating to the letter-based play, exchange and
|
// indices to concrete letters before delegating to the letter-based play, exchange and
|
||||||
// word-check methods, keeping a single domain path shared with the robot.
|
// word-check methods, keeping a single domain path shared with the robot.
|
||||||
@@ -385,16 +554,6 @@ func (svc *Service) GameVariant(ctx context.Context, gameID uuid.UUID) (engine.V
|
|||||||
return svc.store.GetGameVariant(ctx, gameID)
|
return svc.store.GetGameVariant(ctx, gameID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GameLanguage returns the game's language tag ("en"/"ru"), derived from its variant, so a
|
|
||||||
// game push routes out-of-app to the game's own bot rather than the recipient's last-login bot.
|
|
||||||
func (svc *Service) GameLanguage(ctx context.Context, gameID uuid.UUID) (string, error) {
|
|
||||||
v, err := svc.GameVariant(ctx, gameID)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return v.Language(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// RobotSchedule returns a game's bag seed and turn-start time, for the admin console's
|
// RobotSchedule returns a game's bag seed and turn-start time, for the admin console's
|
||||||
// robot-schedule panel (the deterministic play-to-win intent and next-move ETA).
|
// robot-schedule panel (the deterministic play-to-win intent and next-move ETA).
|
||||||
func (svc *Service) RobotSchedule(ctx context.Context, gameID uuid.UUID) (seed int64, turnStartedAt time.Time, err error) {
|
func (svc *Service) RobotSchedule(ctx context.Context, gameID uuid.UUID) (seed int64, turnStartedAt time.Time, err error) {
|
||||||
@@ -426,8 +585,9 @@ func (svc *Service) transition(ctx context.Context, gameID, accountID uuid.UUID,
|
|||||||
return MoveResult{}, ErrNotAPlayer
|
return MoveResult{}, ErrNotAPlayer
|
||||||
}
|
}
|
||||||
// A move is allowed while the game is active or still open (the starter may move on
|
// A move is allowed while the game is active or still open (the starter may move on
|
||||||
// their turn before an opponent joins); only a finished game rejects it. The turn
|
// their turn before an opponent joins; the first-move draw ran when the game opened, so
|
||||||
// check below keeps the starter off the still-empty opponent seat.
|
// the seats are already fixed); only a finished game rejects it. The turn check below
|
||||||
|
// keeps the starter off the still-empty opponent seat.
|
||||||
if pre.Status == StatusFinished {
|
if pre.Status == StatusFinished {
|
||||||
return MoveResult{}, ErrFinished
|
return MoveResult{}, ErrFinished
|
||||||
}
|
}
|
||||||
@@ -454,11 +614,18 @@ func (svc *Service) transition(ctx context.Context, gameID, accountID uuid.UUID,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return MoveResult{}, err
|
return MoveResult{}, err
|
||||||
}
|
}
|
||||||
post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, exchanged, pre.Seats)
|
post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, exchanged, pre.Seats, pre.VsAI)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return MoveResult{}, err
|
return MoveResult{}, err
|
||||||
}
|
}
|
||||||
svc.afterCommitDrafts(ctx, gameID, accountID, rec)
|
svc.afterCommitDrafts(ctx, gameID, accountID, rec)
|
||||||
|
// A nudge the actor answered by moving stops counting as unread (best-effort; the
|
||||||
|
// move has committed, so a cleanup failure is logged, not surfaced).
|
||||||
|
if svc.clearNudges != nil {
|
||||||
|
if err := svc.clearNudges(ctx, gameID, accountID); err != nil {
|
||||||
|
svc.log.Warn("clear nudges after move", zap.Error(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
// Record the seat's think time (turn start to commit) for the move-duration
|
// Record the seat's think time (turn start to commit) for the move-duration
|
||||||
// metric; the timeout path commits separately and is excluded by design.
|
// metric; the timeout path commits separately and is excluded by design.
|
||||||
svc.metrics.recordMoveDuration(ctx, pre.Variant, post.MoveCount, svc.clock().Sub(pre.TurnStartedAt))
|
svc.metrics.recordMoveDuration(ctx, pre.Variant, post.MoveCount, svc.clock().Sub(pre.TurnStartedAt))
|
||||||
@@ -484,7 +651,7 @@ func (svc *Service) afterCommitDrafts(ctx context.Context, gameID, accountID uui
|
|||||||
// cursor and scores, and on a game-ending move the finish stamp and statistics.
|
// cursor and scores, and on a game-ending move the finish stamp and statistics.
|
||||||
// On a persistence failure it evicts the now-divergent live game so the next
|
// On a persistence failure it evicts the now-divergent live game so the next
|
||||||
// access rebuilds from the journal.
|
// access rebuilds from the journal.
|
||||||
func (svc *Service) commit(ctx context.Context, gameID uuid.UUID, g *engine.Game, rec engine.MoveRecord, action string, rackBefore, exchanged []string, seats []Seat) (Game, error) {
|
func (svc *Service) commit(ctx context.Context, gameID uuid.UUID, g *engine.Game, rec engine.MoveRecord, action string, rackBefore, exchanged []string, seats []Seat, vsAI bool) (Game, error) {
|
||||||
now := svc.clock()
|
now := svc.clock()
|
||||||
logLen := len(g.Log())
|
logLen := len(g.Log())
|
||||||
scores := make([]int, g.Players())
|
scores := make([]int, g.Players())
|
||||||
@@ -515,6 +682,9 @@ func (svc *Service) commit(ctx context.Context, gameID uuid.UUID, g *engine.Game
|
|||||||
c.endReason = "timeout"
|
c.endReason = "timeout"
|
||||||
}
|
}
|
||||||
c.winner = g.Result().Winner
|
c.winner = g.Result().Winner
|
||||||
|
// Honest-AI games are practice and never touch player statistics (like guest
|
||||||
|
// games); a human game records them for its non-guest seats.
|
||||||
|
if !vsAI {
|
||||||
statSeats, err := svc.nonGuestSeats(ctx, seats)
|
statSeats, err := svc.nonGuestSeats(ctx, seats)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
svc.cache.remove(gameID)
|
svc.cache.remove(gameID)
|
||||||
@@ -522,6 +692,7 @@ func (svc *Service) commit(ctx context.Context, gameID uuid.UUID, g *engine.Game
|
|||||||
}
|
}
|
||||||
c.stats = buildStats(g, statSeats)
|
c.stats = buildStats(g, statSeats)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if err := svc.store.CommitMove(ctx, c); err != nil {
|
if err := svc.store.CommitMove(ctx, c); err != nil {
|
||||||
svc.cache.remove(gameID)
|
svc.cache.remove(gameID)
|
||||||
return Game{}, err
|
return Game{}, err
|
||||||
@@ -534,13 +705,17 @@ func (svc *Service) commit(ctx context.Context, gameID uuid.UUID, g *engine.Game
|
|||||||
return Game{}, err
|
return Game{}, err
|
||||||
}
|
}
|
||||||
svc.emitMove(ctx, post, rec, g.BagLen())
|
svc.emitMove(ctx, post, rec, g.BagLen())
|
||||||
|
// Honest-AI game still going: nudge the robot to take its turn at once (the
|
||||||
|
// periodic driver is the fallback). No-op for human games and finished ones.
|
||||||
|
svc.triggerAI(post)
|
||||||
return post, nil
|
return post, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// emitMove publishes the live events for a just-committed move: opponent_moved to
|
// emitMove publishes the live events for a just-committed move: opponent_moved to
|
||||||
// every seat — including the actor's own account, so the mover's other devices (and
|
// every seat — including the actor's own account, so the mover's other devices (and
|
||||||
// their lobby) refresh too — and your_turn to the next mover while the game is still
|
// their lobby) refresh too — and, in human games only, your_turn to the next mover
|
||||||
// active. opponent_moved is in-app only (the gateway never turns it into an
|
// while the game is still active (an honest-AI game suppresses your_turn, since the
|
||||||
|
// robot replies at once). opponent_moved is in-app only (the gateway never turns it into an
|
||||||
// out-of-app push), so the actor is not notified out of band about their own move.
|
// out-of-app push), so the actor is not notified out of band about their own move.
|
||||||
// Delivery is best-effort (notify.Publisher never blocks) and the gateway fans each
|
// Delivery is best-effort (notify.Publisher never blocks) and the gateway fans each
|
||||||
// event out to all of the recipient's live streams.
|
// event out to all of the recipient's live streams.
|
||||||
@@ -555,12 +730,12 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
|||||||
}
|
}
|
||||||
intents = append(intents, notify.OpponentMoved(s.AccountID, post.ID, rec, summary, bagLen))
|
intents = append(intents, notify.OpponentMoved(s.AccountID, post.ID, rec, summary, bagLen))
|
||||||
}
|
}
|
||||||
// Game pushes are routed out-of-app by the game's own language, not the recipient's
|
|
||||||
// last-login bot.
|
|
||||||
lang := post.Variant.Language()
|
|
||||||
switch post.Status {
|
switch post.Status {
|
||||||
case StatusActive:
|
case StatusActive:
|
||||||
if next, ok := seatAccount(post.Seats, post.ToMove); ok {
|
// Honest-AI games suppress your_turn: the robot replies instantly, so a "your turn"
|
||||||
|
// notification would arrive together with the AI's move and carry no value — the
|
||||||
|
// human's UI already advances from opponent_moved. Only human games signal the mover.
|
||||||
|
if next, ok := seatAccount(post.Seats, post.ToMove); ok && !post.VsAI {
|
||||||
deadline := post.TurnStartedAt.Add(post.TurnTimeout)
|
deadline := post.TurnStartedAt.Add(post.TurnTimeout)
|
||||||
action := rec.Action.String()
|
action := rec.Action.String()
|
||||||
word := ""
|
word := ""
|
||||||
@@ -569,7 +744,6 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
|||||||
}
|
}
|
||||||
opponent := svc.displayName(ctx, post.Seats, rec.Player)
|
opponent := svc.displayName(ctx, post.Seats, rec.Player)
|
||||||
yourTurn := notify.YourTurn(next, post.ID, deadline, opponent, action, word, scoreLine(post, post.ToMove), post.MoveCount)
|
yourTurn := notify.YourTurn(next, post.ID, deadline, opponent, action, word, scoreLine(post, post.ToMove), post.MoveCount)
|
||||||
yourTurn.Language = lang
|
|
||||||
intents = append(intents, yourTurn)
|
intents = append(intents, yourTurn)
|
||||||
}
|
}
|
||||||
case StatusFinished:
|
case StatusFinished:
|
||||||
@@ -581,28 +755,37 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
over := notify.GameOver(s.AccountID, post.ID, seatResult(post.Seats, s.Seat), scoreLine(post, s.Seat), summary)
|
over := notify.GameOver(s.AccountID, post.ID, seatResult(post.Seats, s.Seat), scoreLine(post, s.Seat), summary)
|
||||||
over.Language = lang
|
|
||||||
intents = append(intents, over)
|
intents = append(intents, over)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
svc.pub.Publish(intents...)
|
svc.pub.Publish(intents...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// displayName resolves the display name of the account at the given seat, or "" when the seat
|
// seatDisplayName returns the name shown for a seat: its captured display-name snapshot
|
||||||
// is absent or the lookup fails (the enriched push then falls back to its plain text).
|
// (docs/ARCHITECTURE.md §7), falling back to the account's current display name for a
|
||||||
func (svc *Service) displayName(ctx context.Context, seats []Seat, seat int) string {
|
// pre-snapshot legacy row, or "" when neither is available.
|
||||||
if svc.accounts == nil {
|
func (svc *Service) seatDisplayName(ctx context.Context, s Seat) string {
|
||||||
return ""
|
if s.DisplayName != "" {
|
||||||
}
|
return s.DisplayName
|
||||||
id, ok := seatAccount(seats, seat)
|
}
|
||||||
if !ok {
|
if svc.accounts == nil || s.AccountID == uuid.Nil {
|
||||||
return ""
|
|
||||||
}
|
|
||||||
acc, err := svc.accounts.GetByID(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
if acc, err := svc.accounts.GetByID(ctx, s.AccountID); err == nil {
|
||||||
return acc.DisplayName
|
return acc.DisplayName
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// displayName resolves the display name shown for the account at the given seat, or ""
|
||||||
|
// when the seat is absent (the enriched push then falls back to its plain text).
|
||||||
|
func (svc *Service) displayName(ctx context.Context, seats []Seat, seat int) string {
|
||||||
|
for _, s := range seats {
|
||||||
|
if s.Seat == seat {
|
||||||
|
return svc.seatDisplayName(ctx, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// scoreLine formats the running scores with recipientSeat's score first, then the remaining
|
// scoreLine formats the running scores with recipientSeat's score first, then the remaining
|
||||||
@@ -697,36 +880,45 @@ func (svc *Service) timeoutGame(ctx context.Context, gameID uuid.UUID, now time.
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
if _, err := svc.commit(ctx, gameID, g, rec, "timeout", rackBefore, nil, cur.Seats); err != nil {
|
if _, err := svc.commit(ctx, gameID, g, rec, "timeout", rackBefore, nil, cur.Seats, cur.VsAI); err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
svc.metrics.recordAbandoned(ctx, cur.Variant)
|
svc.metrics.recordAbandoned(ctx, cur.Variant, cur.VsAI)
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// EvaluatePlay previews a tentative play for a seated player against the current
|
// EvaluatePlay previews a tentative play for a seated player against the current
|
||||||
// board without committing it: whether it is legal and what it would score.
|
// board without committing it: whether it is legal and what it would score.
|
||||||
func (svc *Service) EvaluatePlay(ctx context.Context, gameID, accountID uuid.UUID, tiles []engine.TileRecord) (EvalResult, error) {
|
func (svc *Service) EvaluatePlay(ctx context.Context, gameID, accountID uuid.UUID, tiles []engine.TileRecord) (EvalResult, error) {
|
||||||
|
unlock := svc.locks.lock(gameID)
|
||||||
|
defer unlock()
|
||||||
|
|
||||||
|
// Hot path: an active game stays cached — the engine game is mutated in place across
|
||||||
|
// moves and evicted only when it finishes — so on a hit the cached live game and its
|
||||||
|
// immutable seat list answer the membership check and the score with no DB read. This
|
||||||
|
// preview is fired on every tile placement, the hottest gameplay call at scale.
|
||||||
|
g, seats, ok := svc.cache.get(gameID)
|
||||||
|
if !ok {
|
||||||
|
// Cold path: load and validate from the store, then replay into the cache.
|
||||||
pre, err := svc.store.GetGame(ctx, gameID)
|
pre, err := svc.store.GetGame(ctx, gameID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return EvalResult{}, err
|
return EvalResult{}, err
|
||||||
}
|
}
|
||||||
if _, ok := pre.seatOf(accountID); !ok {
|
|
||||||
return EvalResult{}, ErrNotAPlayer
|
|
||||||
}
|
|
||||||
if pre.Status == StatusFinished {
|
if pre.Status == StatusFinished {
|
||||||
return EvalResult{}, ErrFinished
|
return EvalResult{}, ErrFinished
|
||||||
}
|
}
|
||||||
|
if g, err = svc.liveGame(ctx, pre); err != nil {
|
||||||
unlock := svc.locks.lock(gameID)
|
|
||||||
defer unlock()
|
|
||||||
g, err := svc.liveGame(ctx, pre)
|
|
||||||
if err != nil {
|
|
||||||
return EvalResult{}, err
|
return EvalResult{}, err
|
||||||
}
|
}
|
||||||
|
seats = pre.Seats
|
||||||
|
}
|
||||||
|
if !seatedIn(seats, accountID) {
|
||||||
|
return EvalResult{}, ErrNotAPlayer
|
||||||
|
}
|
||||||
|
|
||||||
validateStart := time.Now()
|
validateStart := time.Now()
|
||||||
rec, err := g.EvaluatePlay(tiles)
|
rec, err := g.EvaluatePlay(tiles)
|
||||||
svc.metrics.recordValidate(ctx, pre.Variant, validateStart)
|
svc.metrics.recordValidate(ctx, g.Variant(), validateStart)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, engine.ErrIllegalPlay) {
|
if errors.Is(err, engine.ErrIllegalPlay) {
|
||||||
return EvalResult{Valid: false}, nil
|
return EvalResult{Valid: false}, nil
|
||||||
@@ -879,12 +1071,7 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
|
|||||||
}
|
}
|
||||||
|
|
||||||
walletAfter := acc.HintBalance
|
walletAfter := acc.HintBalance
|
||||||
if fromAllowance {
|
if !fromAllowance {
|
||||||
if err := svc.store.SpendHintAllowance(ctx, gameID, seat); err != nil {
|
|
||||||
return HintResult{}, err
|
|
||||||
}
|
|
||||||
used++
|
|
||||||
} else {
|
|
||||||
spent, err := svc.accounts.SpendHint(ctx, accountID)
|
spent, err := svc.accounts.SpendHint(ctx, accountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return HintResult{}, err
|
return HintResult{}, err
|
||||||
@@ -894,7 +1081,14 @@ func (svc *Service) Hint(ctx context.Context, gameID, accountID uuid.UUID) (Hint
|
|||||||
}
|
}
|
||||||
walletAfter--
|
walletAfter--
|
||||||
}
|
}
|
||||||
return HintResult{Move: move, HintsRemaining: hintsRemaining(pre.HintsPerPlayer, used, walletAfter)}, nil
|
// hints_used is the per-game total (allowance + wallet): every hint increments it. The first
|
||||||
|
// HintsPerPlayer hints are the free allowance (so fromAllowance above stays correct); the rest
|
||||||
|
// are charged to the wallet. Counting all hints feeds the player's lifetime hint statistics.
|
||||||
|
if err := svc.store.IncHintsUsed(ctx, gameID, seat); err != nil {
|
||||||
|
return HintResult{}, err
|
||||||
|
}
|
||||||
|
used++
|
||||||
|
return HintResult{Move: move, HintsRemaining: hintsRemaining(pre.HintsPerPlayer, used, walletAfter), WalletBalance: walletAfter}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Candidates returns the to-move player's legal plays for a seated player on
|
// Candidates returns the to-move player's legal plays for a seated player on
|
||||||
@@ -934,6 +1128,20 @@ func (svc *Service) RobotTurns(ctx context.Context, robotIDs []uuid.UUID) ([]Rob
|
|||||||
return svc.store.RobotTurns(ctx, robotIDs)
|
return svc.store.RobotTurns(ctx, robotIDs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RobotTurn returns the robot driver's view of a single active game seating one of
|
||||||
|
// robotIDs, and true, or false when the game holds no pooled robot or is no longer
|
||||||
|
// active. It backs the honest-AI fast-move trigger, which drives just the one game.
|
||||||
|
func (svc *Service) RobotTurn(ctx context.Context, gameID uuid.UUID, robotIDs []uuid.UUID) (RobotTurn, bool, error) {
|
||||||
|
return svc.store.RobotTurnByGame(ctx, gameID, robotIDs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// VsAI reports whether a game is an honest-AI game (games.vs_ai). The social
|
||||||
|
// service uses it to reject chat and nudge in AI games (which otherwise report
|
||||||
|
// status 'active').
|
||||||
|
func (svc *Service) VsAI(ctx context.Context, gameID uuid.UUID) (bool, error) {
|
||||||
|
return svc.store.GameVsAI(ctx, gameID)
|
||||||
|
}
|
||||||
|
|
||||||
// GameState returns a seated player's view of the game: the shared summary plus
|
// GameState returns a seated player's view of the game: the shared summary plus
|
||||||
// their private rack, the bag size and their remaining hint budget.
|
// their private rack, the bag size and their remaining hint budget.
|
||||||
func (svc *Service) GameState(ctx context.Context, gameID, accountID uuid.UUID) (StateView, error) {
|
func (svc *Service) GameState(ctx context.Context, gameID, accountID uuid.UUID) (StateView, error) {
|
||||||
@@ -968,6 +1176,7 @@ func (svc *Service) GameState(ctx context.Context, gameID, accountID uuid.UUID)
|
|||||||
Rack: g.Hand(seat),
|
Rack: g.Hand(seat),
|
||||||
BagLen: g.BagLen(),
|
BagLen: g.BagLen(),
|
||||||
HintsRemaining: hintsRemaining(pre.HintsPerPlayer, pre.Seats[seat].HintsUsed, acc.HintBalance),
|
HintsRemaining: hintsRemaining(pre.HintsPerPlayer, pre.Seats[seat].HintsUsed, acc.HintBalance),
|
||||||
|
WalletBalance: acc.HintBalance,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1001,6 +1210,23 @@ func (svc *Service) Participants(ctx context.Context, gameID uuid.UUID) ([]uuid.
|
|||||||
return seats, g.ToMove, g.Status, nil
|
return seats, g.ToMove, g.Status, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SeatName returns the display name shown for the account seated in the game — the seat's
|
||||||
|
// captured snapshot, falling back to the account's current name (see seatDisplayName) — or ""
|
||||||
|
// when the account holds no seat. It lets the social package name a nudge's sender by the same
|
||||||
|
// per-game identity the rest of the game uses, without exposing the seats.
|
||||||
|
func (svc *Service) SeatName(ctx context.Context, gameID, accountID uuid.UUID) (string, error) {
|
||||||
|
g, err := svc.store.GetGame(ctx, gameID)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for _, s := range g.Seats {
|
||||||
|
if s.AccountID == accountID {
|
||||||
|
return svc.seatDisplayName(ctx, s), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
// SharedGame reports whether accounts a and b are seated together in any game
|
// SharedGame reports whether accounts a and b are seated together in any game
|
||||||
// (active or finished). It backs the social package's "befriend an opponent"
|
// (active or finished). It backs the social package's "befriend an opponent"
|
||||||
// request gate without exposing the games tables; a self-pair is never shared.
|
// request gate without exposing the games tables; a self-pair is never shared.
|
||||||
@@ -1011,13 +1237,45 @@ func (svc *Service) SharedGame(ctx context.Context, a, b uuid.UUID) (bool, error
|
|||||||
return svc.store.SharedGameExists(ctx, a, b)
|
return svc.store.SharedGameExists(ctx, a, b)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListForAccount returns every game the account is seated in, newest first, for the
|
// ListForAccount returns every game the account is seated in, newest first — the full
|
||||||
// lobby's active/finished lists. The live position is not loaded — the summaries come
|
// set behind the admin console, the account-merge count and the block-time forfeit
|
||||||
// straight from the durable rows.
|
// sweep. The player's own lobby uses ListForLobby, which drops the honest-AI games the
|
||||||
|
// player left. The live position is not loaded — the summaries come straight from the
|
||||||
|
// durable rows.
|
||||||
func (svc *Service) ListForAccount(ctx context.Context, accountID uuid.UUID) ([]Game, error) {
|
func (svc *Service) ListForAccount(ctx context.Context, accountID uuid.UUID) ([]Game, error) {
|
||||||
return svc.store.ListGamesForAccount(ctx, accountID)
|
return svc.store.ListGamesForAccount(ctx, accountID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListForLobby returns the games shown in the account's own lobby: ListForAccount minus
|
||||||
|
// the honest-AI games the player left — by resigning or by abandoning to the inactivity
|
||||||
|
// timeout (games.end_reason 'resign'/'timeout') — which drop out of the finished list
|
||||||
|
// automatically. The robot never leaves (it moves at once, never sleeps, never resigns),
|
||||||
|
// so only a human's departure matches; the predicate is a game property, not a seat
|
||||||
|
// check, so it extends to any player should the robot ever resign. Admin and
|
||||||
|
// account-merge views keep using ListForAccount and see the full set.
|
||||||
|
func (svc *Service) ListForLobby(ctx context.Context, accountID uuid.UUID) ([]Game, error) {
|
||||||
|
games, err := svc.ListForAccount(ctx, accountID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
kept := games[:0]
|
||||||
|
for _, g := range games {
|
||||||
|
if g.VsAI && (g.EndReason == "resign" || g.EndReason == "timeout") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kept = append(kept, g)
|
||||||
|
}
|
||||||
|
return kept, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountActiveQuickGames reports how many in-progress quick games the account holds —
|
||||||
|
// the count the simultaneous-game limit (MaxActiveQuickGames) is checked against. It
|
||||||
|
// counts active and still-open quick games (including honest-AI ones) and excludes
|
||||||
|
// friend games created by invitation and finished games. See Store.CountActiveQuickGames.
|
||||||
|
func (svc *Service) CountActiveQuickGames(ctx context.Context, accountID uuid.UUID) (int, error) {
|
||||||
|
return svc.store.CountActiveQuickGames(ctx, accountID)
|
||||||
|
}
|
||||||
|
|
||||||
// HideGame hides a finished game from accountID's own lobby (it stays visible to the other
|
// HideGame hides a finished game from accountID's own lobby (it stays visible to the other
|
||||||
// players); it is irreversible by design. Only a player of a finished game may hide it
|
// players); it is irreversible by design. Only a player of a finished game may hide it
|
||||||
// (ErrNotAPlayer / ErrGameActive otherwise); hiding an already-hidden game is a no-op.
|
// (ErrNotAPlayer / ErrGameActive otherwise); hiding an already-hidden game is a no-op.
|
||||||
@@ -1072,6 +1330,14 @@ func (svc *Service) History(ctx context.Context, gameID uuid.UUID) (HistoryView,
|
|||||||
return HistoryView{Game: g, Moves: moves}, nil
|
return HistoryView{Game: g, Moves: moves}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetupDraws returns a game's recorded first-move draws (docs/ARCHITECTURE.md §6), ordered by
|
||||||
|
// round then pick. It backs the admin console's first-move section. An auto-match opponent's
|
||||||
|
// draws carry uuid.Nil until a real opponent joins and back-fills them; an empty slice means
|
||||||
|
// the game predates the draw record.
|
||||||
|
func (svc *Service) SetupDraws(ctx context.Context, gameID uuid.UUID) ([]SetupDraw, error) {
|
||||||
|
return svc.store.SetupDraws(ctx, gameID)
|
||||||
|
}
|
||||||
|
|
||||||
// ExportGCG renders a game as GCG text from the journal alone (no dictionary). It
|
// ExportGCG renders a game as GCG text from the journal alone (no dictionary). It
|
||||||
// is allowed only on a finished game: exporting an in-progress game would leak the
|
// is allowed only on a finished game: exporting an in-progress game would leak the
|
||||||
// full move journal mid-play, so an active game yields ErrGameActive.
|
// full move journal mid-play, so an active game yields ErrGameActive.
|
||||||
@@ -1087,13 +1353,22 @@ func (svc *Service) ExportGCG(ctx context.Context, gameID uuid.UUID) (string, er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return writeGCG(g, svc.seatNames(ctx, g), moves), nil
|
names := svc.seatNames(ctx, g)
|
||||||
|
if g.VsAI {
|
||||||
|
// Label the robot seat "AI" in an honest-AI game's export, not its pool name.
|
||||||
|
for _, s := range g.Seats {
|
||||||
|
if robot, err := svc.accounts.IsRobot(ctx, s.AccountID); err == nil && robot {
|
||||||
|
names[s.Seat] = aiPlayerName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return writeGCG(g, names, moves), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// liveGame returns the live engine.Game for pre, rebuilding it from the journal
|
// liveGame returns the live engine.Game for pre, rebuilding it from the journal
|
||||||
// on a cache miss. Callers must hold the per-game lock.
|
// on a cache miss. Callers must hold the per-game lock.
|
||||||
func (svc *Service) liveGame(ctx context.Context, pre Game) (*engine.Game, error) {
|
func (svc *Service) liveGame(ctx context.Context, pre Game) (*engine.Game, error) {
|
||||||
if g, ok := svc.cache.get(pre.ID); ok {
|
if g, _, ok := svc.cache.get(pre.ID); ok {
|
||||||
return g, nil
|
return g, nil
|
||||||
}
|
}
|
||||||
g, err := svc.replay(ctx, pre)
|
g, err := svc.replay(ctx, pre)
|
||||||
@@ -1108,7 +1383,7 @@ func (svc *Service) liveGame(ctx context.Context, pre Game) (*engine.Game, error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !g.Over() {
|
if !g.Over() {
|
||||||
svc.cache.put(pre.ID, g, pre.Variant.String())
|
svc.cache.put(pre.ID, g, pre.Variant.String(), pre.Seats)
|
||||||
}
|
}
|
||||||
return g, nil
|
return g, nil
|
||||||
}
|
}
|
||||||
@@ -1199,19 +1474,45 @@ func replayMove(g *engine.Game, mv HistoryMove) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// buildStats derives each seat's statistics contribution from a finished game:
|
// buildStats derives each seat's statistics contribution from a finished game:
|
||||||
// win/loss/draw from the (resignation-aware) winner, the final score, and the
|
// win/loss/draw from the (resignation-aware) winner, the final score, and the best
|
||||||
// best single-move score from the log.
|
// single play from the log — its score and, for the per-variant breakdown, its main
|
||||||
|
// word as rendering tiles. Blank flags are taken from every blank ever placed (so a
|
||||||
|
// blank laid by an earlier move and embedded in the best word is honoured), which is
|
||||||
|
// equivalent to reading the final board since a placed tile never moves.
|
||||||
func buildStats(g *engine.Game, seats []Seat) []statDelta {
|
func buildStats(g *engine.Game, seats []Seat) []statDelta {
|
||||||
res := g.Result()
|
res := g.Result()
|
||||||
best := make(map[int]int)
|
bestRec := make(map[int]engine.MoveRecord)
|
||||||
|
blanks := make(map[[2]int]bool)
|
||||||
|
plays := make(map[int]int) // per player: count of plays (tile placements), for the "moves" stat
|
||||||
for _, rec := range g.Log() {
|
for _, rec := range g.Log() {
|
||||||
if rec.Action == engine.ActionPlay && rec.Score > best[rec.Player] {
|
if rec.Action != engine.ActionPlay {
|
||||||
best[rec.Player] = rec.Score
|
continue
|
||||||
|
}
|
||||||
|
plays[rec.Player]++
|
||||||
|
for _, t := range rec.Tiles {
|
||||||
|
if t.Blank {
|
||||||
|
blanks[[2]int{t.Row, t.Col}] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if cur, ok := bestRec[rec.Player]; !ok || rec.Score > cur.Score {
|
||||||
|
bestRec[rec.Player] = rec
|
||||||
|
}
|
||||||
|
}
|
||||||
|
variant := g.Variant().String()
|
||||||
|
values := letterValues(g.Variant())
|
||||||
out := make([]statDelta, 0, len(seats))
|
out := make([]statDelta, 0, len(seats))
|
||||||
for _, s := range seats {
|
for _, s := range seats {
|
||||||
d := statDelta{accountID: s.AccountID, gamePoints: g.Score(s.Seat), wordPoints: best[s.Seat]}
|
// moves counts the seat's plays; hintsUsed is the seat's total hints this game. Both are
|
||||||
|
// summed into account_stats so the screen can show the hint share (hints_used / moves).
|
||||||
|
d := statDelta{accountID: s.AccountID, gamePoints: g.Score(s.Seat), moves: plays[s.Seat], hintsUsed: s.HintsUsed}
|
||||||
|
if rec, ok := bestRec[s.Seat]; ok {
|
||||||
|
d.wordPoints = rec.Score
|
||||||
|
if rec.Score > 0 {
|
||||||
|
d.bestVariant = variant
|
||||||
|
d.bestScore = rec.Score
|
||||||
|
d.bestTiles = mainWordTiles(rec, blanks, values)
|
||||||
|
}
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
case res.Winner < 0:
|
case res.Winner < 0:
|
||||||
d.draws = 1
|
d.draws = 1
|
||||||
@@ -1225,6 +1526,49 @@ func buildStats(g *engine.Game, seats []Seat) []statDelta {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// letterValues builds a lower-cased letter -> tile value lookup for a variant from the
|
||||||
|
// engine's alphabet table, so a best-move word can be rendered with per-tile values on a
|
||||||
|
// screen (statistics) that has not cached the variant's alphabet. It is empty for an
|
||||||
|
// unrecognised variant, leaving every value zero.
|
||||||
|
func letterValues(v engine.Variant) map[string]int {
|
||||||
|
table, err := engine.AlphabetTable(v)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m := make(map[string]int, len(table))
|
||||||
|
for _, e := range table {
|
||||||
|
m[strings.ToLower(e.Letter)] = e.Value
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// mainWordTiles decodes a play's main word into rendering tiles: each letter with its
|
||||||
|
// tile value (0 for a blank) and blank flag. blanks is the set of board coordinates a
|
||||||
|
// blank was ever placed on; values maps a lower-cased letter to its tile value. It walks
|
||||||
|
// the word from its first-letter coordinate along the play's orientation.
|
||||||
|
func mainWordTiles(rec engine.MoveRecord, blanks map[[2]int]bool, values map[string]int) []account.BestMoveTile {
|
||||||
|
if len(rec.Words) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dr, dc := 0, 1
|
||||||
|
if rec.Dir == engine.Vertical {
|
||||||
|
dr, dc = 1, 0
|
||||||
|
}
|
||||||
|
letters := []rune(rec.Words[0])
|
||||||
|
out := make([]account.BestMoveTile, len(letters))
|
||||||
|
for i, r := range letters {
|
||||||
|
row, col := rec.MainRow+i*dr, rec.MainCol+i*dc
|
||||||
|
blank := blanks[[2]int{row, col}]
|
||||||
|
letter := string(r)
|
||||||
|
value := 0
|
||||||
|
if !blank {
|
||||||
|
value = values[strings.ToLower(letter)]
|
||||||
|
}
|
||||||
|
out[i] = account.BestMoveTile{Letter: letter, Value: value, Blank: blank}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// nonGuestSeats filters out guest seats so the finish-time statistics are
|
// nonGuestSeats filters out guest seats so the finish-time statistics are
|
||||||
// recomputed for durable non-guest accounts only — guests never accrue
|
// recomputed for durable non-guest accounts only — guests never accrue
|
||||||
// statistics (docs/ARCHITECTURE.md §9). It is called once per game, on finish.
|
// statistics (docs/ARCHITECTURE.md §9). It is called once per game, on finish.
|
||||||
@@ -1243,15 +1587,13 @@ func (svc *Service) nonGuestSeats(ctx context.Context, seats []Seat) ([]Seat, er
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// seatNames resolves each seat's display name for GCG export.
|
// seatNames resolves each seat's display name — its captured snapshot, else the
|
||||||
|
// account's current name (seatDisplayName) — for game state and GCG export.
|
||||||
func (svc *Service) seatNames(ctx context.Context, g Game) []string {
|
func (svc *Service) seatNames(ctx context.Context, g Game) []string {
|
||||||
names := make([]string, g.Players)
|
names := make([]string, g.Players)
|
||||||
if svc.accounts == nil {
|
|
||||||
return names
|
|
||||||
}
|
|
||||||
for _, s := range g.Seats {
|
for _, s := range g.Seats {
|
||||||
if acc, err := svc.accounts.GetByID(ctx, s.AccountID); err == nil {
|
if s.Seat >= 0 && s.Seat < len(names) {
|
||||||
names[s.Seat] = acc.DisplayName
|
names[s.Seat] = svc.seatDisplayName(ctx, s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return names
|
return names
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package game
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestMainWordTilesHorizontalWithBlank checks that a horizontal main word is decoded into
|
||||||
|
// tiles along its row, that the per-letter value is looked up from the value table, and that
|
||||||
|
// a blank cell (here the middle 'a') is rendered with a zero value regardless of its letter
|
||||||
|
// value — the blank flag is taken from the placed-blank set, not from this move's own tiles.
|
||||||
|
func TestMainWordTilesHorizontalWithBlank(t *testing.T) {
|
||||||
|
rec := engine.MoveRecord{Dir: engine.Horizontal, MainRow: 7, MainCol: 5, Words: []string{"cat"}}
|
||||||
|
blanks := map[[2]int]bool{{7, 6}: true}
|
||||||
|
values := map[string]int{"c": 3, "a": 1, "t": 1}
|
||||||
|
got := mainWordTiles(rec, blanks, values)
|
||||||
|
want := []account.BestMoveTile{
|
||||||
|
{Letter: "c", Value: 3, Blank: false},
|
||||||
|
{Letter: "a", Value: 0, Blank: true},
|
||||||
|
{Letter: "t", Value: 1, Blank: false},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("mainWordTiles = %+v, want %+v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMainWordTilesVerticalCyrillic checks vertical walk and multi-byte (Cyrillic) letters:
|
||||||
|
// the word must be split by rune, not byte, and laid down its column.
|
||||||
|
func TestMainWordTilesVerticalCyrillic(t *testing.T) {
|
||||||
|
rec := engine.MoveRecord{Dir: engine.Vertical, MainRow: 3, MainCol: 8, Words: []string{"съёмка"}}
|
||||||
|
values := map[string]int{"с": 1, "ъ": 10, "ё": 4, "м": 2, "к": 2, "а": 1}
|
||||||
|
got := mainWordTiles(rec, map[[2]int]bool{}, values)
|
||||||
|
want := []account.BestMoveTile{
|
||||||
|
{Letter: "с", Value: 1}, {Letter: "ъ", Value: 10}, {Letter: "ё", Value: 4},
|
||||||
|
{Letter: "м", Value: 2}, {Letter: "к", Value: 2}, {Letter: "а", Value: 1},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("mainWordTiles = %+v, want %+v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMainWordTilesNoWord checks the defensive nil for a record carrying no words.
|
||||||
|
func TestMainWordTilesNoWord(t *testing.T) {
|
||||||
|
if got := mainWordTiles(engine.MoveRecord{}, nil, nil); got != nil {
|
||||||
|
t.Errorf("mainWordTiles(no words) = %+v, want nil", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+407
-84
@@ -3,6 +3,7 @@ package game
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash/fnv"
|
"hash/fnv"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"github.com/go-jet/jet/v2/qrm"
|
"github.com/go-jet/jet/v2/qrm"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/postgres/jet/backend/model"
|
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||||
@@ -41,6 +43,8 @@ type gameInsert struct {
|
|||||||
dropoutTiles string
|
dropoutTiles string
|
||||||
// multipleWordsPerTurn false selects the single-word rule for the game.
|
// multipleWordsPerTurn false selects the single-word rule for the game.
|
||||||
multipleWordsPerTurn bool
|
multipleWordsPerTurn bool
|
||||||
|
// vsAI marks an honest-AI game (games.vs_ai).
|
||||||
|
vsAI bool
|
||||||
// status is the lifecycle state to create the game in: StatusActive for a normal
|
// status is the lifecycle state to create the game in: StatusActive for a normal
|
||||||
// seated game, StatusOpen for an auto-match game still awaiting an opponent. An
|
// seated game, StatusOpen for an auto-match game still awaiting an opponent. An
|
||||||
// empty string defaults to StatusActive.
|
// empty string defaults to StatusActive.
|
||||||
@@ -51,6 +55,10 @@ type gameInsert struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// statDelta is one account's contribution to its statistics on a game finish.
|
// statDelta is one account's contribution to its statistics on a game finish.
|
||||||
|
// bestVariant/bestScore/bestTiles describe the game's best play for this account when
|
||||||
|
// it scored (bestVariant empty otherwise): the variant label, the play's total score and
|
||||||
|
// its main word as rendering tiles. They feed the per-variant account_best_move upsert,
|
||||||
|
// which keeps only the account's highest-scoring play per variant.
|
||||||
type statDelta struct {
|
type statDelta struct {
|
||||||
accountID uuid.UUID
|
accountID uuid.UUID
|
||||||
wins int
|
wins int
|
||||||
@@ -58,6 +66,11 @@ type statDelta struct {
|
|||||||
draws int
|
draws int
|
||||||
gamePoints int
|
gamePoints int
|
||||||
wordPoints int
|
wordPoints int
|
||||||
|
moves int // plays this game (tile placements), summed into account_stats.moves
|
||||||
|
hintsUsed int // hints used this game (allowance + wallet), summed into account_stats.hints_used
|
||||||
|
bestVariant string
|
||||||
|
bestScore int
|
||||||
|
bestTiles []account.BestMoveTile
|
||||||
}
|
}
|
||||||
|
|
||||||
// commit is everything a single committed transition persists: the journal row,
|
// commit is everything a single committed transition persists: the journal row,
|
||||||
@@ -106,18 +119,30 @@ type activeGame struct {
|
|||||||
turnTimeoutSecs int
|
turnTimeoutSecs int
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateGame inserts the games row and one game_players row per seat (seat 0
|
// seatInsert is one seat to create: the account to seat (uuid.Nil for the still-empty
|
||||||
// first) inside a single transaction.
|
// opponent seat of an open auto-match game) and the display-name snapshot to stamp on
|
||||||
func (s *Store) CreateGame(ctx context.Context, ins gameInsert, seats []uuid.UUID) error {
|
// it — the player's name as of when the seat was taken (account.go, docs/ARCHITECTURE.md §7).
|
||||||
|
type seatInsert struct {
|
||||||
|
accountID uuid.UUID
|
||||||
|
displayName string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateGame inserts the games row, one game_players row per seat (seat 0 first) and
|
||||||
|
// the first-move seeding draws inside a single transaction.
|
||||||
|
func (s *Store) CreateGame(ctx context.Context, ins gameInsert, seats []seatInsert, draws []SetupDraw) error {
|
||||||
return withTx(ctx, s.db, func(tx *sql.Tx) error {
|
return withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||||
return insertGameTx(ctx, tx, ins, seats)
|
if err := insertGameTx(ctx, tx, ins, seats); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return insertSetupDrawsTx(ctx, tx, ins.id, draws)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// insertGameTx inserts the games row and one game_players row per seat (seat 0
|
// insertGameTx inserts the games row and one game_players row per seat (seat 0
|
||||||
// first) on tx. A seat whose account id is uuid.Nil is written with a NULL
|
// first) on tx, stamping each seat's display-name snapshot. A seat whose account id is
|
||||||
// account_id — the still-empty opponent seat of a StatusOpen auto-match game.
|
// uuid.Nil is written with a NULL account_id (and an empty snapshot) — the still-empty
|
||||||
func insertGameTx(ctx context.Context, tx *sql.Tx, ins gameInsert, seats []uuid.UUID) error {
|
// opponent seat of a StatusOpen auto-match game.
|
||||||
|
func insertGameTx(ctx context.Context, tx *sql.Tx, ins gameInsert, seats []seatInsert) error {
|
||||||
status := ins.status
|
status := ins.status
|
||||||
if status == "" {
|
if status == "" {
|
||||||
status = StatusActive
|
status = StatusActive
|
||||||
@@ -130,20 +155,20 @@ func insertGameTx(ctx context.Context, tx *sql.Tx, ins gameInsert, seats []uuid.
|
|||||||
table.Games.GameID, table.Games.Variant, table.Games.DictVersion, table.Games.Seed,
|
table.Games.GameID, table.Games.Variant, table.Games.DictVersion, table.Games.Seed,
|
||||||
table.Games.Status, table.Games.Players, table.Games.TurnTimeoutSecs,
|
table.Games.Status, table.Games.Players, table.Games.TurnTimeoutSecs,
|
||||||
table.Games.HintsAllowed, table.Games.HintsPerPlayer, table.Games.OpenDeadlineAt,
|
table.Games.HintsAllowed, table.Games.HintsPerPlayer, table.Games.OpenDeadlineAt,
|
||||||
table.Games.DropoutTiles, table.Games.MultipleWordsPerTurn,
|
table.Games.DropoutTiles, table.Games.MultipleWordsPerTurn, table.Games.VsAi,
|
||||||
).VALUES(ins.id, ins.variant, ins.dictVersion, ins.seed, status, ins.players,
|
).VALUES(ins.id, ins.variant, ins.dictVersion, ins.seed, status, ins.players,
|
||||||
ins.turnTimeoutSecs, ins.hintsAllowed, ins.hintsPerPlayer, deadline, ins.dropoutTiles, ins.multipleWordsPerTurn)
|
ins.turnTimeoutSecs, ins.hintsAllowed, ins.hintsPerPlayer, deadline, ins.dropoutTiles, ins.multipleWordsPerTurn, ins.vsAI)
|
||||||
if _, err := gi.ExecContext(ctx, tx); err != nil {
|
if _, err := gi.ExecContext(ctx, tx); err != nil {
|
||||||
return fmt.Errorf("insert game: %w", err)
|
return fmt.Errorf("insert game: %w", err)
|
||||||
}
|
}
|
||||||
for seat, accountID := range seats {
|
for seat, si := range seats {
|
||||||
var acc any = accountID
|
var acc any = si.accountID
|
||||||
if accountID == uuid.Nil {
|
if si.accountID == uuid.Nil {
|
||||||
acc = postgres.NULL
|
acc = postgres.NULL
|
||||||
}
|
}
|
||||||
pi := table.GamePlayers.INSERT(
|
pi := table.GamePlayers.INSERT(
|
||||||
table.GamePlayers.GameID, table.GamePlayers.Seat, table.GamePlayers.AccountID,
|
table.GamePlayers.GameID, table.GamePlayers.Seat, table.GamePlayers.AccountID, table.GamePlayers.DisplayName,
|
||||||
).VALUES(ins.id, seat, acc)
|
).VALUES(ins.id, seat, acc, si.displayName)
|
||||||
if _, err := pi.ExecContext(ctx, tx); err != nil {
|
if _, err := pi.ExecContext(ctx, tx); err != nil {
|
||||||
return fmt.Errorf("insert seat %d: %w", seat, err)
|
return fmt.Errorf("insert seat %d: %w", seat, err)
|
||||||
}
|
}
|
||||||
@@ -151,6 +176,30 @@ func insertGameTx(ctx context.Context, tx *sql.Tx, ins gameInsert, seats []uuid.
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// insertSetupDrawsTx appends the first-move seeding draws for game gameID on tx —
|
||||||
|
// the dictionary-independent record of how the first player was chosen
|
||||||
|
// (docs/ARCHITECTURE.md §6). The games row must already exist on tx (the foreign
|
||||||
|
// key), so it runs after insertGameTx. An empty draws slice is a no-op.
|
||||||
|
func insertSetupDrawsTx(ctx context.Context, tx *sql.Tx, gameID uuid.UUID, draws []SetupDraw) error {
|
||||||
|
for _, d := range draws {
|
||||||
|
// A uuid.Nil account marks the synthetic opponent of an auto-match draw, persisted as
|
||||||
|
// a NULL account_id and back-filled when a real opponent joins.
|
||||||
|
var acc any = d.Account
|
||||||
|
if d.Account == uuid.Nil {
|
||||||
|
acc = postgres.NULL
|
||||||
|
}
|
||||||
|
di := table.GameSetupDraws.INSERT(
|
||||||
|
table.GameSetupDraws.GameID, table.GameSetupDraws.Round, table.GameSetupDraws.PickNo,
|
||||||
|
table.GameSetupDraws.AccountID, table.GameSetupDraws.Letter, table.GameSetupDraws.IsBlank,
|
||||||
|
table.GameSetupDraws.DrawRank,
|
||||||
|
).VALUES(gameID, d.Round, d.PickNo, acc, d.Letter, d.Blank, d.Rank)
|
||||||
|
if _, err := di.ExecContext(ctx, tx); err != nil {
|
||||||
|
return fmt.Errorf("insert setup draw round %d pick %d: %w", d.Round, d.PickNo, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// openMatchKey hashes an auto-match bucket (variant + per-turn word rule) into the
|
// openMatchKey hashes an auto-match bucket (variant + per-turn word rule) into the
|
||||||
// advisory-lock key that serialises concurrent enqueues for that bucket, so two
|
// advisory-lock key that serialises concurrent enqueues for that bucket, so two
|
||||||
// players never both open a game instead of pairing.
|
// players never both open a game instead of pairing.
|
||||||
@@ -166,46 +215,42 @@ func openMatchKey(variant string, multipleWords bool) int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// OpenOrJoin atomically resolves an auto-match enqueue for accountID into the game it
|
// OpenOrJoin atomically resolves an auto-match enqueue for accountID into the game it
|
||||||
// lands in: it re-uses the caller's own still-open game (joined=false, created=false,
|
// lands in: it joins another player's waiting open game and flips it active
|
||||||
// a re-enqueue is idempotent), joins another player's waiting open game and flips it
|
// (joined=true), or opens a fresh game seating the caller with an empty opponent seat
|
||||||
// active (joined=true), or opens a fresh game seating the caller with an empty
|
// (created=true). A re-enqueue while the caller already has an open game in the bucket
|
||||||
// opponent seat (created=true). ins supplies the new game's immutable fields and is
|
// opens another fresh game (or joins a different player's) rather than returning the
|
||||||
// used only when a game is created. A transaction-scoped advisory lock on the
|
// caller's own, so tapping "random opponent" again always starts a new search. ins
|
||||||
// (variant, rule) bucket serialises concurrent enqueues so two callers pair rather
|
// supplies the new game's immutable fields and is used only when a game is created. A
|
||||||
// than each opening a game. seats is the two-seat arrangement (the caller and uuid.Nil
|
// transaction-scoped advisory lock on the (variant, rule) bucket serialises concurrent
|
||||||
// for the still-empty opponent, in the chosen order) used only when a game is created.
|
// enqueues so two callers pair rather than each opening a game. seats is the two-seat
|
||||||
func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, ins gameInsert, seats []uuid.UUID) (gameID uuid.UUID, joined, created bool, err error) {
|
// arrangement (the caller and uuid.Nil for the still-empty opponent, in the chosen
|
||||||
|
// order) used only when a game is created; callerName is the caller's display-name
|
||||||
|
// snapshot, stamped on their seat whether they open a fresh game or fill another
|
||||||
|
// player's open one. seats and draws (the first-move draw recorded against the synthetic
|
||||||
|
// opponent, docs/ARCHITECTURE.md §6) are used only when a game is created.
|
||||||
|
func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, callerName string, ins gameInsert, seats []seatInsert, exclude []uuid.UUID, draws []SetupDraw) (gameID uuid.UUID, joined, created bool, err error) {
|
||||||
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
|
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||||
if _, e := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`,
|
if _, e := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`,
|
||||||
openMatchKey(ins.variant, ins.multipleWordsPerTurn)); e != nil {
|
openMatchKey(ins.variant, ins.multipleWordsPerTurn)); e != nil {
|
||||||
return fmt.Errorf("open match lock: %w", e)
|
return fmt.Errorf("open match lock: %w", e)
|
||||||
}
|
}
|
||||||
// 1. The caller's own still-open game for this bucket — a re-enqueue is idempotent.
|
// 1. Another player's open game waiting for an opponent — fill its seat and start it.
|
||||||
var own uuid.UUID
|
// A game whose waiting player is in exclude (the caller's per-user block set, either
|
||||||
switch e := tx.QueryRowContext(ctx,
|
// direction) is skipped, so a block keeps the pair out of the same anonymous game;
|
||||||
`SELECT g.game_id FROM backend.games g
|
// an empty exclude (the "{}" literal) excludes nothing.
|
||||||
JOIN backend.game_players p ON p.game_id = g.game_id
|
|
||||||
WHERE g.status = 'open' AND g.variant = $1 AND g.multiple_words_per_turn = $2 AND p.account_id = $3
|
|
||||||
LIMIT 1`,
|
|
||||||
ins.variant, ins.multipleWordsPerTurn, accountID).Scan(&own); {
|
|
||||||
case e == nil:
|
|
||||||
gameID = own
|
|
||||||
return nil
|
|
||||||
case !errors.Is(e, sql.ErrNoRows):
|
|
||||||
return fmt.Errorf("find own open game: %w", e)
|
|
||||||
}
|
|
||||||
// 2. Another player's open game waiting for an opponent — fill its seat and start it.
|
|
||||||
var other uuid.UUID
|
var other uuid.UUID
|
||||||
switch e := tx.QueryRowContext(ctx,
|
switch e := tx.QueryRowContext(ctx,
|
||||||
`SELECT g.game_id FROM backend.games g
|
`SELECT g.game_id FROM backend.games g
|
||||||
WHERE g.status = 'open' AND g.variant = $1 AND g.multiple_words_per_turn = $2
|
WHERE g.status = 'open' AND g.variant = $1 AND g.multiple_words_per_turn = $2
|
||||||
AND NOT EXISTS (SELECT 1 FROM backend.game_players p
|
AND NOT EXISTS (SELECT 1 FROM backend.game_players p
|
||||||
WHERE p.game_id = g.game_id AND p.account_id = $3)
|
WHERE p.game_id = g.game_id AND p.account_id = $3)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM backend.game_players b
|
||||||
|
WHERE b.game_id = g.game_id AND b.account_id = ANY($4::uuid[]))
|
||||||
ORDER BY g.created_at
|
ORDER BY g.created_at
|
||||||
LIMIT 1 FOR UPDATE SKIP LOCKED`,
|
LIMIT 1 FOR UPDATE SKIP LOCKED`,
|
||||||
ins.variant, ins.multipleWordsPerTurn, accountID).Scan(&other); {
|
ins.variant, ins.multipleWordsPerTurn, accountID, uuidArrayLiteral(exclude)).Scan(&other); {
|
||||||
case e == nil:
|
case e == nil:
|
||||||
if er := fillOpenSeat(ctx, tx, other, accountID); er != nil {
|
if er := fillAndActivate(ctx, tx, other, accountID, callerName); er != nil {
|
||||||
return er
|
return er
|
||||||
}
|
}
|
||||||
gameID, joined = other, true
|
gameID, joined = other, true
|
||||||
@@ -213,20 +258,26 @@ func (s *Store) OpenOrJoin(ctx context.Context, accountID uuid.UUID, ins gameIns
|
|||||||
case !errors.Is(e, sql.ErrNoRows):
|
case !errors.Is(e, sql.ErrNoRows):
|
||||||
return fmt.Errorf("find open game: %w", e)
|
return fmt.Errorf("find open game: %w", e)
|
||||||
}
|
}
|
||||||
// 3. None waiting — open a fresh game seating the caller (the other seat empty).
|
// 2. None waiting — open a fresh game seating the caller (the other seat empty) and
|
||||||
|
// recording the first-move draw; the synthetic opponent's rows carry a NULL account
|
||||||
|
// until a real opponent joins and back-fills them.
|
||||||
if e := insertGameTx(ctx, tx, ins, seats); e != nil {
|
if e := insertGameTx(ctx, tx, ins, seats); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
if e := insertSetupDrawsTx(ctx, tx, ins.id, draws); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
gameID, created = ins.id, true
|
gameID, created = ins.id, true
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
return gameID, joined, created, err
|
return gameID, joined, created, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// AttachRobot fills the empty opponent seat of open game gameID with robotID and
|
// AttachRobot fills the empty opponent seat of open game gameID with robotID, stamping
|
||||||
// flips it to active, returning whether it attached. It is a no-op (false) when the
|
// displayName (the robot's per-game name) on the seat, and flips it to active, returning
|
||||||
// game is no longer open — a human joined first — so the reaper never double-fills.
|
// whether it attached. It is a no-op (false) when the game is no longer open — a human
|
||||||
func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID) (bool, error) {
|
// joined first — so the reaper never double-fills.
|
||||||
|
func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID, displayName string) (bool, error) {
|
||||||
attached := false
|
attached := false
|
||||||
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
|
err := withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||||
var status string
|
var status string
|
||||||
@@ -240,7 +291,7 @@ func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID) (boo
|
|||||||
if status != StatusOpen {
|
if status != StatusOpen {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if e := fillOpenSeat(ctx, tx, gameID, robotID); e != nil {
|
if e := fillAndActivate(ctx, tx, gameID, robotID, displayName); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
attached = true
|
attached = true
|
||||||
@@ -249,14 +300,23 @@ func (s *Store) AttachRobot(ctx context.Context, gameID, robotID uuid.UUID) (boo
|
|||||||
return attached, err
|
return attached, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// fillOpenSeat seats accountID in an open game's empty opponent seat and flips the
|
// fillAndActivate seats accountID in an open game's empty opponent seat — stamping
|
||||||
// game to active, stamping a fresh turn clock. The caller holds the game row.
|
// displayName as the seat's snapshot — back-fills the first-move draw rows the open game
|
||||||
func fillOpenSeat(ctx context.Context, tx *sql.Tx, gameID, accountID uuid.UUID) error {
|
// recorded for the then-unknown opponent (docs/ARCHITECTURE.md §6), and flips the game to
|
||||||
|
// active with a fresh turn clock. The seat the joiner takes was already fixed by the draw at
|
||||||
|
// open time, so the journal (any opening move the starter made while waiting) is never
|
||||||
|
// disturbed. The caller holds the game row.
|
||||||
|
func fillAndActivate(ctx context.Context, tx *sql.Tx, gameID, accountID uuid.UUID, displayName string) error {
|
||||||
if _, err := tx.ExecContext(ctx,
|
if _, err := tx.ExecContext(ctx,
|
||||||
`UPDATE backend.game_players SET account_id = $2 WHERE game_id = $1 AND account_id IS NULL`,
|
`UPDATE backend.game_players SET account_id = $2, display_name = $3 WHERE game_id = $1 AND account_id IS NULL`,
|
||||||
gameID, accountID); err != nil {
|
gameID, accountID, displayName); err != nil {
|
||||||
return fmt.Errorf("fill opponent seat: %w", err)
|
return fmt.Errorf("fill opponent seat: %w", err)
|
||||||
}
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx,
|
||||||
|
`UPDATE backend.game_setup_draws SET account_id = $2 WHERE game_id = $1 AND account_id IS NULL`,
|
||||||
|
gameID, accountID); err != nil {
|
||||||
|
return fmt.Errorf("back-fill opponent draws: %w", err)
|
||||||
|
}
|
||||||
if _, err := tx.ExecContext(ctx,
|
if _, err := tx.ExecContext(ctx,
|
||||||
`UPDATE backend.games SET status = 'active', open_deadline_at = NULL, turn_started_at = now(), updated_at = now()
|
`UPDATE backend.games SET status = 'active', open_deadline_at = NULL, turn_started_at = now(), updated_at = now()
|
||||||
WHERE game_id = $1`, gameID); err != nil {
|
WHERE game_id = $1`, gameID); err != nil {
|
||||||
@@ -295,27 +355,33 @@ func (s *Store) ExpiredOpen(ctx context.Context, now time.Time) ([]OpenGame, err
|
|||||||
// GetGame loads the games row joined with its seats (ordered by seat), or
|
// GetGame loads the games row joined with its seats (ordered by seat), or
|
||||||
// ErrNotFound.
|
// ErrNotFound.
|
||||||
func (s *Store) GetGame(ctx context.Context, id uuid.UUID) (Game, error) {
|
func (s *Store) GetGame(ctx context.Context, id uuid.UUID) (Game, error) {
|
||||||
gstmt := postgres.SELECT(table.Games.AllColumns).
|
// One round-trip: the game joined with its seats. A LEFT JOIN keeps a (would-be)
|
||||||
FROM(table.Games).
|
// seatless game returning the game with no seats, exactly as the prior two-query
|
||||||
|
// version did; ORDER BY seat preserves seat order. The games columns repeat per seat
|
||||||
|
// row — cheap at 2-4 seats, and one round-trip instead of two, which matters because
|
||||||
|
// GetGame is the universal "load the game" step on every game operation.
|
||||||
|
stmt := postgres.SELECT(table.Games.AllColumns, table.GamePlayers.AllColumns).
|
||||||
|
FROM(table.Games.LEFT_JOIN(table.GamePlayers, table.GamePlayers.GameID.EQ(table.Games.GameID))).
|
||||||
WHERE(table.Games.GameID.EQ(postgres.UUID(id))).
|
WHERE(table.Games.GameID.EQ(postgres.UUID(id))).
|
||||||
LIMIT(1)
|
ORDER_BY(table.GamePlayers.Seat.ASC())
|
||||||
var grow model.Games
|
var rows []struct {
|
||||||
if err := gstmt.QueryContext(ctx, s.db, &grow); err != nil {
|
model.Games
|
||||||
if errors.Is(err, qrm.ErrNoRows) {
|
model.GamePlayers
|
||||||
return Game{}, ErrNotFound
|
|
||||||
}
|
}
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
return Game{}, fmt.Errorf("game: get %s: %w", id, err)
|
return Game{}, fmt.Errorf("game: get %s: %w", id, err)
|
||||||
}
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
sstmt := postgres.SELECT(table.GamePlayers.AllColumns).
|
return Game{}, ErrNotFound
|
||||||
FROM(table.GamePlayers).
|
|
||||||
WHERE(table.GamePlayers.GameID.EQ(postgres.UUID(id))).
|
|
||||||
ORDER_BY(table.GamePlayers.Seat.ASC())
|
|
||||||
var srows []model.GamePlayers
|
|
||||||
if err := sstmt.QueryContext(ctx, s.db, &srows); err != nil {
|
|
||||||
return Game{}, fmt.Errorf("game: get seats %s: %w", id, err)
|
|
||||||
}
|
}
|
||||||
return projectGame(grow, srows)
|
seats := make([]model.GamePlayers, 0, len(rows))
|
||||||
|
for i := range rows {
|
||||||
|
// Skip the phantom all-NULL seat row a LEFT JOIN yields for a seatless game.
|
||||||
|
if rows[i].GamePlayers.GameID == id {
|
||||||
|
seats = append(seats, rows[i].GamePlayers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return projectGame(rows[0].Games, seats)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetGameVariant reads just a game's variant — a cheap single-column lookup the edge uses
|
// GetGameVariant reads just a game's variant — a cheap single-column lookup the edge uses
|
||||||
@@ -354,6 +420,26 @@ func (s *Store) SharedGameExists(ctx context.Context, a, b uuid.UUID) (bool, err
|
|||||||
return len(rows) > 0, nil
|
return len(rows) > 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteOpenGame removes a game only while it is still open (an auto-match game awaiting an
|
||||||
|
// opponent), reporting whether a row was deleted. The starter's lone seat and any draft cascade
|
||||||
|
// away with it. It no-ops (false) once the game has filled and become active, so a caller can
|
||||||
|
// fall back to resigning the now-active seat. Used to clear a blocked player from matchmaking.
|
||||||
|
func (s *Store) DeleteOpenGame(ctx context.Context, gameID uuid.UUID) (bool, error) {
|
||||||
|
stmt := table.Games.DELETE().WHERE(
|
||||||
|
table.Games.GameID.EQ(postgres.UUID(gameID)).
|
||||||
|
AND(table.Games.Status.EQ(postgres.String(StatusOpen))),
|
||||||
|
)
|
||||||
|
res, err := stmt.ExecContext(ctx, s.db)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("game: delete open game %s: %w", gameID, err)
|
||||||
|
}
|
||||||
|
n, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("game: delete open game rows %s: %w", gameID, err)
|
||||||
|
}
|
||||||
|
return n > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ListGamesForAccount loads every game the account is seated in (active and
|
// ListGamesForAccount loads every game the account is seated in (active and
|
||||||
// finished), newest first, each joined with its ordered seats. It backs the lobby's
|
// finished), newest first, each joined with its ordered seats. It backs the lobby's
|
||||||
// "my games" lists.
|
// "my games" lists.
|
||||||
@@ -415,6 +501,28 @@ func (s *Store) ListGamesForAccount(ctx context.Context, accountID uuid.UUID) ([
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CountActiveQuickGames counts the account's in-progress quick games — the ones the
|
||||||
|
// simultaneous-game limit (MaxActiveQuickGames) is checked against. It includes both
|
||||||
|
// active and still-open (awaiting-opponent) games, the honest-AI ones among them, and
|
||||||
|
// excludes friend games (those linked to a game_invitations row) and finished games.
|
||||||
|
// A hidden game still occupies a slot, so this is a dedicated count rather than a
|
||||||
|
// filter over ListGamesForAccount (which drops hidden games). Joining on the account's
|
||||||
|
// own seat counts each game once (an open game's empty opponent seat has no account).
|
||||||
|
func (s *Store) CountActiveQuickGames(ctx context.Context, accountID uuid.UUID) (int, error) {
|
||||||
|
// The status literals are game.StatusActive / game.StatusOpen, matching the
|
||||||
|
// games.status CHECK in the baseline migration.
|
||||||
|
const q = `
|
||||||
|
SELECT COUNT(*) FROM backend.games g
|
||||||
|
JOIN backend.game_players gp ON gp.game_id = g.game_id
|
||||||
|
LEFT JOIN backend.game_invitations gi ON gi.game_id = g.game_id
|
||||||
|
WHERE gp.account_id = $1 AND g.status IN ('active', 'open') AND gi.game_id IS NULL`
|
||||||
|
var n int
|
||||||
|
if err := s.db.QueryRowContext(ctx, q, accountID).Scan(&n); err != nil {
|
||||||
|
return 0, fmt.Errorf("game: count active quick games: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
// HideGame hides a game from the account's own lobby list (idempotent). The caller validates the
|
// HideGame hides a game from the account's own lobby list (idempotent). The caller validates the
|
||||||
// game is finished and the account is a player.
|
// game is finished and the account is a player.
|
||||||
func (s *Store) HideGame(ctx context.Context, accountID, gameID uuid.UUID) error {
|
func (s *Store) HideGame(ctx context.Context, accountID, gameID uuid.UUID) error {
|
||||||
@@ -526,6 +634,37 @@ func (s *Store) GetJournal(ctx context.Context, id uuid.UUID) ([]HistoryMove, er
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetupDraws loads the ordered first-move seeding draws for a game (round then pick
|
||||||
|
// order), or an empty slice for a game created before the draw was recorded. It
|
||||||
|
// backs the admin console's first-move section.
|
||||||
|
func (s *Store) SetupDraws(ctx context.Context, id uuid.UUID) ([]SetupDraw, error) {
|
||||||
|
stmt := postgres.SELECT(table.GameSetupDraws.AllColumns).
|
||||||
|
FROM(table.GameSetupDraws).
|
||||||
|
WHERE(table.GameSetupDraws.GameID.EQ(postgres.UUID(id))).
|
||||||
|
ORDER_BY(table.GameSetupDraws.Round.ASC(), table.GameSetupDraws.PickNo.ASC())
|
||||||
|
var rows []model.GameSetupDraws
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return nil, fmt.Errorf("game: get setup draws %s: %w", id, err)
|
||||||
|
}
|
||||||
|
out := make([]SetupDraw, len(rows))
|
||||||
|
for i, r := range rows {
|
||||||
|
// A NULL account is the synthetic opponent of an auto-match draw not yet back-filled.
|
||||||
|
acc := uuid.Nil
|
||||||
|
if r.AccountID != nil {
|
||||||
|
acc = *r.AccountID
|
||||||
|
}
|
||||||
|
out[i] = SetupDraw{
|
||||||
|
Round: int(r.Round),
|
||||||
|
PickNo: int(r.PickNo),
|
||||||
|
Account: acc,
|
||||||
|
Letter: r.Letter,
|
||||||
|
Blank: r.IsBlank,
|
||||||
|
Rank: int(r.DrawRank),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// CommitMove appends the move and applies the post-move game state — the turn
|
// CommitMove appends the move and applies the post-move game state — the turn
|
||||||
// cursor and per-seat scores, plus the finish stamp and statistics when the move
|
// cursor and per-seat scores, plus the finish stamp and statistics when the move
|
||||||
// ended the game — in one transaction.
|
// ended the game — in one transaction.
|
||||||
@@ -576,6 +715,9 @@ func (s *Store) CommitMove(ctx context.Context, c commit) error {
|
|||||||
if err := upsertStats(ctx, tx, d, c.now); err != nil {
|
if err := upsertStats(ctx, tx, d, c.now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := upsertBestMove(ctx, tx, d, c.now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -605,6 +747,9 @@ func (s *Store) VoidGame(ctx context.Context, v voidCommit) error {
|
|||||||
if err := upsertStats(ctx, tx, d, v.now); err != nil {
|
if err := upsertStats(ctx, tx, d, v.now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := upsertBestMove(ctx, tx, d, v.now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
@@ -657,13 +802,17 @@ func upsertStats(ctx context.Context, tx *sql.Tx, d statDelta, now time.Time) er
|
|||||||
draws := row.Draws + int32(d.draws)
|
draws := row.Draws + int32(d.draws)
|
||||||
maxGame := max(row.MaxGamePoints, int32(d.gamePoints))
|
maxGame := max(row.MaxGamePoints, int32(d.gamePoints))
|
||||||
maxWord := max(row.MaxWordPoints, int32(d.wordPoints))
|
maxWord := max(row.MaxWordPoints, int32(d.wordPoints))
|
||||||
|
moves := row.Moves + int32(d.moves)
|
||||||
|
hintsUsed := row.HintsUsed + int32(d.hintsUsed)
|
||||||
|
|
||||||
upd := table.AccountStats.UPDATE(
|
upd := table.AccountStats.UPDATE(
|
||||||
table.AccountStats.Wins, table.AccountStats.Losses, table.AccountStats.Draws,
|
table.AccountStats.Wins, table.AccountStats.Losses, table.AccountStats.Draws,
|
||||||
table.AccountStats.MaxGamePoints, table.AccountStats.MaxWordPoints, table.AccountStats.UpdatedAt,
|
table.AccountStats.MaxGamePoints, table.AccountStats.MaxWordPoints, table.AccountStats.UpdatedAt,
|
||||||
|
table.AccountStats.Moves, table.AccountStats.HintsUsed,
|
||||||
).SET(
|
).SET(
|
||||||
postgres.Int(int64(wins)), postgres.Int(int64(losses)), postgres.Int(int64(draws)),
|
postgres.Int(int64(wins)), postgres.Int(int64(losses)), postgres.Int(int64(draws)),
|
||||||
postgres.Int(int64(maxGame)), postgres.Int(int64(maxWord)), postgres.TimestampzT(now),
|
postgres.Int(int64(maxGame)), postgres.Int(int64(maxWord)), postgres.TimestampzT(now),
|
||||||
|
postgres.Int(int64(moves)), postgres.Int(int64(hintsUsed)),
|
||||||
).WHERE(table.AccountStats.AccountID.EQ(postgres.UUID(d.accountID)))
|
).WHERE(table.AccountStats.AccountID.EQ(postgres.UUID(d.accountID)))
|
||||||
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
if _, err := upd.ExecContext(ctx, tx); err != nil {
|
||||||
return fmt.Errorf("update stats %s: %w", d.accountID, err)
|
return fmt.Errorf("update stats %s: %w", d.accountID, err)
|
||||||
@@ -671,8 +820,41 @@ func upsertStats(ctx context.Context, tx *sql.Tx, d statDelta, now time.Time) er
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SpendHintAllowance increments a seat's per-game hint counter by one.
|
// upsertBestMove records the account's best play for a variant, keeping only the
|
||||||
func (s *Store) SpendHintAllowance(ctx context.Context, gameID uuid.UUID, seat int) error {
|
// highest-scoring one: a first play inserts, a later one replaces it only when it scored
|
||||||
|
// strictly higher (the conditional DO UPDATE makes the upsert atomic under concurrent
|
||||||
|
// finishes without a separate lock). It is a no-op when the finish carries no scoring play
|
||||||
|
// for the account (a draw with no plays, or an exchange/pass-only game).
|
||||||
|
func upsertBestMove(ctx context.Context, tx *sql.Tx, d statDelta, now time.Time) error {
|
||||||
|
if d.bestVariant == "" || len(d.bestTiles) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tiles, err := json.Marshal(d.bestTiles)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marshal best move %s/%s: %w", d.accountID, d.bestVariant, err)
|
||||||
|
}
|
||||||
|
stmt := table.AccountBestMove.
|
||||||
|
INSERT(
|
||||||
|
table.AccountBestMove.AccountID, table.AccountBestMove.Variant,
|
||||||
|
table.AccountBestMove.Score, table.AccountBestMove.Tiles, table.AccountBestMove.UpdatedAt,
|
||||||
|
).
|
||||||
|
VALUES(d.accountID, d.bestVariant, d.bestScore, string(tiles), postgres.TimestampzT(now)).
|
||||||
|
ON_CONFLICT(table.AccountBestMove.AccountID, table.AccountBestMove.Variant).
|
||||||
|
DO_UPDATE(postgres.SET(
|
||||||
|
table.AccountBestMove.Score.SET(table.AccountBestMove.EXCLUDED.Score),
|
||||||
|
table.AccountBestMove.Tiles.SET(table.AccountBestMove.EXCLUDED.Tiles),
|
||||||
|
table.AccountBestMove.UpdatedAt.SET(table.AccountBestMove.EXCLUDED.UpdatedAt),
|
||||||
|
).WHERE(table.AccountBestMove.EXCLUDED.Score.GT(table.AccountBestMove.Score)))
|
||||||
|
if _, err := stmt.ExecContext(ctx, tx); err != nil {
|
||||||
|
return fmt.Errorf("upsert best move %s/%s: %w", d.accountID, d.bestVariant, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncHintsUsed increments a seat's per-game hints-used counter by one. It is called for
|
||||||
|
// every hint — both the free per-game allowance and the wallet-charged ones — so the counter
|
||||||
|
// is the seat's total hints used this game (the first HintsPerPlayer being the allowance).
|
||||||
|
func (s *Store) IncHintsUsed(ctx context.Context, gameID uuid.UUID, seat int) error {
|
||||||
stmt := table.GamePlayers.
|
stmt := table.GamePlayers.
|
||||||
UPDATE(table.GamePlayers.HintsUsed).
|
UPDATE(table.GamePlayers.HintsUsed).
|
||||||
SET(table.GamePlayers.HintsUsed.ADD(postgres.Int(1))).
|
SET(table.GamePlayers.HintsUsed.ADD(postgres.Int(1))).
|
||||||
@@ -681,7 +863,7 @@ func (s *Store) SpendHintAllowance(ctx context.Context, gameID uuid.UUID, seat i
|
|||||||
AND(table.GamePlayers.Seat.EQ(postgres.Int(int64(seat)))),
|
AND(table.GamePlayers.Seat.EQ(postgres.Int(int64(seat)))),
|
||||||
)
|
)
|
||||||
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
if _, err := stmt.ExecContext(ctx, s.db); err != nil {
|
||||||
return fmt.Errorf("game: spend hint allowance: %w", err)
|
return fmt.Errorf("game: increment hints used: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -896,7 +1078,7 @@ func (s *Store) RobotTurns(ctx context.Context, ids []uuid.UUID) ([]RobotTurn, e
|
|||||||
}
|
}
|
||||||
stmt := postgres.SELECT(
|
stmt := postgres.SELECT(
|
||||||
table.Games.GameID, table.Games.ToMove, table.Games.TurnStartedAt,
|
table.Games.GameID, table.Games.ToMove, table.Games.TurnStartedAt,
|
||||||
table.Games.MoveCount, table.Games.Seed,
|
table.Games.MoveCount, table.Games.Seed, table.Games.VsAi,
|
||||||
table.GamePlayers.Seat, table.GamePlayers.AccountID,
|
table.GamePlayers.Seat, table.GamePlayers.AccountID,
|
||||||
).FROM(
|
).FROM(
|
||||||
table.Games.INNER_JOIN(table.GamePlayers, table.GamePlayers.GameID.EQ(table.Games.GameID)),
|
table.Games.INNER_JOIN(table.GamePlayers, table.GamePlayers.GameID.EQ(table.Games.GameID)),
|
||||||
@@ -914,24 +1096,163 @@ func (s *Store) RobotTurns(ctx context.Context, ids []uuid.UUID) ([]RobotTurn, e
|
|||||||
}
|
}
|
||||||
out := make([]RobotTurn, 0, len(rows))
|
out := make([]RobotTurn, 0, len(rows))
|
||||||
for _, r := range rows {
|
for _, r := range rows {
|
||||||
// The filter matches only the robot's (non-null) seat, so AccountID is set.
|
out = append(out, robotTurnFrom(r.Games, r.GamePlayers))
|
||||||
robotID := uuid.Nil
|
|
||||||
if r.GamePlayers.AccountID != nil {
|
|
||||||
robotID = *r.GamePlayers.AccountID
|
|
||||||
}
|
}
|
||||||
out = append(out, RobotTurn{
|
if err := s.fillEndgamePass(ctx, out); err != nil {
|
||||||
GameID: r.Games.GameID,
|
return nil, err
|
||||||
RobotID: robotID,
|
|
||||||
RobotSeat: int(r.GamePlayers.Seat),
|
|
||||||
ToMove: int(r.Games.ToMove),
|
|
||||||
TurnStartedAt: r.Games.TurnStartedAt,
|
|
||||||
MoveCount: int(r.Games.MoveCount),
|
|
||||||
Seed: r.Games.Seed,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RobotTurnByGame returns the robot turn for a single active game — the seat held by
|
||||||
|
// one of ids (the robot pool) — and true, or false when the game is not active, holds
|
||||||
|
// no pooled robot, or is gone. It backs the honest-AI after-commit trigger, which
|
||||||
|
// drives one game at once rather than scanning the whole pool (RobotTurns). It leaves
|
||||||
|
// EndgamePass false: honest-AI games move at once, so the endgame think-time shrink is a
|
||||||
|
// human-mimicry concern computed only on the RobotTurns scan.
|
||||||
|
func (s *Store) RobotTurnByGame(ctx context.Context, gameID uuid.UUID, ids []uuid.UUID) (RobotTurn, bool, error) {
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return RobotTurn{}, false, nil
|
||||||
|
}
|
||||||
|
exprs := make([]postgres.Expression, len(ids))
|
||||||
|
for i, id := range ids {
|
||||||
|
exprs[i] = postgres.UUID(id)
|
||||||
|
}
|
||||||
|
stmt := postgres.SELECT(
|
||||||
|
table.Games.GameID, table.Games.ToMove, table.Games.TurnStartedAt,
|
||||||
|
table.Games.MoveCount, table.Games.Seed, table.Games.VsAi,
|
||||||
|
table.GamePlayers.Seat, table.GamePlayers.AccountID,
|
||||||
|
).FROM(
|
||||||
|
table.Games.INNER_JOIN(table.GamePlayers, table.GamePlayers.GameID.EQ(table.Games.GameID)),
|
||||||
|
).WHERE(
|
||||||
|
table.Games.GameID.EQ(postgres.UUID(gameID)).
|
||||||
|
AND(table.Games.Status.EQ(postgres.String(StatusActive))).
|
||||||
|
AND(table.GamePlayers.AccountID.IN(exprs...)),
|
||||||
|
).LIMIT(1)
|
||||||
|
|
||||||
|
var rows []struct {
|
||||||
|
model.Games
|
||||||
|
model.GamePlayers
|
||||||
|
}
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||||
|
return RobotTurn{}, false, fmt.Errorf("game: robot turn by game: %w", err)
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return RobotTurn{}, false, nil
|
||||||
|
}
|
||||||
|
return robotTurnFrom(rows[0].Games, rows[0].GamePlayers), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// robotTurnFrom projects a games row joined with the robot's seat into a RobotTurn.
|
||||||
|
// The query matches only the robot's (non-null) seat, so AccountID is set.
|
||||||
|
func robotTurnFrom(g model.Games, p model.GamePlayers) RobotTurn {
|
||||||
|
robotID := uuid.Nil
|
||||||
|
if p.AccountID != nil {
|
||||||
|
robotID = *p.AccountID
|
||||||
|
}
|
||||||
|
return RobotTurn{
|
||||||
|
GameID: g.GameID,
|
||||||
|
RobotID: robotID,
|
||||||
|
RobotSeat: int(p.Seat),
|
||||||
|
ToMove: int(g.ToMove),
|
||||||
|
TurnStartedAt: g.TurnStartedAt,
|
||||||
|
MoveCount: int(g.MoveCount),
|
||||||
|
Seed: g.Seed,
|
||||||
|
VsAI: g.VsAi,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fillEndgamePass marks the turns whose game is a dead-drawn endgame — its two most
|
||||||
|
// recent committed moves are both passes, so the board and racks are frozen and the
|
||||||
|
// seated robot is bound to pass again — setting EndgamePass and OppLastMove from the
|
||||||
|
// move journal so the driver can shorten the robot's think time. Turns whose game is
|
||||||
|
// not in that state are left unchanged. A nil or empty slice is a no-op. It runs one
|
||||||
|
// batched journal query for the whole scan, so it adds no per-game round trip.
|
||||||
|
func (s *Store) fillEndgamePass(ctx context.Context, turns []RobotTurn) error {
|
||||||
|
if len(turns) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ids := make([]uuid.UUID, len(turns))
|
||||||
|
for i := range turns {
|
||||||
|
ids[i] = turns[i].GameID
|
||||||
|
}
|
||||||
|
info, err := s.endgamePassInfo(ctx, ids)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i := range turns {
|
||||||
|
if d, ok := info[turns[i].GameID]; ok {
|
||||||
|
turns[i].EndgamePass = true
|
||||||
|
turns[i].OppLastMove = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// endgamePassInfo returns, for each of ids whose two most recent committed moves are
|
||||||
|
// both passes, the human's think time on the most recent of them (the gap between the
|
||||||
|
// last two journal entries' created_at). Games with fewer than two moves, or whose last
|
||||||
|
// two are not both passes, are absent from the map. It reads the move journal only — no
|
||||||
|
// schema change — mirroring the analytics.go duration reports. A negative gap (clock
|
||||||
|
// skew) is floored to zero.
|
||||||
|
func (s *Store) endgamePassInfo(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]time.Duration, error) {
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return map[uuid.UUID]time.Duration{}, nil
|
||||||
|
}
|
||||||
|
const q = `
|
||||||
|
SELECT q.game_id, q.secs FROM (
|
||||||
|
SELECT t.game_id,
|
||||||
|
bool_and(t.action = 'pass') AS both_pass,
|
||||||
|
COUNT(*) AS n,
|
||||||
|
EXTRACT(EPOCH FROM (MAX(t.created_at) - MIN(t.created_at))) AS secs
|
||||||
|
FROM (
|
||||||
|
SELECT m.game_id, m.action, m.created_at,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY m.game_id ORDER BY m.seq DESC) AS rn
|
||||||
|
FROM backend.game_moves m
|
||||||
|
WHERE m.game_id = ANY($1::uuid[])
|
||||||
|
) t
|
||||||
|
WHERE t.rn <= 2
|
||||||
|
GROUP BY t.game_id
|
||||||
|
) q
|
||||||
|
WHERE q.n = 2 AND q.both_pass`
|
||||||
|
rows, err := s.db.QueryContext(ctx, q, uuidArrayLiteral(ids))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("game: endgame pass info: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make(map[uuid.UUID]time.Duration, len(ids))
|
||||||
|
for rows.Next() {
|
||||||
|
var id uuid.UUID
|
||||||
|
var secs float64
|
||||||
|
if err := rows.Scan(&id, &secs); err != nil {
|
||||||
|
return nil, fmt.Errorf("game: scan endgame pass info: %w", err)
|
||||||
|
}
|
||||||
|
if secs < 0 {
|
||||||
|
secs = 0
|
||||||
|
}
|
||||||
|
out[id] = time.Duration(secs * float64(time.Second))
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GameVsAI reports whether a game is an honest-AI game (games.vs_ai) — a cheap
|
||||||
|
// single-column read for the social chat/nudge gate, which must reject both in an
|
||||||
|
// AI game even though it reports status 'active'. ErrNotFound when the game is gone.
|
||||||
|
func (s *Store) GameVsAI(ctx context.Context, id uuid.UUID) (bool, error) {
|
||||||
|
stmt := postgres.SELECT(table.Games.VsAi).
|
||||||
|
FROM(table.Games).
|
||||||
|
WHERE(table.Games.GameID.EQ(postgres.UUID(id))).
|
||||||
|
LIMIT(1)
|
||||||
|
var row model.Games
|
||||||
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||||
|
if errors.Is(err, qrm.ErrNoRows) {
|
||||||
|
return false, ErrNotFound
|
||||||
|
}
|
||||||
|
return false, fmt.Errorf("game: get vs_ai %s: %w", id, err)
|
||||||
|
}
|
||||||
|
return row.VsAi, nil
|
||||||
|
}
|
||||||
|
|
||||||
// GameSeed returns the bag seed a game was dealt from, used to replay it. The
|
// GameSeed returns the bag seed a game was dealt from, used to replay it. The
|
||||||
// seed is server-only state and never travels in the public Game view.
|
// seed is server-only state and never travels in the public Game view.
|
||||||
func (s *Store) GameSeed(ctx context.Context, id uuid.UUID) (int64, error) {
|
func (s *Store) GameSeed(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||||
@@ -1026,6 +1347,7 @@ func projectGame(g model.Games, seats []model.GamePlayers) (Game, error) {
|
|||||||
UpdatedAt: g.UpdatedAt,
|
UpdatedAt: g.UpdatedAt,
|
||||||
}
|
}
|
||||||
out.MultipleWordsPerTurn = g.MultipleWordsPerTurn
|
out.MultipleWordsPerTurn = g.MultipleWordsPerTurn
|
||||||
|
out.VsAI = g.VsAi
|
||||||
if g.EndReason != nil {
|
if g.EndReason != nil {
|
||||||
out.EndReason = *g.EndReason
|
out.EndReason = *g.EndReason
|
||||||
}
|
}
|
||||||
@@ -1047,6 +1369,7 @@ func projectGame(g model.Games, seats []model.GamePlayers) (Game, error) {
|
|||||||
Score: int(p.Score),
|
Score: int(p.Score),
|
||||||
HintsUsed: int(p.HintsUsed),
|
HintsUsed: int(p.HintsUsed),
|
||||||
IsWinner: p.IsWinner,
|
IsWinner: p.IsWinner,
|
||||||
|
DisplayName: p.DisplayName,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
|
|||||||
@@ -65,6 +65,9 @@ var (
|
|||||||
ErrNoHintsLeft = errors.New("game: no hints remaining")
|
ErrNoHintsLeft = errors.New("game: no hints remaining")
|
||||||
// ErrNoHintAvailable is returned when the player has no legal play to reveal.
|
// ErrNoHintAvailable is returned when the player has no legal play to reveal.
|
||||||
ErrNoHintAvailable = errors.New("game: no legal move to suggest")
|
ErrNoHintAvailable = errors.New("game: no legal move to suggest")
|
||||||
|
// ErrGameLimitReached is returned when an account already holds MaxActiveQuickGames
|
||||||
|
// simultaneous quick games and tries to create another game (quick or by invitation).
|
||||||
|
ErrGameLimitReached = errors.New("game: simultaneous game limit reached")
|
||||||
)
|
)
|
||||||
|
|
||||||
// AllowedTurnTimeouts is the set of per-game move clocks a game may be created
|
// AllowedTurnTimeouts is the set of per-game move clocks a game may be created
|
||||||
@@ -79,6 +82,28 @@ var AllowedTurnTimeouts = []time.Duration{
|
|||||||
// zero (the owner's default: a full day).
|
// zero (the owner's default: a full day).
|
||||||
const DefaultTurnTimeout = 24 * time.Hour
|
const DefaultTurnTimeout = 24 * time.Hour
|
||||||
|
|
||||||
|
// AIInactivityTimeout is the move clock for an honest-AI game (CreateParams.VsAI).
|
||||||
|
// These games have no short per-move timeout; instead the player loses a game they
|
||||||
|
// abandon after seven days of inactivity. Because the robot moves immediately, only
|
||||||
|
// the human is ever on the clock, so the per-turn timeout doubles as the abandon
|
||||||
|
// rule (the sweeper resigns the overdue seat). It is set programmatically and is not
|
||||||
|
// one of AllowedTurnTimeouts (never offered in the creation UI).
|
||||||
|
const AIInactivityTimeout = 7 * 24 * time.Hour
|
||||||
|
|
||||||
|
// MaxActiveQuickGames is the cap on a player's simultaneous quick games (human
|
||||||
|
// auto-match and honest-AI), counting both in-progress (StatusActive) and
|
||||||
|
// still-open, awaiting-opponent (StatusOpen) games. Friend games created by
|
||||||
|
// invitation are not counted. At the cap the backend refuses to create a new game
|
||||||
|
// of any kind — quick or by invitation — and the lobby disables "New Game";
|
||||||
|
// accepting an incoming invitation is always allowed. See
|
||||||
|
// Store.CountActiveQuickGames.
|
||||||
|
const MaxActiveQuickGames = 10
|
||||||
|
|
||||||
|
// aiPlayerName labels the robot seat in an honest-AI game's GCG export, so a downloaded
|
||||||
|
// game file shows a clean "AI" rather than the robot's human-like pool name (the in-app
|
||||||
|
// UI shows 🤖 from the game's vs_ai flag).
|
||||||
|
const aiPlayerName = "AI"
|
||||||
|
|
||||||
// CreateParams describes a new game. Seats lists the seated accounts in turn
|
// CreateParams describes a new game. Seats lists the seated accounts in turn
|
||||||
// order (seat 0 moves first); lobby/matchmaking assembles it in a later stage.
|
// order (seat 0 moves first); lobby/matchmaking assembles it in a later stage.
|
||||||
type CreateParams struct {
|
type CreateParams struct {
|
||||||
@@ -92,6 +117,10 @@ type CreateParams struct {
|
|||||||
// MultipleWordsPerTurn true selects standard Scrabble; false the single-word rule —
|
// MultipleWordsPerTurn true selects standard Scrabble; false the single-word rule —
|
||||||
// only the main word is validated and scored. Russian games default to false.
|
// only the main word is validated and scored. Russian games default to false.
|
||||||
MultipleWordsPerTurn bool
|
MultipleWordsPerTurn bool
|
||||||
|
// VsAI creates an honest-AI game against a pooled robot (see games.vs_ai): the
|
||||||
|
// robot is seated at once, the move clock is AIInactivityTimeout, and chat/nudge
|
||||||
|
// and finish-time statistics are suppressed. Set by the lobby's AI-match path.
|
||||||
|
VsAI bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Game is the persisted state of a match: the games row joined with its seats.
|
// Game is the persisted state of a match: the games row joined with its seats.
|
||||||
@@ -115,6 +144,9 @@ type Game struct {
|
|||||||
FinishedAt *time.Time
|
FinishedAt *time.Time
|
||||||
// MultipleWordsPerTurn true selects standard Scrabble; false the single-word rule.
|
// MultipleWordsPerTurn true selects standard Scrabble; false the single-word rule.
|
||||||
MultipleWordsPerTurn bool
|
MultipleWordsPerTurn bool
|
||||||
|
// VsAI is true for an honest-AI game (games.vs_ai): the opponent is a robot the
|
||||||
|
// player knowingly chose, shown as 🤖, with chat/nudge disabled and no statistics.
|
||||||
|
VsAI bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Seat is one player's standing in a game.
|
// Seat is one player's standing in a game.
|
||||||
@@ -122,8 +154,15 @@ type Seat struct {
|
|||||||
Seat int
|
Seat int
|
||||||
AccountID uuid.UUID
|
AccountID uuid.UUID
|
||||||
Score int
|
Score int
|
||||||
|
// HintsUsed is the total hints the seat used this game — both the free per-game allowance
|
||||||
|
// and the wallet-charged ones (the first HintsPerPlayer being the allowance).
|
||||||
HintsUsed int
|
HintsUsed int
|
||||||
IsWinner bool
|
IsWinner bool
|
||||||
|
// DisplayName is the seat's display-name snapshot, captured when the seat was taken
|
||||||
|
// (the human's then-current name, or a disguised robot's per-game name). Empty for a
|
||||||
|
// still-empty open seat or a pre-snapshot legacy row, where readers fall back to the
|
||||||
|
// account's current display name (docs/ARCHITECTURE.md §7).
|
||||||
|
DisplayName string
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenGame identifies an auto-match game waiting for an opponent whose robot
|
// OpenGame identifies an auto-match game waiting for an opponent whose robot
|
||||||
@@ -145,6 +184,18 @@ func (g Game) seatOf(accountID uuid.UUID) (int, bool) {
|
|||||||
return 0, false
|
return 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// seatedIn reports whether accountID holds a seat in seats. It backs the read-side
|
||||||
|
// membership check against the cached, immutable seat list, so a hot read can skip
|
||||||
|
// loading the game from the store.
|
||||||
|
func seatedIn(seats []Seat, accountID uuid.UUID) bool {
|
||||||
|
for _, s := range seats {
|
||||||
|
if s.AccountID == accountID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// MoveResult is the outcome of a committed transition: the decoded move and the
|
// MoveResult is the outcome of a committed transition: the decoded move and the
|
||||||
// post-move game, plus the actor's own refilled rack and the bag size after the draw
|
// post-move game, plus the actor's own refilled rack and the bag size after the draw
|
||||||
// (Rack/BagLen), so the mover renders the next state from the response without a
|
// (Rack/BagLen), so the mover renders the next state from the response without a
|
||||||
@@ -157,10 +208,13 @@ type MoveResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// HintResult is a revealed hint and the requesting player's remaining hint
|
// HintResult is a revealed hint and the requesting player's remaining hint
|
||||||
// budget (per-seat allowance plus profile wallet) after spending one.
|
// budget (per-seat allowance plus profile wallet) after spending one. WalletBalance is
|
||||||
|
// the global wallet alone, so the client can keep its live wallet authoritative and
|
||||||
|
// re-derive the per-game allowance (HintsRemaining - WalletBalance).
|
||||||
type HintResult struct {
|
type HintResult struct {
|
||||||
Move engine.MoveRecord
|
Move engine.MoveRecord
|
||||||
HintsRemaining int
|
HintsRemaining int
|
||||||
|
WalletBalance int
|
||||||
}
|
}
|
||||||
|
|
||||||
// EvalResult previews a tentative play without committing it. Dir is the
|
// EvalResult previews a tentative play without committing it. Dir is the
|
||||||
@@ -183,6 +237,9 @@ type StateView struct {
|
|||||||
Rack []string
|
Rack []string
|
||||||
BagLen int
|
BagLen int
|
||||||
HintsRemaining int
|
HintsRemaining int
|
||||||
|
// WalletBalance is the player's global hint-wallet balance alone (HintsRemaining folds
|
||||||
|
// it in with the per-game allowance), so the client keeps the wallet live across games.
|
||||||
|
WalletBalance int
|
||||||
}
|
}
|
||||||
|
|
||||||
// HistoryMove is one decoded journal row, independent of any dictionary.
|
// HistoryMove is one decoded journal row, independent of any dictionary.
|
||||||
@@ -220,6 +277,18 @@ type RobotTurn struct {
|
|||||||
TurnStartedAt time.Time
|
TurnStartedAt time.Time
|
||||||
MoveCount int
|
MoveCount int
|
||||||
Seed int64
|
Seed int64
|
||||||
|
// VsAI is true when the game is an honest-AI game: the driver then makes the
|
||||||
|
// robot move immediately, with no sleep window and no proactive nudge.
|
||||||
|
VsAI bool
|
||||||
|
// EndgamePass is true when the two most recent committed moves are both passes, so
|
||||||
|
// the board and racks are frozen and the robot is bound to pass again. The driver
|
||||||
|
// then shortens the robot's think time (see robot.endgamePassDelay) so a decided
|
||||||
|
// game is not dragged out. It is false until at least two moves exist.
|
||||||
|
EndgamePass bool
|
||||||
|
// OppLastMove is the human's think time on the most recent move — the gap between
|
||||||
|
// the last two journal entries — used to scale the shortened endgame think time. It
|
||||||
|
// is meaningful only when EndgamePass is true (zero otherwise).
|
||||||
|
OppLastMove time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complaint is a word-check complaint in the admin review queue. It is filed
|
// Complaint is a word-check complaint in the admin review queue. It is filed
|
||||||
|
|||||||
@@ -89,7 +89,8 @@ func TestGetStatsZeroForFreshAccount(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("get stats: %v", err)
|
t.Fatalf("get stats: %v", err)
|
||||||
}
|
}
|
||||||
if (st != account.Stats{}) {
|
zero := st.Wins == 0 && st.Losses == 0 && st.Draws == 0 && st.MaxGamePoints == 0 && st.MaxWordPoints == 0
|
||||||
|
if !zero || len(st.BestMoves) != 0 {
|
||||||
t.Fatalf("fresh stats = %+v, want zero", st)
|
t.Fatalf("fresh stats = %+v, want zero", st)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,10 +118,13 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
|||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
ext := "tg-" + uuid.NewString()
|
ext := "tg-" + uuid.NewString()
|
||||||
|
|
||||||
acc, err := store.ProvisionTelegram(ctx, ext, "ru-RU", "thehandle", "Иван")
|
acc, created, err := store.ProvisionTelegram(ctx, ext, "ru-RU", "thehandle", "Иван")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision telegram: %v", err)
|
t.Fatalf("provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
|
if !created {
|
||||||
|
t.Error("created = false on first contact, want true")
|
||||||
|
}
|
||||||
if acc.PreferredLanguage != "ru" {
|
if acc.PreferredLanguage != "ru" {
|
||||||
t.Errorf("PreferredLanguage = %q, want ru", acc.PreferredLanguage)
|
t.Errorf("PreferredLanguage = %q, want ru", acc.PreferredLanguage)
|
||||||
}
|
}
|
||||||
@@ -132,10 +136,13 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A later login with different fields returns the same account, unchanged.
|
// A later login with different fields returns the same account, unchanged.
|
||||||
again, err := store.ProvisionTelegram(ctx, ext, "en", "other", "Other")
|
again, created, err := store.ProvisionTelegram(ctx, ext, "en", "other", "Other")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("re-provision telegram: %v", err)
|
t.Fatalf("re-provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
|
if created {
|
||||||
|
t.Error("created = true on a repeat login, want false")
|
||||||
|
}
|
||||||
if again.ID != acc.ID {
|
if again.ID != acc.ID {
|
||||||
t.Errorf("re-provision id = %s, want %s", again.ID, acc.ID)
|
t.Errorf("re-provision id = %s, want %s", again.ID, acc.ID)
|
||||||
}
|
}
|
||||||
@@ -149,7 +156,7 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
|||||||
// language CHECK.
|
// language CHECK.
|
||||||
func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
acc, err := account.NewStore(testDB).ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "fr", "", "")
|
acc, _, err := account.NewStore(testDB).ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "fr", "", "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision telegram: %v", err)
|
t.Fatalf("provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
@@ -158,46 +165,6 @@ func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestServiceLanguageRoundTrip checks SetServiceLanguage persists the push-routing
|
|
||||||
// language (the bot a Telegram user last signed in through): a fresh account has
|
|
||||||
// none, a set value reads back, a later login overwrites it (last-login-wins), and
|
|
||||||
// an empty value is a no-op. The push-target route coalesces it with the preferred
|
|
||||||
// language.
|
|
||||||
func TestServiceLanguageRoundTrip(t *testing.T) {
|
|
||||||
ctx := context.Background()
|
|
||||||
store := account.NewStore(testDB)
|
|
||||||
acc, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provision telegram: %v", err)
|
|
||||||
}
|
|
||||||
if acc.ServiceLanguage != "" {
|
|
||||||
t.Errorf("fresh ServiceLanguage = %q, want empty", acc.ServiceLanguage)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := store.SetServiceLanguage(ctx, acc.ID, "ru"); err != nil {
|
|
||||||
t.Fatalf("set service language: %v", err)
|
|
||||||
}
|
|
||||||
if got, err := store.GetByID(ctx, acc.ID); err != nil {
|
|
||||||
t.Fatalf("get by id: %v", err)
|
|
||||||
} else if got.ServiceLanguage != "ru" {
|
|
||||||
t.Errorf("ServiceLanguage = %q, want ru", got.ServiceLanguage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A later login through the other bot updates it; a subsequent empty value
|
|
||||||
// (a non-Telegram login) leaves it unchanged.
|
|
||||||
if err := store.SetServiceLanguage(ctx, acc.ID, "en"); err != nil {
|
|
||||||
t.Fatalf("update service language: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.SetServiceLanguage(ctx, acc.ID, ""); err != nil {
|
|
||||||
t.Fatalf("noop service language: %v", err)
|
|
||||||
}
|
|
||||||
if got, err := store.GetByID(ctx, acc.ID); err != nil {
|
|
||||||
t.Fatalf("get by id: %v", err)
|
|
||||||
} else if got.ServiceLanguage != "en" {
|
|
||||||
t.Errorf("ServiceLanguage after update+noop = %q, want en", got.ServiceLanguage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHighRateFlagRoundTrip covers the soft high-rate marker: a fresh account
|
// TestHighRateFlagRoundTrip covers the soft high-rate marker: a fresh account
|
||||||
// is unflagged, FlagHighRate stamps it exactly once (a second sustained episode
|
// is unflagged, FlagHighRate stamps it exactly once (a second sustained episode
|
||||||
// never moves the timestamp), ClearHighRateFlag reverses it, and a re-flag after
|
// never moves the timestamp), ClearHighRateFlag reverses it, and a re-flag after
|
||||||
@@ -205,7 +172,7 @@ func TestServiceLanguageRoundTrip(t *testing.T) {
|
|||||||
func TestHighRateFlagRoundTrip(t *testing.T) {
|
func TestHighRateFlagRoundTrip(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
acc, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision telegram: %v", err)
|
t.Fatalf("provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
@@ -261,7 +228,7 @@ func TestIdentityExternalID(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
ext := "tg-" + uuid.NewString()
|
ext := "tg-" + uuid.NewString()
|
||||||
acc, err := store.ProvisionTelegram(ctx, ext, "en", "", "Tg User")
|
acc, _, err := store.ProvisionTelegram(ctx, ext, "en", "", "Tg User")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision telegram: %v", err)
|
t.Fatalf("provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
@@ -286,7 +253,7 @@ func TestIdentityExternalID(t *testing.T) {
|
|||||||
func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
acc, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision telegram: %v", err)
|
t.Fatalf("provision telegram: %v", err)
|
||||||
}
|
}
|
||||||
@@ -298,6 +265,7 @@ func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
|||||||
PreferredLanguage: "en",
|
PreferredLanguage: "en",
|
||||||
TimeZone: "UTC",
|
TimeZone: "UTC",
|
||||||
NotificationsInAppOnly: false,
|
NotificationsInAppOnly: false,
|
||||||
|
VariantPreferences: []string{"erudit_ru"},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("update profile: %v", err)
|
t.Fatalf("update profile: %v", err)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package inttest
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -205,6 +206,12 @@ func TestConsoleGameDetailRobotSchedule(t *testing.T) {
|
|||||||
if !strings.Contains(body, "~40%") {
|
if !strings.Contains(body, "~40%") {
|
||||||
t.Error("robot play-to-win target caption missing")
|
t.Error("robot play-to-win target caption missing")
|
||||||
}
|
}
|
||||||
|
if !strings.Contains(body, "First-move draw") {
|
||||||
|
t.Error("first-move draw section missing from the game detail")
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, `id="replay-board"`) {
|
||||||
|
t.Error("replay board container missing from the game detail")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestConsoleThrottledViewAndFlagClear drives the rate-limit surface end to
|
// TestConsoleThrottledViewAndFlagClear drives the rate-limit surface end to
|
||||||
@@ -215,7 +222,7 @@ func TestConsoleGameDetailRobotSchedule(t *testing.T) {
|
|||||||
func TestConsoleThrottledViewAndFlagClear(t *testing.T) {
|
func TestConsoleThrottledViewAndFlagClear(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
accounts := account.NewStore(testDB)
|
accounts := account.NewStore(testDB)
|
||||||
acc, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Throttled Player")
|
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Throttled Player")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision: %v", err)
|
t.Fatalf("provision: %v", err)
|
||||||
}
|
}
|
||||||
@@ -273,6 +280,76 @@ func TestConsoleThrottledViewAndFlagClear(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestConsoleGrantHints drives the admin hint-wallet grant end to end: the card shows the form,
|
||||||
|
// the action is CSRF-guarded, a same-origin grant adds to the wallet, a second grant adds again
|
||||||
|
// (rather than replacing), the inclusive per-grant cap is accepted, and an out-of-range or
|
||||||
|
// non-numeric amount is refused without changing the balance.
|
||||||
|
func TestConsoleGrantHints(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zap.NewNop(), Accounts: accounts, Games: newGameService(), Registry: testRegistry, DictDir: dictDir(),
|
||||||
|
})
|
||||||
|
h := srv.Handler()
|
||||||
|
base := "http://admin.test/_gm/users/" + id.String()
|
||||||
|
|
||||||
|
if code, body := consoleDo(h, http.MethodGet, base, "", ""); code != http.StatusOK || !strings.Contains(body, "Add hints") {
|
||||||
|
t.Fatalf("user card = %d, has grant form = %v", code, strings.Contains(body, "Add hints"))
|
||||||
|
}
|
||||||
|
// The grant POST is CSRF-guarded like every console action.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/grant-hints", "amount=5", ""); code != http.StatusForbidden {
|
||||||
|
t.Fatalf("grant without origin = %d, want 403", code)
|
||||||
|
}
|
||||||
|
// A same-origin grant adds to the wallet.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/grant-hints", "amount=5", "http://admin.test"); code != http.StatusOK || !strings.Contains(body, "now 5") {
|
||||||
|
t.Fatalf("grant 5 = %d, body has 'now 5' = %v", code, strings.Contains(body, "now 5"))
|
||||||
|
}
|
||||||
|
if acc, err := accounts.GetByID(ctx, id); err != nil || acc.HintBalance != 5 {
|
||||||
|
t.Fatalf("after grant 5: balance=%d err=%v, want 5", acc.HintBalance, err)
|
||||||
|
}
|
||||||
|
// A second grant adds again rather than replacing.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/grant-hints", "amount=3", "http://admin.test"); code != http.StatusOK || !strings.Contains(body, "now 8") {
|
||||||
|
t.Fatalf("grant 3 = %d, body has 'now 8' = %v", code, strings.Contains(body, "now 8"))
|
||||||
|
}
|
||||||
|
// An out-of-range or non-numeric amount is refused; the balance is left untouched.
|
||||||
|
for _, bad := range []string{"0", "-1", "101", "x", ""} {
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/grant-hints", "amount="+bad, "http://admin.test"); code != http.StatusOK || !strings.Contains(body, "Invalid amount") {
|
||||||
|
t.Fatalf("grant %q = %d, has 'Invalid amount' = %v", bad, code, strings.Contains(body, "Invalid amount"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acc, err := accounts.GetByID(ctx, id); err != nil || acc.HintBalance != 8 {
|
||||||
|
t.Fatalf("after invalid grants: balance=%d err=%v, want 8", acc.HintBalance, err)
|
||||||
|
}
|
||||||
|
// The inclusive per-grant cap (100) is accepted.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/grant-hints", "amount=100", "http://admin.test"); code != http.StatusOK {
|
||||||
|
t.Fatalf("grant 100 = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if acc, err := accounts.GetByID(ctx, id); err != nil || acc.HintBalance != 108 {
|
||||||
|
t.Fatalf("after grant 100: balance=%d err=%v, want 108", acc.HintBalance, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestGrantHintsStore covers the wallet store method directly: an additive grant raises the
|
||||||
|
// balance, a non-positive grant is rejected, and an unknown account yields ErrNotFound.
|
||||||
|
func TestGrantHintsStore(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
if bal, err := accounts.GrantHints(ctx, id, 4); err != nil || bal != 4 {
|
||||||
|
t.Fatalf("grant 4 = (%d, %v), want (4, nil)", bal, err)
|
||||||
|
}
|
||||||
|
if bal, err := accounts.GrantHints(ctx, id, 6); err != nil || bal != 10 {
|
||||||
|
t.Fatalf("grant 6 = (%d, %v), want (10, nil)", bal, err)
|
||||||
|
}
|
||||||
|
if _, err := accounts.GrantHints(ctx, id, 0); err == nil {
|
||||||
|
t.Error("grant 0 should be rejected (non-positive)")
|
||||||
|
}
|
||||||
|
if _, err := accounts.GrantHints(ctx, uuid.New(), 1); !errors.Is(err, account.ErrNotFound) {
|
||||||
|
t.Errorf("grant unknown account = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// consoleDo issues a request to h, optionally with an Origin header, and returns
|
// consoleDo issues a request to h, optionally with an Origin header, and returns
|
||||||
// the status and body. Form bodies are sent as application/x-www-form-urlencoded.
|
// the status and body. Form bodies are sent as application/x-www-form-urlencoded.
|
||||||
func consoleDo(h http.Handler, method, target, body, origin string) (int, string) {
|
func consoleDo(h http.Handler, method, target, body, origin string) (int, string) {
|
||||||
|
|||||||
@@ -0,0 +1,269 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/notify"
|
||||||
|
"scrabble/backend/internal/robot"
|
||||||
|
"scrabble/backend/internal/social"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The AI-game suite covers the honest-AI quick game: a game created already seated with a
|
||||||
|
// pooled robot (vs_ai), in which the robot moves immediately, the move clock is the 7-day
|
||||||
|
// inactivity rule, chat and nudge are disabled and no statistics are recorded.
|
||||||
|
|
||||||
|
// startAIGame creates an active vs_ai game seating a fresh human and a pooled robot, the human
|
||||||
|
// at seat 0 when humanFirst (otherwise the robot moves first), and returns it with the two ids.
|
||||||
|
func startAIGame(t *testing.T, svc *game.Service, robots *robot.Service, humanFirst bool, seed int64) (game.Game, uuid.UUID, uuid.UUID) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
human := provisionAccount(t)
|
||||||
|
robotID, err := robots.Pick(engine.VariantEnglish)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pick robot: %v", err)
|
||||||
|
}
|
||||||
|
seats := []uuid.UUID{human, robotID}
|
||||||
|
if !humanFirst {
|
||||||
|
seats = []uuid.UUID{robotID, human}
|
||||||
|
}
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: seats, VsAI: true, Seed: seed,
|
||||||
|
HintsAllowed: true, HintsPerPlayer: 1, MultipleWordsPerTurn: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create AI game: %v", err)
|
||||||
|
}
|
||||||
|
return g, human, robotID
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameStartSeatsRobotActive checks the matchmaker's AI path creates an active game already
|
||||||
|
// seated with a robot (no open/wait phase), flagged vs_ai and on the 7-day inactivity clock.
|
||||||
|
func TestAIGameStartSeatsRobotActive(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
robots := newRobotService(t, newGameService())
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
mm := newMatchmaker(t, robots, time.Minute, 0)
|
||||||
|
|
||||||
|
human := provisionAccount(t)
|
||||||
|
res, err := mm.StartVsAI(ctx, human, engine.VariantEnglish, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("start vs AI: %v", err)
|
||||||
|
}
|
||||||
|
g := res.Game
|
||||||
|
if !res.Matched || g.Status != game.StatusActive {
|
||||||
|
t.Fatalf("AI game = (matched %v, status %q), want (true, active)", res.Matched, g.Status)
|
||||||
|
}
|
||||||
|
if !g.VsAI {
|
||||||
|
t.Error("an AI game must be flagged vs_ai")
|
||||||
|
}
|
||||||
|
if g.TurnTimeout != game.AIInactivityTimeout {
|
||||||
|
t.Errorf("AI game move clock = %s, want %s", g.TurnTimeout, game.AIInactivityTimeout)
|
||||||
|
}
|
||||||
|
var hasHuman, hasRobot bool
|
||||||
|
for _, s := range g.Seats {
|
||||||
|
switch {
|
||||||
|
case s.AccountID == human:
|
||||||
|
hasHuman = true
|
||||||
|
case s.AccountID != uuid.Nil:
|
||||||
|
hasRobot = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(g.Seats) != 2 || !hasHuman || !hasRobot {
|
||||||
|
t.Errorf("AI game seats = %+v, want exactly the human and a robot (no empty seat)", g.Seats)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIRobotMovesImmediately checks the robot in a vs_ai game moves the instant it is its turn,
|
||||||
|
// with no sampled delay and no sleep window (the honest-AI fast path the trigger drives).
|
||||||
|
func TestAIRobotMovesImmediately(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
g, _, _ := startAIGame(t, svc, robots, false, openingSeed(t)) // robot at seat 0, to move
|
||||||
|
|
||||||
|
if err := robots.DriveGame(ctx, g.ID, time.Now()); err != nil {
|
||||||
|
t.Fatalf("drive AI game: %v", err)
|
||||||
|
}
|
||||||
|
after, err := svc.GameByID(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get game: %v", err)
|
||||||
|
}
|
||||||
|
if after.MoveCount != 1 {
|
||||||
|
t.Errorf("after one drive the robot's first move must be in (move count %d, want 1)", after.MoveCount)
|
||||||
|
}
|
||||||
|
if after.ToMove == 0 {
|
||||||
|
t.Error("after the robot's move it must be the human's turn")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameStatsSkipped checks a vs_ai game records no statistics: a human resign (a loss in a
|
||||||
|
// normal game) leaves the human with no stats row.
|
||||||
|
func TestAIGameStatsSkipped(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
g, human, _ := startAIGame(t, svc, robots, true, openingSeed(t))
|
||||||
|
|
||||||
|
if _, err := svc.Resign(ctx, g.ID, human); err != nil {
|
||||||
|
t.Fatalf("resign: %v", err)
|
||||||
|
}
|
||||||
|
if _, _, _, _, _, found := readStats(t, human); found {
|
||||||
|
t.Error("an AI game must not record statistics for the human")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameSevenDayTimeout checks the reused turn-timeout sweeper enforces the 7-day inactivity
|
||||||
|
// rule: nothing fires within seven days, and past it the human on the clock is resigned and loses.
|
||||||
|
func TestAIGameSevenDayTimeout(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
g, human, robotID := startAIGame(t, svc, robots, true, openingSeed(t)) // human at seat 0, to move
|
||||||
|
|
||||||
|
// Six days idle: well under the 7-day clock, so the sweeper leaves it active.
|
||||||
|
setTurnStarted(t, g.ID, time.Now().Add(-6*24*time.Hour))
|
||||||
|
if _, err := svc.SweepTimeouts(ctx, time.Now()); err != nil {
|
||||||
|
t.Fatalf("sweep: %v", err)
|
||||||
|
}
|
||||||
|
if mid, _ := svc.GameByID(ctx, g.ID); mid.Status != game.StatusActive {
|
||||||
|
t.Fatalf("at six days idle the AI game must still be active, got %q", mid.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Eight days idle: past the clock, so the human (on the clock) is timed out and loses.
|
||||||
|
setTurnStarted(t, g.ID, time.Now().Add(-8*24*time.Hour))
|
||||||
|
if _, err := svc.SweepTimeouts(ctx, time.Now()); err != nil {
|
||||||
|
t.Fatalf("sweep: %v", err)
|
||||||
|
}
|
||||||
|
done, err := svc.GameByID(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get game: %v", err)
|
||||||
|
}
|
||||||
|
if done.Status != game.StatusFinished || done.EndReason != "timeout" {
|
||||||
|
t.Fatalf("after seven days idle: (status %q, reason %q), want (finished, timeout)", done.Status, done.EndReason)
|
||||||
|
}
|
||||||
|
for _, s := range done.Seats {
|
||||||
|
if s.AccountID == robotID && !s.IsWinner {
|
||||||
|
t.Error("the robot must win when the human abandons the game")
|
||||||
|
}
|
||||||
|
if s.AccountID == human && s.IsWinner {
|
||||||
|
t.Error("the abandoning human must not win")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, _, _, _, _, found := readStats(t, human); found {
|
||||||
|
t.Error("a timed-out AI game must not record statistics")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameSuppressesYourTurn checks an honest-AI game emits opponent_moved but no your_turn:
|
||||||
|
// the robot replies instantly, so a "your turn" signal would arrive with the AI's move and be
|
||||||
|
// pointless (the human's UI advances from opponent_moved).
|
||||||
|
func TestAIGameSuppressesYourTurn(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
seed := openingSeed(t)
|
||||||
|
g, human, _ := startAIGame(t, svc, robots, true, seed) // human at seat 0, to move
|
||||||
|
|
||||||
|
hint, ok := newMirror(t, seed, 2).HintView()
|
||||||
|
if !ok || len(hint.Tiles) == 0 {
|
||||||
|
t.Fatal("no opening move for the seed")
|
||||||
|
}
|
||||||
|
if _, err := svc.SubmitPlay(ctx, g.ID, human, hint.Tiles); err != nil {
|
||||||
|
t.Fatalf("human play: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var opponentMoved, yourTurn int
|
||||||
|
pub.mu.Lock()
|
||||||
|
for _, in := range pub.intents {
|
||||||
|
switch in.Kind {
|
||||||
|
case notify.KindYourTurn:
|
||||||
|
yourTurn++
|
||||||
|
case notify.KindOpponentMoved:
|
||||||
|
opponentMoved++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub.mu.Unlock()
|
||||||
|
if yourTurn != 0 {
|
||||||
|
t.Errorf("an AI game must emit no your_turn; got %d", yourTurn)
|
||||||
|
}
|
||||||
|
if opponentMoved == 0 {
|
||||||
|
t.Error("an AI game must still emit opponent_moved so the human's UI advances")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameGCGLabelsRobotAI checks the GCG export of an honest-AI game labels the robot seat
|
||||||
|
// "AI" rather than leaking its human-like pool name.
|
||||||
|
func TestAIGameGCGLabelsRobotAI(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
g, human, robotID := startAIGame(t, svc, robots, true, openingSeed(t))
|
||||||
|
if _, err := svc.Resign(ctx, g.ID, human); err != nil { // finish the game so GCG export is allowed
|
||||||
|
t.Fatalf("resign: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gcg, err := svc.ExportGCG(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("export gcg: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gcg, " AI\n") {
|
||||||
|
t.Errorf("GCG must label the robot seat \"AI\"; got:\n%s", gcg)
|
||||||
|
}
|
||||||
|
robot, err := account.NewStore(testDB).GetByID(ctx, robotID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get robot: %v", err)
|
||||||
|
}
|
||||||
|
if strings.Contains(gcg, robot.DisplayName) {
|
||||||
|
t.Errorf("GCG must not leak the robot's pool name %q; got:\n%s", robot.DisplayName, gcg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAIGameChatAndNudgeRejected checks chat and nudge are both refused in a vs_ai game (the
|
||||||
|
// opponent is a robot), even though the game reports status 'active'.
|
||||||
|
func TestAIGameChatAndNudgeRejected(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
soc := newSocialService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
g, human, _ := startAIGame(t, svc, robots, true, openingSeed(t))
|
||||||
|
|
||||||
|
if _, err := soc.PostMessage(ctx, g.ID, human, "hi robot", ""); !errors.Is(err, social.ErrGameVsAI) {
|
||||||
|
t.Errorf("chat in an AI game = %v, want ErrGameVsAI", err)
|
||||||
|
}
|
||||||
|
if _, err := soc.Nudge(ctx, g.ID, human); !errors.Is(err, social.ErrGameVsAI) {
|
||||||
|
t.Errorf("nudge in an AI game = %v, want ErrGameVsAI", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/ads"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bannerServer assembles a console-capable server with the ads domain wired.
|
||||||
|
func bannerServer(t *testing.T) (*server.Server, *ads.Service) {
|
||||||
|
t.Helper()
|
||||||
|
adsSvc := ads.NewService(ads.NewStore(testDB))
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zap.NewNop(),
|
||||||
|
Accounts: account.NewStore(testDB),
|
||||||
|
Games: newGameService(),
|
||||||
|
Registry: testRegistry,
|
||||||
|
DictDir: dictDir(),
|
||||||
|
Ads: adsSvc,
|
||||||
|
})
|
||||||
|
return srv, adsSvc
|
||||||
|
}
|
||||||
|
|
||||||
|
// findCampaign returns the id of the campaign with the given name, or fails.
|
||||||
|
func findCampaign(t *testing.T, svc *ads.Service, name string) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
all, err := svc.ListCampaigns(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list campaigns: %v", err)
|
||||||
|
}
|
||||||
|
for _, c := range all {
|
||||||
|
if c.Name == name {
|
||||||
|
return c.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("campaign %q not found", name)
|
||||||
|
return uuid.Nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultCampaign returns the seeded perpetual default campaign.
|
||||||
|
func defaultCampaign(t *testing.T, svc *ads.Service) ads.Campaign {
|
||||||
|
t.Helper()
|
||||||
|
all, err := svc.ListCampaigns(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list campaigns: %v", err)
|
||||||
|
}
|
||||||
|
for _, c := range all {
|
||||||
|
if c.IsDefault {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("no default campaign seeded")
|
||||||
|
return ads.Campaign{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBannerConsoleCRUD drives the /_gm/banners console over HTTP against real
|
||||||
|
// stores: pages render, the CSRF guard bites, validation and the default-campaign
|
||||||
|
// protection hold, and a campaign + message round-trips through create/edit/
|
||||||
|
// reorder/delete.
|
||||||
|
func TestBannerConsoleCRUD(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
srv, adsSvc := bannerServer(t)
|
||||||
|
h := srv.Handler()
|
||||||
|
base := "http://admin.test/_gm"
|
||||||
|
const origin = "http://admin.test"
|
||||||
|
|
||||||
|
// The list renders and shows the seeded default campaign.
|
||||||
|
if code, body := consoleDo(h, http.MethodGet, base+"/banners", "", ""); code != http.StatusOK || !strings.Contains(body, "Default (house)") {
|
||||||
|
t.Fatalf("banners list = %d, has default=%v", code, strings.Contains(body, "Default (house)"))
|
||||||
|
}
|
||||||
|
|
||||||
|
name := "Promo-" + uuid.NewString()[:8]
|
||||||
|
// CSRF: a create without a same-origin header is rejected.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/banners", "name="+name+"&weight=30&enabled=on", ""); code != http.StatusForbidden {
|
||||||
|
t.Fatalf("create without origin = %d, want 403", code)
|
||||||
|
}
|
||||||
|
// Validation: weight out of range is refused.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners", "name=Bad&weight=0&enabled=on", origin); code != http.StatusOK || !strings.Contains(body, "Not saved") {
|
||||||
|
t.Fatalf("create weight=0 = %d, has 'Not saved'=%v", code, strings.Contains(body, "Not saved"))
|
||||||
|
}
|
||||||
|
// A valid create persists.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners", "name="+name+"&weight=30&enabled=on", origin); code != http.StatusOK || !strings.Contains(body, "Created") {
|
||||||
|
t.Fatalf("create = %d, has Created=%v", code, strings.Contains(body, "Created"))
|
||||||
|
}
|
||||||
|
id := findCampaign(t, adsSvc, name)
|
||||||
|
|
||||||
|
// The detail page renders.
|
||||||
|
if code, body := consoleDo(h, http.MethodGet, base+"/banners/"+id.String(), "", ""); code != http.StatusOK || !strings.Contains(body, name) {
|
||||||
|
t.Fatalf("detail = %d, has name=%v", code, strings.Contains(body, name))
|
||||||
|
}
|
||||||
|
// A message needs both languages.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/messages", "body_en=Hello&body_ru=", origin); code != http.StatusOK || !strings.Contains(body, "Not saved") {
|
||||||
|
t.Fatalf("add half message = %d, has 'Not saved'=%v", code, strings.Contains(body, "Not saved"))
|
||||||
|
}
|
||||||
|
// A bilingual message is added.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/messages", "body_en=Hello&body_ru=Привет", origin); code != http.StatusOK || !strings.Contains(body, "Added") {
|
||||||
|
t.Fatalf("add message = %d, has Added=%v", code, strings.Contains(body, "Added"))
|
||||||
|
}
|
||||||
|
cm, err := adsSvc.Campaign(ctx, id)
|
||||||
|
if err != nil || len(cm.Messages) != 1 {
|
||||||
|
t.Fatalf("campaign messages = %d (err %v), want 1", len(cm.Messages), err)
|
||||||
|
}
|
||||||
|
mid := cm.Messages[0].ID
|
||||||
|
// Edit it.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/messages/"+mid.String(), "body_en=Hi&body_ru=Привет!", origin); code != http.StatusOK {
|
||||||
|
t.Fatalf("edit message = %d", code)
|
||||||
|
}
|
||||||
|
if cm, _ := adsSvc.Campaign(ctx, id); cm.Messages[0].BodyEn != "Hi" {
|
||||||
|
t.Fatalf("edit did not persist: %q", cm.Messages[0].BodyEn)
|
||||||
|
}
|
||||||
|
// Reorder is a no-op for a single message but still succeeds.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/messages/"+mid.String()+"/move", "dir=down", origin); code != http.StatusOK {
|
||||||
|
t.Fatalf("move message = %d", code)
|
||||||
|
}
|
||||||
|
// Delete the message, then the campaign.
|
||||||
|
if code, _ := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/messages/"+mid.String()+"/delete", "", origin); code != http.StatusOK {
|
||||||
|
t.Fatalf("delete message = %d", code)
|
||||||
|
}
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+id.String()+"/delete", "", origin); code != http.StatusOK || !strings.Contains(body, "Deleted") {
|
||||||
|
t.Fatalf("delete campaign = %d, has Deleted=%v", code, strings.Contains(body, "Deleted"))
|
||||||
|
}
|
||||||
|
if _, err := adsSvc.Campaign(ctx, id); err == nil {
|
||||||
|
t.Fatal("campaign still present after delete")
|
||||||
|
}
|
||||||
|
|
||||||
|
// The default campaign cannot be deleted.
|
||||||
|
def := defaultCampaign(t, adsSvc)
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+def.ID.String()+"/delete", "", origin); code != http.StatusOK || !strings.Contains(body, "Not saved") {
|
||||||
|
t.Fatalf("delete default = %d, has 'Not saved'=%v", code, strings.Contains(body, "Not saved"))
|
||||||
|
}
|
||||||
|
if _, err := adsSvc.Campaign(ctx, def.ID); err != nil {
|
||||||
|
t.Fatalf("default campaign gone after refused delete: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBannerMessageOwnership guards the campaign/message pairing: a message may
|
||||||
|
// only be edited or deleted through the URL of the campaign it belongs to. This
|
||||||
|
// closes a default-protection bypass — deleting the default's last message via an
|
||||||
|
// unrelated campaign's URL must be refused.
|
||||||
|
func TestBannerMessageOwnership(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
srv, adsSvc := bannerServer(t)
|
||||||
|
h := srv.Handler()
|
||||||
|
base := "http://admin.test/_gm"
|
||||||
|
const origin = "http://admin.test"
|
||||||
|
|
||||||
|
def := defaultCampaign(t, adsSvc)
|
||||||
|
if len(def.Messages) == 0 {
|
||||||
|
t.Fatal("default campaign has no seeded message")
|
||||||
|
}
|
||||||
|
defMsg := def.Messages[0].ID
|
||||||
|
|
||||||
|
// A separate timed campaign whose URL we will (mis)use.
|
||||||
|
otherID, err := adsSvc.CreateCampaign(ctx, ads.Campaign{Name: "Own-" + uuid.NewString()[:8], Weight: 10, Enabled: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create campaign: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = adsSvc.DeleteCampaign(ctx, otherID) })
|
||||||
|
|
||||||
|
// Deleting the default's message through the other campaign's URL is refused,
|
||||||
|
// and the default keeps its message (the bypass is closed).
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+otherID.String()+"/messages/"+defMsg.String()+"/delete", "", origin); code != http.StatusOK || !strings.Contains(body, "Not found") {
|
||||||
|
t.Fatalf("cross-campaign delete = %d, has 'Not found'=%v", code, strings.Contains(body, "Not found"))
|
||||||
|
}
|
||||||
|
// Editing it through the wrong campaign is refused too.
|
||||||
|
if code, body := consoleDo(h, http.MethodPost, base+"/banners/"+otherID.String()+"/messages/"+defMsg.String(), "body_en=Hijacked&body_ru=Взлом", origin); code != http.StatusOK || !strings.Contains(body, "Not found") {
|
||||||
|
t.Fatalf("cross-campaign edit = %d, has 'Not found'=%v", code, strings.Contains(body, "Not found"))
|
||||||
|
}
|
||||||
|
// The default's message is intact.
|
||||||
|
again := defaultCampaign(t, adsSvc)
|
||||||
|
if len(again.Messages) != len(def.Messages) {
|
||||||
|
t.Fatalf("default messages = %d, want %d (unchanged)", len(again.Messages), len(def.Messages))
|
||||||
|
}
|
||||||
|
if again.Messages[0].BodyEn != def.Messages[0].BodyEn {
|
||||||
|
t.Fatalf("default message body changed: %q -> %q", def.Messages[0].BodyEn, again.Messages[0].BodyEn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// profileBanner is the banner block of the profile.get JSON response.
|
||||||
|
type profileBanner struct {
|
||||||
|
Banner *struct {
|
||||||
|
Campaigns []struct {
|
||||||
|
Weight int `json:"weight"`
|
||||||
|
Messages []string `json:"messages"`
|
||||||
|
} `json:"campaigns"`
|
||||||
|
Timings struct {
|
||||||
|
HoldMs int `json:"hold_ms"`
|
||||||
|
} `json:"timings"`
|
||||||
|
} `json:"banner"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBannerProfileEligibility checks the profile.get banner block follows
|
||||||
|
// eligibility: a free account sees it, the no_banner role and a non-empty hint
|
||||||
|
// wallet each suppress it.
|
||||||
|
func TestBannerProfileEligibility(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
srv, _ := bannerServer(t)
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
getBanner := func() profileBanner {
|
||||||
|
t.Helper()
|
||||||
|
rec := userGet(t, srv, "/api/v1/user/profile", id)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("profile = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
var p profileBanner
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
|
||||||
|
t.Fatalf("decode profile: %v", err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// A free account with an empty hint wallet and no role is eligible.
|
||||||
|
p := getBanner()
|
||||||
|
if p.Banner == nil || len(p.Banner.Campaigns) == 0 || p.Banner.Timings.HoldMs <= 0 {
|
||||||
|
t.Fatalf("eligible account: banner=%v", p.Banner)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The no_banner role suppresses it unconditionally.
|
||||||
|
if err := accounts.GrantRole(ctx, id, account.RoleNoBanner); err != nil {
|
||||||
|
t.Fatalf("grant role: %v", err)
|
||||||
|
}
|
||||||
|
if p := getBanner(); p.Banner != nil {
|
||||||
|
t.Fatal("no_banner role still shows the banner")
|
||||||
|
}
|
||||||
|
if err := accounts.RevokeRole(ctx, id, account.RoleNoBanner); err != nil {
|
||||||
|
t.Fatalf("revoke role: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A non-empty hint wallet suppresses it.
|
||||||
|
if _, err := accounts.GrantHints(ctx, id, 5); err != nil {
|
||||||
|
t.Fatalf("grant hints: %v", err)
|
||||||
|
}
|
||||||
|
if p := getBanner(); p.Banner != nil {
|
||||||
|
t.Fatal("a non-empty hint wallet still shows the banner")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBannerSurvivesProfileUpdate guards that a profile update (e.g. a language switch) returns the
|
||||||
|
// banner block too, so the client's profile keeps the banner instead of losing it until reload.
|
||||||
|
func TestBannerSurvivesProfileUpdate(t *testing.T) {
|
||||||
|
srv, _ := bannerServer(t)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
body := `{"display_name":"Tester","preferred_language":"ru","time_zone":"UTC","away_start":"00:00",` +
|
||||||
|
`"away_end":"00:00","block_chat":false,"block_friend_requests":false,"notifications_in_app_only":true,` +
|
||||||
|
`"variant_preferences":["erudit_ru"]}`
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPut, "/api/v1/user/profile", strings.NewReader(body))
|
||||||
|
req.Header.Set("X-User-ID", id.String())
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("update profile = %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var p profileBanner
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if p.Banner == nil || len(p.Banner.Campaigns) == 0 {
|
||||||
|
t.Fatalf("profile update dropped the banner block: %v", p.Banner)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/notify"
|
||||||
|
"scrabble/backend/internal/social"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestBlockInstantReadsExistingUnread checks that blocking marks read any chat the blocked
|
||||||
|
// user had left unread for the blocker in their shared games, so no stale unread badge
|
||||||
|
// lingers for someone the blocker no longer sees.
|
||||||
|
func TestBlockInstantReadsExistingUnread(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
sender, viewer := seats[0], seats[1] // seat 0 moves first, so it may chat
|
||||||
|
|
||||||
|
if _, err := svc.PostMessage(ctx, gameID, sender, "good luck", ""); err != nil {
|
||||||
|
t.Fatalf("post: %v", err)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, viewer); !unread {
|
||||||
|
t.Fatal("viewer should have the message unread before blocking")
|
||||||
|
}
|
||||||
|
if err := svc.Block(ctx, viewer, sender); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, viewer); unread {
|
||||||
|
t.Error("blocking should instant-read the blocked sender's prior unread message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatFromBlockedIsBornReadAndNotDelivered checks the store-but-hide path for chat: a
|
||||||
|
// message the blocked user sends is stored and visible to themselves, but is born read for
|
||||||
|
// the blocker, never delivered to them, and hidden from their view.
|
||||||
|
func TestChatFromBlockedIsBornReadAndNotDelivered(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
blocked, blocker := seats[0], seats[1] // seat 0 moves first, so the blocked user may chat
|
||||||
|
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.PostMessage(ctx, gameID, blocked, "hello there", ""); err != nil {
|
||||||
|
t.Fatalf("blocked user's post = %v, want nil (it must look ordinary to them)", err)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, blocker); unread {
|
||||||
|
t.Error("the blocked sender's message must be born read for the blocker")
|
||||||
|
}
|
||||||
|
if pub.delivered(blocker, notify.KindChatMessage) {
|
||||||
|
t.Error("the blocked sender's message must not be delivered to the blocker")
|
||||||
|
}
|
||||||
|
if msgs, _ := svc.Messages(ctx, gameID, blocker); len(msgs) != 0 {
|
||||||
|
t.Errorf("blocker still sees the blocked sender's message: %+v", msgs)
|
||||||
|
}
|
||||||
|
if msgs, _ := svc.Messages(ctx, gameID, blocked); len(msgs) != 1 {
|
||||||
|
t.Errorf("the blocked sender should see their own message, got %+v", msgs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatToBlockedIsRejected checks the blocker-side guard: a player cannot post when their
|
||||||
|
// only opponent is someone they have blocked (the composer is hidden client-side too).
|
||||||
|
func TestChatToBlockedIsRejected(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
blocker, blocked := seats[0], seats[1] // blocker moves first, so it is the one trying to chat
|
||||||
|
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.PostMessage(ctx, gameID, blocker, "hi", ""); !errors.Is(err, social.ErrRecipientBlocked) {
|
||||||
|
t.Fatalf("chat to blocked opponent = %v, want ErrRecipientBlocked", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNudgeFromBlockedIsBornReadAndNotDelivered checks the store-but-hide path for nudge: a
|
||||||
|
// nudge the blocked user sends is recorded (so their once-per-hour cooldown applies, looking
|
||||||
|
// ordinary to them) but is born read and never delivered to the blocker.
|
||||||
|
func TestNudgeFromBlockedIsBornReadAndNotDelivered(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
blocker, blocked := seats[0], seats[1] // seat 0 awaited; the blocked seat-1 player nudges it
|
||||||
|
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Nudge(ctx, gameID, blocked); err != nil {
|
||||||
|
t.Fatalf("blocked user's nudge = %v, want nil (it must look ordinary to them)", err)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, blocker); unread {
|
||||||
|
t.Error("the blocked sender's nudge must be born read for the blocker")
|
||||||
|
}
|
||||||
|
if pub.delivered(blocker, notify.KindNudge) {
|
||||||
|
t.Error("the blocked sender's nudge must not be delivered to the blocker")
|
||||||
|
}
|
||||||
|
// The nudge is still recorded, so the cooldown applies (the blocked user notices nothing).
|
||||||
|
if _, ok, _ := svc.LastNudgeAt(ctx, gameID, blocked); !ok {
|
||||||
|
t.Error("the suppressed nudge should still be recorded")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNudgeToBlockedIsRejected checks the blocker-side guard: a player cannot nudge the
|
||||||
|
// awaited opponent when they have blocked them.
|
||||||
|
func TestNudgeToBlockedIsRejected(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
blocked, blocker := seats[0], seats[1] // seat 0 awaited; the blocker (seat 1) tries to nudge it
|
||||||
|
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Nudge(ctx, gameID, blocker); !errors.Is(err, social.ErrRecipientBlocked) {
|
||||||
|
t.Fatalf("nudge to blocked opponent = %v, want ErrRecipientBlocked", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBlockPublishesToBlockerOnly checks that block and unblock confirm to the blocker (so
|
||||||
|
// their other sessions update in place) and never reach the blocked user.
|
||||||
|
func TestBlockPublishesToBlockerOnly(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
blocker, blocked := provisionAccount(t), provisionAccount(t)
|
||||||
|
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if !pub.notified(blocker, notify.NotifyUserBlocked) {
|
||||||
|
t.Error("the blocker should receive a user_blocked event")
|
||||||
|
}
|
||||||
|
if pub.notified(blocked, notify.NotifyUserBlocked) {
|
||||||
|
t.Error("the blocked user must never receive a user_blocked event")
|
||||||
|
}
|
||||||
|
if err := svc.Unblock(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("unblock: %v", err)
|
||||||
|
}
|
||||||
|
if !pub.notified(blocker, notify.NotifyUserUnblocked) {
|
||||||
|
t.Error("the blocker should receive a user_unblocked event")
|
||||||
|
}
|
||||||
|
if pub.notified(blocked, notify.NotifyUserUnblocked) {
|
||||||
|
t.Error("the blocked user must never receive a user_unblocked event")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMatchmakingExcludesBlockedPlayers checks auto-match never pairs two players with a
|
||||||
|
// block between them (either direction), while an unblocked third player still joins.
|
||||||
|
func TestMatchmakingExcludesBlockedPlayers(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
mm := newMatchmaker(t, newRobotService(t, newGameService()), 90*time.Second, 90*time.Second)
|
||||||
|
soc := newSocialService()
|
||||||
|
mm.SetBlocker(soc)
|
||||||
|
a, b, c := provisionAccount(t), provisionAccount(t), provisionAccount(t)
|
||||||
|
|
||||||
|
if err := soc.Block(ctx, a, b); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
// The block is seen from both sides — the exclusion set unions both directions.
|
||||||
|
if !contains(blockedWith(t, soc, a), b) || !contains(blockedWith(t, soc, b), a) {
|
||||||
|
t.Fatal("a block must appear in BlockedWith for both the blocker and the blocked")
|
||||||
|
}
|
||||||
|
|
||||||
|
// b opens a game awaiting an opponent.
|
||||||
|
r1, err := mm.Enqueue(ctx, b, engine.VariantEnglish, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("enqueue b: %v", err)
|
||||||
|
}
|
||||||
|
if r1.Matched {
|
||||||
|
t.Fatal("first enqueue must open a game, not match")
|
||||||
|
}
|
||||||
|
// a must not join b's game (a blocked b): it opens its own instead.
|
||||||
|
r2, err := mm.Enqueue(ctx, a, engine.VariantEnglish, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("enqueue a: %v", err)
|
||||||
|
}
|
||||||
|
if r2.Matched || r2.Game.ID == r1.Game.ID {
|
||||||
|
t.Fatalf("a joined the blocked player's game %s (matched %v), want a fresh game", r1.Game.ID, r2.Matched)
|
||||||
|
}
|
||||||
|
// A third, unblocked player joins b's still-open game (the oldest), proving the exclusion
|
||||||
|
// is specific to the blocked pair, not a blanket refusal.
|
||||||
|
r3, err := mm.Enqueue(ctx, c, engine.VariantEnglish, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("enqueue c: %v", err)
|
||||||
|
}
|
||||||
|
if !r3.Matched || r3.Game.ID != r1.Game.ID {
|
||||||
|
t.Fatalf("unblocked c = (game %s, matched %v), want it to join b's open game %s", r3.Game.ID, r3.Matched, r1.Game.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAdminSocialLists checks the admin user card's blocks / blocked-by / friends queries
|
||||||
|
// return the full truth in both directions, including a friendship that a block overrides but
|
||||||
|
// does not delete.
|
||||||
|
func TestAdminSocialLists(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
_, seats := newGameWithSeats(t, 2)
|
||||||
|
a, b := seats[0], seats[1]
|
||||||
|
if err := svc.SendFriendRequest(ctx, a, b); err != nil {
|
||||||
|
t.Fatalf("request: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.RespondFriendRequest(ctx, b, a, true); err != nil {
|
||||||
|
t.Fatalf("accept: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.Block(ctx, a, b); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
blocks, err := svc.AdminBlocksBy(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin blocks by: %v", err)
|
||||||
|
}
|
||||||
|
if len(blocks) != 1 || blocks[0].AccountID != b || blocks[0].At.IsZero() {
|
||||||
|
t.Errorf("a's blocks = %v, want [b] with a date", blocks)
|
||||||
|
}
|
||||||
|
blockedBy, err := svc.AdminBlockedBy(ctx, b)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin blocked by: %v", err)
|
||||||
|
}
|
||||||
|
if len(blockedBy) != 1 || blockedBy[0].AccountID != a {
|
||||||
|
t.Errorf("b's blocked-by = %v, want [a]", blockedBy)
|
||||||
|
}
|
||||||
|
// The friendship survives the block, so it still shows on both admin friend lists.
|
||||||
|
friendsA, err := svc.AdminFriends(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin friends: %v", err)
|
||||||
|
}
|
||||||
|
if len(friendsA) != 1 || friendsA[0].AccountID != b || friendsA[0].At.IsZero() {
|
||||||
|
t.Errorf("a's admin friends = %v, want [b] with a date", friendsA)
|
||||||
|
}
|
||||||
|
if friendsB, err := svc.AdminFriends(ctx, b); err != nil || len(friendsB) != 1 || friendsB[0].AccountID != a {
|
||||||
|
t.Errorf("b's admin friends = %v (err %v), want [a]", friendsB, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRobotBlockIsPerGameAndMatchmakerImmune checks that blocking a disguised-robot opponent
|
||||||
|
// is recorded per-game in robot_blocks — never in the blocks table or against the shared robot
|
||||||
|
// account — so the matchmaker keeps the robot free, and that unblocking by the row id removes it.
|
||||||
|
func TestRobotBlockIsPerGameAndMatchmakerImmune(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
accs := account.NewStore(testDB)
|
||||||
|
human := provisionAccount(t)
|
||||||
|
robot, err := accs.ProvisionRobot(ctx, "robot-block-"+uuid.NewString(), "Robbie")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision robot: %v", err)
|
||||||
|
}
|
||||||
|
g, err := newGameService().Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robot.ID},
|
||||||
|
TurnTimeout: 24 * time.Hour, Seed: openingSeed(t),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create game: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.BlockInGame(ctx, human, robot.ID, g.ID); err != nil {
|
||||||
|
t.Fatalf("block robot: %v", err)
|
||||||
|
}
|
||||||
|
rbs, err := svc.ListRobotBlocks(ctx, human)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list robot blocks: %v", err)
|
||||||
|
}
|
||||||
|
if len(rbs) != 1 || rbs[0].GameID != g.ID {
|
||||||
|
t.Fatalf("robot blocks = %v, want one for game %s", rbs, g.ID)
|
||||||
|
}
|
||||||
|
if bl, _ := svc.ListBlocks(ctx, human); len(bl) != 0 {
|
||||||
|
t.Errorf("blocks table must stay empty for a robot block, got %v", bl)
|
||||||
|
}
|
||||||
|
if yes, _ := svc.IsBlocked(ctx, human, robot.ID); yes {
|
||||||
|
t.Error("the shared robot account must never be blocked")
|
||||||
|
}
|
||||||
|
// Matchmaking immunity: the robot is never in the caller's exclusion set, so the matchmaker
|
||||||
|
// keeps giving robots and the player can never be starved by blocking them.
|
||||||
|
if with, _ := svc.BlockedWith(ctx, human); contains(with, robot.ID) {
|
||||||
|
t.Error("a robot block must not put the robot in BlockedWith")
|
||||||
|
}
|
||||||
|
// Unblock by the robot_blocks row id removes it.
|
||||||
|
if err := svc.Unblock(ctx, human, rbs[0].ID); err != nil {
|
||||||
|
t.Fatalf("unblock robot: %v", err)
|
||||||
|
}
|
||||||
|
if rbs, _ := svc.ListRobotBlocks(ctx, human); len(rbs) != 0 {
|
||||||
|
t.Errorf("robot block not removed by unblock: %v", rbs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// blockedWith reads the both-direction block set for id.
|
||||||
|
func blockedWith(t *testing.T, soc *social.Service, id uuid.UUID) []uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
ids, err := soc.BlockedWith(context.Background(), id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("blocked with: %v", err)
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// contains reports whether ids includes want.
|
||||||
|
func contains(ids []uuid.UUID, want uuid.UUID) bool {
|
||||||
|
for _, id := range ids {
|
||||||
|
if id == want {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.uber.org/zap/zaptest"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/notify"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
"scrabble/backend/internal/session"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chatAccessBody mirrors the backend's /internal/chat-access JSON for the test.
|
||||||
|
type chatAccessBody struct {
|
||||||
|
ExternalID string `json:"external_id"`
|
||||||
|
Registered bool `json:"registered"`
|
||||||
|
Eligible bool `json:"eligible"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// chatAccess issues the gateway-internal chat-access query and asserts a 200.
|
||||||
|
func chatAccess(t *testing.T, srv *server.Server, body string) chatAccessBody {
|
||||||
|
t.Helper()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/internal/chat-access", strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("chat-access %s = %d: %s", body, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var b chatAccessBody
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &b); err != nil {
|
||||||
|
t.Fatalf("decode chat-access: %v", err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatAccessResolver drives the gateway-internal eligibility resolver over HTTP:
|
||||||
|
// the registered/suspended/chat_muted truth table by Telegram identity and by account
|
||||||
|
// id, the suspension dominating the chat_muted role, an unknown identity reported
|
||||||
|
// unregistered, and an account with no Telegram identity carrying an empty external_id.
|
||||||
|
func TestChatAccessResolver(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
srv := server.New(":0", server.Deps{Logger: zaptest.NewLogger(t), DB: testDB, Accounts: accounts})
|
||||||
|
|
||||||
|
ext := "tg-" + uuid.NewString()
|
||||||
|
acc, _, err := accounts.ProvisionTelegram(ctx, ext, "en", "", "Chatter")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision: %v", err)
|
||||||
|
}
|
||||||
|
id := acc.ID
|
||||||
|
|
||||||
|
byExt := func() chatAccessBody { return chatAccess(t, srv, `{"external_id":"`+ext+`"}`) }
|
||||||
|
byUser := func() chatAccessBody { return chatAccess(t, srv, `{"user_id":"`+id.String()+`"}`) }
|
||||||
|
|
||||||
|
// A registered, unsuspended, unmuted account is eligible by either address, and the
|
||||||
|
// account-id query resolves back to its Telegram identity.
|
||||||
|
if b := byExt(); !b.Registered || !b.Eligible || b.ExternalID != ext {
|
||||||
|
t.Fatalf("fresh by external_id = %+v, want registered+eligible+ext", b)
|
||||||
|
}
|
||||||
|
if b := byUser(); !b.Registered || !b.Eligible || b.ExternalID != ext {
|
||||||
|
t.Fatalf("fresh by user_id = %+v, want registered+eligible+ext", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A suspension mutes; a lift restores.
|
||||||
|
if _, err := accounts.Suspend(ctx, id, nil, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); !b.Registered || b.Eligible {
|
||||||
|
t.Fatalf("suspended = %+v, want registered but not eligible", b)
|
||||||
|
}
|
||||||
|
if err := accounts.LiftSuspension(ctx, id); err != nil {
|
||||||
|
t.Fatalf("lift: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); !b.Eligible {
|
||||||
|
t.Fatalf("after lift = %+v, want eligible", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The chat_muted role mutes independently; a revoke restores.
|
||||||
|
if err := accounts.GrantRole(ctx, id, account.RoleChatMuted); err != nil {
|
||||||
|
t.Fatalf("grant chat_muted: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); !b.Registered || b.Eligible {
|
||||||
|
t.Fatalf("chat_muted = %+v, want registered but not eligible", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suspension dominates: while chat_muted is set, lifting a concurrent suspension
|
||||||
|
// must not re-grant chat (the role still mutes).
|
||||||
|
if _, err := accounts.Suspend(ctx, id, nil, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend over mute: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); b.Eligible {
|
||||||
|
t.Fatalf("suspended+muted = %+v, want not eligible", b)
|
||||||
|
}
|
||||||
|
if err := accounts.LiftSuspension(ctx, id); err != nil {
|
||||||
|
t.Fatalf("lift over mute: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); b.Eligible {
|
||||||
|
t.Fatalf("lifted but still muted = %+v, want not eligible", b)
|
||||||
|
}
|
||||||
|
if err := accounts.RevokeRole(ctx, id, account.RoleChatMuted); err != nil {
|
||||||
|
t.Fatalf("revoke chat_muted: %v", err)
|
||||||
|
}
|
||||||
|
if b := byExt(); !b.Eligible {
|
||||||
|
t.Fatalf("after revoke = %+v, want eligible", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An unknown Telegram identity is unregistered (and thus left muted).
|
||||||
|
if b := chatAccess(t, srv, `{"external_id":"tg-missing-`+uuid.NewString()+`"}`); b.Registered || b.Eligible {
|
||||||
|
t.Fatalf("unknown identity = %+v, want neither registered nor eligible", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An account with no Telegram identity (a guest) carries an empty external_id, so
|
||||||
|
// the gateway has nothing to gate.
|
||||||
|
guest := provisionGuest(t)
|
||||||
|
if b := chatAccess(t, srv, `{"user_id":"`+guest.String()+`"}`); b.ExternalID != "" || b.Registered {
|
||||||
|
t.Fatalf("guest by user_id = %+v, want empty external_id and not registered", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A request naming neither address is a bad request.
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/internal/chat-access", strings.NewReader(`{}`))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("empty query = %d, want 400", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// captureNotifier records every published intent so a test can assert which live
|
||||||
|
// events a console action emitted.
|
||||||
|
type captureNotifier struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
intents []notify.Intent
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *captureNotifier) Publish(in ...notify.Intent) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.intents = append(c.intents, in...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// count returns how many intents of kind addressed to user were captured.
|
||||||
|
func (c *captureNotifier) count(user uuid.UUID, kind string) int {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
n := 0
|
||||||
|
for _, in := range c.intents {
|
||||||
|
if in.UserID == user && in.Kind == kind {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatAccessPublishedOnModeration drives the admin console and asserts each
|
||||||
|
// moderation action that can change chat eligibility — block, unblock, and the
|
||||||
|
// chat_muted role grant/revoke — emits the chat_access_changed signal the gateway
|
||||||
|
// turns into a chat-gate command.
|
||||||
|
func TestChatAccessPublishedOnModeration(t *testing.T) {
|
||||||
|
notifier := &captureNotifier{}
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: account.NewStore(testDB),
|
||||||
|
Games: newGameService(),
|
||||||
|
Registry: testRegistry,
|
||||||
|
DictDir: dictDir(),
|
||||||
|
Notifier: notifier,
|
||||||
|
})
|
||||||
|
h := srv.Handler()
|
||||||
|
id := provisionAccount(t)
|
||||||
|
base := "http://admin.test/_gm/users/" + id.String()
|
||||||
|
const origin = "http://admin.test"
|
||||||
|
|
||||||
|
steps := []struct {
|
||||||
|
name, path, body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"block", "/block", "duration=permanent", "Blocked"},
|
||||||
|
{"unblock", "/unblock", "", "Unblocked"},
|
||||||
|
{"grant chat_muted", "/grant-role", "role=chat_muted", "Role granted"},
|
||||||
|
{"revoke chat_muted", "/revoke-role", "role=chat_muted", "Role revoked"},
|
||||||
|
}
|
||||||
|
for i, s := range steps {
|
||||||
|
code, body := consoleDo(h, http.MethodPost, base+s.path, s.body, origin)
|
||||||
|
if code != http.StatusOK || !strings.Contains(body, s.want) {
|
||||||
|
t.Fatalf("%s = %d, has %q = %v", s.name, code, s.want, strings.Contains(body, s.want))
|
||||||
|
}
|
||||||
|
if got := notifier.count(id, notify.KindChatAccessChanged); got != i+1 {
|
||||||
|
t.Fatalf("after %s: chat_access_changed count = %d, want %d", s.name, got, i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatAccessPublishedOnFirstRegistration checks that a Telegram first contact
|
||||||
|
// (the sessions/telegram endpoint creating the account) emits chat_access_changed —
|
||||||
|
// the re-grant for a user who joined the moderated chat before registering — and that
|
||||||
|
// a repeat login does not re-emit.
|
||||||
|
func TestChatAccessPublishedOnFirstRegistration(t *testing.T) {
|
||||||
|
notifier := &captureNotifier{}
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: account.NewStore(testDB),
|
||||||
|
Sessions: session.NewService(session.NewStore(testDB), session.NewCache()),
|
||||||
|
Notifier: notifier,
|
||||||
|
})
|
||||||
|
h := srv.Handler()
|
||||||
|
ext := "tg-" + uuid.NewString()
|
||||||
|
|
||||||
|
post := func() {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/internal/sessions/telegram",
|
||||||
|
strings.NewReader(`{"external_id":"`+ext+`","language_code":"en","first_name":"Reg"}`))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("telegram auth = %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
post()
|
||||||
|
acc, err := account.NewStore(testDB).AccountByIdentity(context.Background(), account.KindTelegram, ext)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("lookup: %v", err)
|
||||||
|
}
|
||||||
|
if got := notifier.count(acc.ID, notify.KindChatAccessChanged); got != 1 {
|
||||||
|
t.Fatalf("first registration: chat_access_changed count = %d, want 1", got)
|
||||||
|
}
|
||||||
|
// A repeat login (the account already exists) must not re-emit.
|
||||||
|
post()
|
||||||
|
if got := notifier.count(acc.ID, notify.KindChatAccessChanged); got != 1 {
|
||||||
|
t.Fatalf("repeat login: chat_access_changed count = %d, want still 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionsExpiredBetween checks the sweeper's window query: a non-lifted
|
||||||
|
// temporary block whose expiry falls in the window is returned, while one outside the
|
||||||
|
// window, a permanent block, and a lifted block are not.
|
||||||
|
func TestSuspensionsExpiredBetween(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
|
||||||
|
// A temporary block whose expiry already lapsed at a known instant.
|
||||||
|
tempID := provisionAccount(t)
|
||||||
|
expiry := time.Now().Add(-time.Hour).Truncate(time.Second)
|
||||||
|
if _, err := accounts.Suspend(ctx, tempID, &expiry, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend temp: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
contains := func(ids []uuid.UUID, want uuid.UUID) bool {
|
||||||
|
for _, id := range ids {
|
||||||
|
if id == want {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// A window straddling the expiry returns the account.
|
||||||
|
got, err := accounts.SuspensionsExpiredBetween(ctx, expiry.Add(-time.Minute), expiry.Add(time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expired between: %v", err)
|
||||||
|
}
|
||||||
|
if !contains(got, tempID) {
|
||||||
|
t.Fatalf("window over expiry missing the lapsed block %s", tempID)
|
||||||
|
}
|
||||||
|
// A window entirely after the expiry does not.
|
||||||
|
got, err = accounts.SuspensionsExpiredBetween(ctx, expiry.Add(time.Minute), expiry.Add(2*time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expired between (after): %v", err)
|
||||||
|
}
|
||||||
|
if contains(got, tempID) {
|
||||||
|
t.Fatalf("window after expiry should not return %s", tempID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A permanent block never appears, even in a wide window.
|
||||||
|
permID := provisionAccount(t)
|
||||||
|
if _, err := accounts.Suspend(ctx, permID, nil, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend perm: %v", err)
|
||||||
|
}
|
||||||
|
// A lifted block does not appear either. The block must still be in force when lifted
|
||||||
|
// (LiftSuspension only lifts in-force blocks), so its expiry is in the future and the
|
||||||
|
// wide window below still covers it — yet lifted_at excludes it.
|
||||||
|
liftID := provisionAccount(t)
|
||||||
|
liftExpiry := time.Now().Add(30 * time.Minute).Truncate(time.Second)
|
||||||
|
if _, err := accounts.Suspend(ctx, liftID, &liftExpiry, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend lift: %v", err)
|
||||||
|
}
|
||||||
|
if err := accounts.LiftSuspension(ctx, liftID); err != nil {
|
||||||
|
t.Fatalf("lift: %v", err)
|
||||||
|
}
|
||||||
|
wide, err := accounts.SuspensionsExpiredBetween(ctx, time.Now().Add(-2*time.Hour), time.Now().Add(time.Hour))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expired between (wide): %v", err)
|
||||||
|
}
|
||||||
|
if contains(wide, permID) {
|
||||||
|
t.Fatalf("permanent block %s must not be reported as expired", permID)
|
||||||
|
}
|
||||||
|
if contains(wide, liftID) {
|
||||||
|
t.Fatalf("lifted block %s must not be reported as expired", liftID)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/social"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestChatUnreadAndMarkRead checks a text message marks every recipient seat unread (not the
|
||||||
|
// sender), surfaces through HasUnread / UnreadGames and the message-level HasUnreadMessage /
|
||||||
|
// UnreadMessageGames (it is a real message, not a nudge), and that MarkRead clears the reader's bit.
|
||||||
|
func TestChatUnreadAndMarkRead(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 2) // seat 0 is to move
|
||||||
|
|
||||||
|
if _, err := svc.PostMessage(ctx, gameID, seats[0], "good luck", ""); err != nil {
|
||||||
|
t.Fatalf("post: %v", err)
|
||||||
|
}
|
||||||
|
// The opponent has it unread; the sender does not.
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[1]); !unread {
|
||||||
|
t.Error("recipient should have the message unread")
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[0]); unread {
|
||||||
|
t.Error("sender should not have their own message unread")
|
||||||
|
}
|
||||||
|
if set, err := svc.UnreadGames(ctx, seats[1]); err != nil {
|
||||||
|
t.Fatalf("unread games: %v", err)
|
||||||
|
} else if !set[gameID] {
|
||||||
|
t.Error("UnreadGames should include the game for the recipient")
|
||||||
|
}
|
||||||
|
// A text message also raises the message-level flags (it is not just a nudge).
|
||||||
|
if msg, _ := svc.HasUnreadMessage(ctx, gameID, seats[1]); !msg {
|
||||||
|
t.Error("recipient should have the message flagged as an unread message")
|
||||||
|
}
|
||||||
|
if set, err := svc.UnreadMessageGames(ctx, seats[1]); err != nil {
|
||||||
|
t.Fatalf("unread message games: %v", err)
|
||||||
|
} else if !set[gameID] {
|
||||||
|
t.Error("UnreadMessageGames should include the game for a text message")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reading it clears the recipient's bit and reports one entry marked.
|
||||||
|
if n, err := svc.MarkRead(ctx, gameID, seats[1]); err != nil {
|
||||||
|
t.Fatalf("mark read: %v", err)
|
||||||
|
} else if n != 1 {
|
||||||
|
t.Errorf("marked %d, want 1", n)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[1]); unread {
|
||||||
|
t.Error("message should be read after MarkRead")
|
||||||
|
}
|
||||||
|
// A second MarkRead is a no-op — nothing is left unread.
|
||||||
|
if n, _ := svc.MarkRead(ctx, gameID, seats[1]); n != 0 {
|
||||||
|
t.Errorf("second mark read marked %d, want 0", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNudgeUnreadTargetsOnlyToMove checks, in a three-player game, that a nudge marks ONLY the
|
||||||
|
// awaited (to-move) seat unread — never the other waiting players. This is the owner's nudge
|
||||||
|
// targeting invariant, now observable through the unread bitmask. It also checks a nudge raises
|
||||||
|
// HasUnread but not the message-level flags, so the badge can colour it apart from a real message.
|
||||||
|
func TestNudgeUnreadTargetsOnlyToMove(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 3) // seat 0 is to move
|
||||||
|
|
||||||
|
// A waiting player nudges; only the awaited seat 0 is targeted.
|
||||||
|
if _, err := svc.Nudge(ctx, gameID, seats[1]); err != nil {
|
||||||
|
t.Fatalf("nudge: %v", err)
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[0]); !unread {
|
||||||
|
t.Error("the awaited seat should have the nudge unread")
|
||||||
|
}
|
||||||
|
// A nudge is not a message: it must not raise the message-level flags.
|
||||||
|
if msg, _ := svc.HasUnreadMessage(ctx, gameID, seats[0]); msg {
|
||||||
|
t.Error("a nudge must not be flagged as an unread message")
|
||||||
|
}
|
||||||
|
if set, _ := svc.UnreadMessageGames(ctx, seats[0]); set[gameID] {
|
||||||
|
t.Error("UnreadMessageGames must not include a game whose only unread entry is a nudge")
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[2]); unread {
|
||||||
|
t.Error("a non-awaited waiting seat must not receive the nudge")
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[1]); unread {
|
||||||
|
t.Error("the nudging sender must not have it unread")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTextMessageUnreadReachesAllOpponents checks a text message in a three-player game marks both
|
||||||
|
// opponents (every seated player but the sender) unread.
|
||||||
|
func TestTextMessageUnreadReachesAllOpponents(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 3) // seat 0 is to move and may chat
|
||||||
|
|
||||||
|
if _, err := svc.PostMessage(ctx, gameID, seats[0], "hello all", ""); err != nil {
|
||||||
|
t.Fatalf("post: %v", err)
|
||||||
|
}
|
||||||
|
for _, s := range []int{1, 2} {
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[s]); !unread {
|
||||||
|
t.Errorf("seat %d should have the text message unread", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if unread, _ := svc.HasUnread(ctx, gameID, seats[0]); unread {
|
||||||
|
t.Error("the sender should not have their own message unread")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNudgeClearedByMove checks the move path clears a nudge the actor answered by moving: the
|
||||||
|
// game service's wired NudgeClearer flips the awaited seat's nudge to read on commit.
|
||||||
|
func TestNudgeClearedByMove(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gameSvc, gameID, seats, play := newDraftGame(t)
|
||||||
|
socialSvc := newSocialService()
|
||||||
|
gameSvc.SetNudgeClearer(socialSvc.ClearNudges)
|
||||||
|
|
||||||
|
// The waiting seat 1 nudges the to-move seat 0.
|
||||||
|
if _, err := socialSvc.Nudge(ctx, gameID, seats[1]); err != nil {
|
||||||
|
t.Fatalf("nudge: %v", err)
|
||||||
|
}
|
||||||
|
if unread, _ := socialSvc.HasUnread(ctx, gameID, seats[0]); !unread {
|
||||||
|
t.Fatal("seat 0 should have the nudge unread before moving")
|
||||||
|
}
|
||||||
|
// Seat 0 answers by moving — the commit clears its pending nudge.
|
||||||
|
if _, err := gameSvc.SubmitPlay(ctx, gameID, seats[0], play.Tiles); err != nil {
|
||||||
|
t.Fatalf("submit play: %v", err)
|
||||||
|
}
|
||||||
|
if unread, _ := socialSvc.HasUnread(ctx, gameID, seats[0]); unread {
|
||||||
|
t.Error("the nudge should be cleared once the awaited player has moved")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestChatToRobotIsBornRead checks a text message to a disguised robot opponent (a pooled
|
||||||
|
// robot substituted into an ordinary, non-AI game) is born read: the robot never opens the
|
||||||
|
// chat, so the message must not linger unread (skewing the count and the read metric).
|
||||||
|
func TestChatToRobotIsBornRead(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
human := provisionAccount(t)
|
||||||
|
robot, err := account.NewStore(testDB).ProvisionRobot(ctx, "robot-chat-"+uuid.NewString(), "Robbie")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision robot: %v", err)
|
||||||
|
}
|
||||||
|
g, err := newGameService().Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robot.ID},
|
||||||
|
TurnTimeout: 24 * time.Hour, Seed: openingSeed(t),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create game: %v", err)
|
||||||
|
}
|
||||||
|
// The human (seat 0, to move) chats the disguised robot; the message is born read.
|
||||||
|
msg, err := svc.PostMessage(ctx, g.ID, human, "good luck", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("post: %v", err)
|
||||||
|
}
|
||||||
|
if items, _ := svc.AdminListMessages(ctx, social.AdminMessageFilter{GameID: g.ID, UnreadOnly: true}, 50, 0); len(items) != 0 {
|
||||||
|
t.Errorf("a message to a robot should be born read, but the unread filter listed %d", len(items))
|
||||||
|
}
|
||||||
|
card, err := svc.AdminMessageDetail(ctx, msg.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("detail: %v", err)
|
||||||
|
}
|
||||||
|
for _, s := range card.Seats {
|
||||||
|
if s.AccountID == robot.ID && s.Role != "read" {
|
||||||
|
t.Errorf("robot seat role = %q, want read", s.Role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAdminChatUnreadFilterAndDetail checks the admin unread-only filter and the per-seat read
|
||||||
|
// breakdown of the message card.
|
||||||
|
func TestAdminChatUnreadFilterAndDetail(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
gameID, seats := newGameWithSeats(t, 2)
|
||||||
|
|
||||||
|
msg, err := svc.PostMessage(ctx, gameID, seats[0], "good luck", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("post: %v", err)
|
||||||
|
}
|
||||||
|
// The unread-only filter (scoped to the game) lists the still-unread message.
|
||||||
|
if items, err := svc.AdminListMessages(ctx, social.AdminMessageFilter{GameID: gameID, UnreadOnly: true}, 50, 0); err != nil {
|
||||||
|
t.Fatalf("admin list: %v", err)
|
||||||
|
} else if len(items) != 1 || items[0].ID != msg.ID {
|
||||||
|
t.Fatalf("unread filter = %+v, want the one message", items)
|
||||||
|
}
|
||||||
|
// The detail card marks the sender 'sender' and the recipient 'unread'.
|
||||||
|
card, err := svc.AdminMessageDetail(ctx, msg.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("detail: %v", err)
|
||||||
|
}
|
||||||
|
roles := map[uuid.UUID]string{}
|
||||||
|
for _, s := range card.Seats {
|
||||||
|
roles[s.AccountID] = s.Role
|
||||||
|
}
|
||||||
|
if roles[seats[0]] != "sender" {
|
||||||
|
t.Errorf("sender role = %q, want sender", roles[seats[0]])
|
||||||
|
}
|
||||||
|
if roles[seats[1]] != "unread" {
|
||||||
|
t.Errorf("recipient role = %q, want unread", roles[seats[1]])
|
||||||
|
}
|
||||||
|
|
||||||
|
// After the recipient reads, the filter drops it and the seat flips to 'read'.
|
||||||
|
if _, err := svc.MarkRead(ctx, gameID, seats[1]); err != nil {
|
||||||
|
t.Fatalf("mark read: %v", err)
|
||||||
|
}
|
||||||
|
if items, _ := svc.AdminListMessages(ctx, social.AdminMessageFilter{GameID: gameID, UnreadOnly: true}, 50, 0); len(items) != 0 {
|
||||||
|
t.Errorf("unread filter should be empty after read, got %d", len(items))
|
||||||
|
}
|
||||||
|
card2, err := svc.AdminMessageDetail(ctx, msg.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("detail after read: %v", err)
|
||||||
|
}
|
||||||
|
for _, s := range card2.Seats {
|
||||||
|
if s.AccountID == seats[1] && s.Role != "read" {
|
||||||
|
t.Errorf("recipient role after read = %q, want read", s.Role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -134,11 +134,13 @@ func TestDictionaryUpdateFlow(t *testing.T) {
|
|||||||
// newGameServiceOn builds a game service over the shared pool but a caller-supplied
|
// newGameServiceOn builds a game service over the shared pool but a caller-supplied
|
||||||
// dictionary directory, version and registry, for the isolated dictionary tests.
|
// dictionary directory, version and registry, for the isolated dictionary tests.
|
||||||
func newGameServiceOn(dir, version string, reg *engine.Registry) *game.Service {
|
func newGameServiceOn(dir, version string, reg *engine.Registry) *game.Service {
|
||||||
return game.NewService(
|
svc := game.NewService(
|
||||||
game.NewStore(testDB), account.NewStore(testDB), reg,
|
game.NewStore(testDB), account.NewStore(testDB), reg,
|
||||||
game.Config{DictDir: dir, DictVersion: version, TimeoutSweepInterval: time.Minute, CacheTTL: time.Hour},
|
game.Config{DictDir: dir, DictVersion: version, TimeoutSweepInterval: time.Minute, CacheTTL: time.Hour},
|
||||||
zap.NewNop(),
|
zap.NewNop(),
|
||||||
)
|
)
|
||||||
|
svc.SetFirstMoveEntropy(seatZeroFirstMove)
|
||||||
|
return svc
|
||||||
}
|
}
|
||||||
|
|
||||||
// seedDawgs copies the committed DAWG of every variant from src into dst (flat).
|
// seedDawgs copies the committed DAWG of every variant from src into dst (flat).
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -134,12 +135,20 @@ func TestUpdateProfilePersists(t *testing.T) {
|
|||||||
store := account.NewStore(testDB)
|
store := account.NewStore(testDB)
|
||||||
acc := provisionAccount(t)
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
// A fresh account defaults to Erudit only (the DB-level column default).
|
||||||
|
if def, err := store.GetByID(ctx, acc); err != nil {
|
||||||
|
t.Fatalf("get default: %v", err)
|
||||||
|
} else if want := []string{"erudit_ru"}; !slices.Equal(def.VariantPreferences, want) {
|
||||||
|
t.Errorf("default variant preferences = %v, want %v", def.VariantPreferences, want)
|
||||||
|
}
|
||||||
|
|
||||||
updated, err := store.UpdateProfile(ctx, acc, account.ProfileUpdate{
|
updated, err := store.UpdateProfile(ctx, acc, account.ProfileUpdate{
|
||||||
DisplayName: "Kaya",
|
DisplayName: "Kaya",
|
||||||
PreferredLanguage: "ru",
|
PreferredLanguage: "ru",
|
||||||
TimeZone: "Europe/Moscow",
|
TimeZone: "Europe/Moscow",
|
||||||
BlockChat: true,
|
BlockChat: true,
|
||||||
BlockFriendRequests: true,
|
BlockFriendRequests: true,
|
||||||
|
VariantPreferences: []string{"scrabble_en", "erudit_ru"},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("update profile: %v", err)
|
t.Fatalf("update profile: %v", err)
|
||||||
@@ -157,6 +166,10 @@ func TestUpdateProfilePersists(t *testing.T) {
|
|||||||
if reloaded.TimeZone != "Europe/Moscow" || !reloaded.BlockChat {
|
if reloaded.TimeZone != "Europe/Moscow" || !reloaded.BlockChat {
|
||||||
t.Errorf("profile did not persist: %+v", reloaded)
|
t.Errorf("profile did not persist: %+v", reloaded)
|
||||||
}
|
}
|
||||||
|
// The text[] column round-trips and is stored canonically (Erudit-first).
|
||||||
|
if want := []string{"erudit_ru", "scrabble_en"}; !slices.Equal(reloaded.VariantPreferences, want) {
|
||||||
|
t.Errorf("variant preferences = %v, want %v", reloaded.VariantPreferences, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestUpdateProfileOffsetTimezone checks the UTC-offset timezone: it is
|
// TestUpdateProfileOffsetTimezone checks the UTC-offset timezone: it is
|
||||||
@@ -170,6 +183,7 @@ func TestUpdateProfileOffsetTimezone(t *testing.T) {
|
|||||||
DisplayName: "Kaya",
|
DisplayName: "Kaya",
|
||||||
PreferredLanguage: "en",
|
PreferredLanguage: "en",
|
||||||
TimeZone: "+03:00",
|
TimeZone: "+03:00",
|
||||||
|
VariantPreferences: []string{"erudit_ru"},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("update with offset timezone: %v", err)
|
t.Fatalf("update with offset timezone: %v", err)
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/feedback"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newFeedbackService() *feedback.Service {
|
||||||
|
return feedback.NewService(feedback.NewStore(testDB), account.NewStore(testDB))
|
||||||
|
}
|
||||||
|
|
||||||
|
// latestFeedbackID returns the id of the account's single message (across states).
|
||||||
|
func latestFeedbackID(t *testing.T, svc *feedback.Service, acc uuid.UUID) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
for _, status := range []string{"unread", "read", "archived"} {
|
||||||
|
rows, err := svc.AdminList(ctx, feedback.AdminFilter{AccountID: acc, Status: status}, 50, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin list %s: %v", status, err)
|
||||||
|
}
|
||||||
|
if len(rows) > 0 {
|
||||||
|
return rows[0].ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("no feedback message for account")
|
||||||
|
return uuid.Nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackGuestRejected(t *testing.T) {
|
||||||
|
svc := newFeedbackService()
|
||||||
|
guest := provisionGuest(t)
|
||||||
|
if err := svc.Submit(context.Background(), guest, "hi", nil, "", "web", "1.2.3.4"); !errors.Is(err, feedback.ErrGuestForbidden) {
|
||||||
|
t.Fatalf("guest submit err = %v, want ErrGuestForbidden", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackSubmitGateAndReplyLifecycle(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
if err := svc.Submit(ctx, acc, " please fix the board ", []byte("PNGDATA"), "shot.png", "ios", "9.9.9.9"); err != nil {
|
||||||
|
t.Fatalf("submit: %v", err)
|
||||||
|
}
|
||||||
|
// Anti-spam gate: a second message is refused while the first is unreviewed.
|
||||||
|
if err := svc.Submit(ctx, acc, "again", nil, "", "web", ""); !errors.Is(err, feedback.ErrPendingReview) {
|
||||||
|
t.Fatalf("second submit err = %v, want ErrPendingReview", err)
|
||||||
|
}
|
||||||
|
if st, err := svc.State(ctx, acc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if st.CanSend || st.BlockedReason != "pending" || st.Reply != nil {
|
||||||
|
t.Fatalf("state = %+v, want pending / no reply", st)
|
||||||
|
}
|
||||||
|
|
||||||
|
id := latestFeedbackID(t, svc, acc)
|
||||||
|
m, err := svc.AdminGet(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin get: %v", err)
|
||||||
|
}
|
||||||
|
if m.Body != "please fix the board" { // trimmed
|
||||||
|
t.Fatalf("body = %q, want trimmed", m.Body)
|
||||||
|
}
|
||||||
|
if !m.HasAttachment || m.AttachmentName != "shot.png" || m.Channel != "ios" || m.SenderIP != "9.9.9.9" {
|
||||||
|
t.Fatalf("admin message = %+v", m)
|
||||||
|
}
|
||||||
|
if name, data, ok, err := svc.Attachment(ctx, id); err != nil || !ok || name != "shot.png" || string(data) != "PNGDATA" {
|
||||||
|
t.Fatalf("attachment = (%q, %q, %v, %v)", name, data, ok, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply: marks the message read (so the player can send again) and is undelivered.
|
||||||
|
if err := svc.Reply(ctx, id, "We are on it."); err != nil {
|
||||||
|
t.Fatalf("reply: %v", err)
|
||||||
|
}
|
||||||
|
if unread, err := svc.ReplyUnread(ctx, acc); err != nil || !unread {
|
||||||
|
t.Fatalf("reply unread = %v (err %v), want true", unread, err)
|
||||||
|
}
|
||||||
|
st, err := svc.State(ctx, acc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !st.CanSend {
|
||||||
|
t.Fatal("want canSend true after the message was read via reply")
|
||||||
|
}
|
||||||
|
if st.Reply == nil || st.Reply.Body != "We are on it." {
|
||||||
|
t.Fatalf("reply not shown: %+v", st.Reply)
|
||||||
|
}
|
||||||
|
// Fetching the state delivered the reply: the badge clears.
|
||||||
|
if unread, err := svc.ReplyUnread(ctx, acc); err != nil || unread {
|
||||||
|
t.Fatalf("reply unread = %v (err %v), want false after State", unread, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The reply is hidden one week after it was delivered.
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.feedback_messages SET reply_read_at = now() - interval '8 days' WHERE message_id = $1`, id); err != nil {
|
||||||
|
t.Fatalf("age reply: %v", err)
|
||||||
|
}
|
||||||
|
if st, err := svc.State(ctx, acc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if st.Reply != nil {
|
||||||
|
t.Fatalf("reply should be hidden after a week, got %+v", st.Reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackReplyHiddenAfterNewMessage(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
// msg1, replied → the player can send again and currently sees the reply.
|
||||||
|
if err := svc.Submit(ctx, acc, "first", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit msg1: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.Reply(ctx, latestFeedbackID(t, svc, acc), "the answer"); err != nil {
|
||||||
|
t.Fatalf("reply: %v", err)
|
||||||
|
}
|
||||||
|
if st, err := svc.State(ctx, acc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if st.Reply == nil || st.Reply.Body != "the answer" {
|
||||||
|
t.Fatalf("reply not shown before the new message: %+v", st.Reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sending a new message immediately drops the previous reply (it now belongs to an
|
||||||
|
// older message), even though it is well within the one-week window.
|
||||||
|
if err := svc.Submit(ctx, acc, "second", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit msg2: %v", err)
|
||||||
|
}
|
||||||
|
st, err := svc.State(ctx, acc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.Reply != nil {
|
||||||
|
t.Fatalf("reply should be hidden after a new message, got %+v", st.Reply)
|
||||||
|
}
|
||||||
|
if st.CanSend || st.BlockedReason != "pending" {
|
||||||
|
t.Fatalf("state after new message = %+v, want pending", st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackSnapshotsLanguage(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.accounts SET preferred_language = 'en' WHERE account_id = $1`, acc); err != nil {
|
||||||
|
t.Fatalf("set language: %v", err)
|
||||||
|
}
|
||||||
|
// A message snapshots the sender's interface language at submit time.
|
||||||
|
if err := svc.Submit(ctx, acc, "from telegram", nil, "", "telegram", ""); err != nil {
|
||||||
|
t.Fatalf("submit: %v", err)
|
||||||
|
}
|
||||||
|
id := latestFeedbackID(t, svc, acc)
|
||||||
|
if m, err := svc.AdminGet(ctx, id); err != nil {
|
||||||
|
t.Fatalf("admin get: %v", err)
|
||||||
|
} else if m.Lang != "en" {
|
||||||
|
t.Fatalf("snapshot = lang %q, want en", m.Lang)
|
||||||
|
}
|
||||||
|
// Changing the account afterwards must not change the stored snapshot.
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.accounts SET preferred_language = 'ru' WHERE account_id = $1`, acc); err != nil {
|
||||||
|
t.Fatalf("change language: %v", err)
|
||||||
|
}
|
||||||
|
if m, err := svc.AdminGet(ctx, id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if m.Lang != "en" {
|
||||||
|
t.Fatalf("snapshot drifted after account change = lang %q, want en", m.Lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackBanRole(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
if err := accounts.GrantRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
|
||||||
|
t.Fatalf("grant role: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.Submit(ctx, acc, "hi", nil, "", "web", ""); !errors.Is(err, feedback.ErrBanned) {
|
||||||
|
t.Fatalf("banned submit err = %v, want ErrBanned", err)
|
||||||
|
}
|
||||||
|
if st, err := svc.State(ctx, acc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if st.CanSend || st.BlockedReason != "banned" {
|
||||||
|
t.Fatalf("state = %+v, want banned", st)
|
||||||
|
}
|
||||||
|
// Revoke restores submission (the /users unblock path).
|
||||||
|
if err := accounts.RevokeRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
|
||||||
|
t.Fatalf("revoke role: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.Submit(ctx, acc, "hi again", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit after unban: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackValidation(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
attachment []byte
|
||||||
|
attachmentName string
|
||||||
|
want error
|
||||||
|
}{
|
||||||
|
{"empty body", " ", nil, "", feedback.ErrEmptyMessage},
|
||||||
|
{"too long", strings.Repeat("a", 1025), nil, "", feedback.ErrMessageTooLong},
|
||||||
|
{"bad type", "ok", []byte("x"), "evil.exe", feedback.ErrAttachmentType},
|
||||||
|
{"too large", "ok", make([]byte, 1_000_001), "a.png", feedback.ErrAttachmentTooLarge},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
acc := provisionAccount(t) // fresh account so the pending gate never fires first
|
||||||
|
if err := svc.Submit(ctx, acc, tt.body, tt.attachment, tt.attachmentName, "web", ""); !errors.Is(err, tt.want) {
|
||||||
|
t.Fatalf("submit err = %v, want %v", err, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackAdminLifecycle(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
if err := svc.Submit(ctx, acc, "first report", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit: %v", err)
|
||||||
|
}
|
||||||
|
id := latestFeedbackID(t, svc, acc)
|
||||||
|
|
||||||
|
inCount := func(status string) int {
|
||||||
|
t.Helper()
|
||||||
|
n, err := svc.AdminCount(ctx, feedback.AdminFilter{AccountID: acc, Status: status})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("count %s: %v", status, err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
if inCount("unread") != 1 || inCount("read") != 0 || inCount("archived") != 0 {
|
||||||
|
t.Fatalf("after submit: unread=%d read=%d archived=%d", inCount("unread"), inCount("read"), inCount("archived"))
|
||||||
|
}
|
||||||
|
// Marking read moves it from the unread queue to the read list.
|
||||||
|
if err := svc.MarkRead(ctx, id); err != nil {
|
||||||
|
t.Fatalf("mark read: %v", err)
|
||||||
|
}
|
||||||
|
if inCount("unread") != 0 || inCount("read") != 1 {
|
||||||
|
t.Fatalf("after read: unread=%d read=%d", inCount("unread"), inCount("read"))
|
||||||
|
}
|
||||||
|
// Archiving moves it to the archive.
|
||||||
|
if err := svc.Archive(ctx, id); err != nil {
|
||||||
|
t.Fatalf("archive: %v", err)
|
||||||
|
}
|
||||||
|
if inCount("read") != 0 || inCount("archived") != 1 {
|
||||||
|
t.Fatalf("after archive: read=%d archived=%d", inCount("read"), inCount("archived"))
|
||||||
|
}
|
||||||
|
// Deleting removes it entirely.
|
||||||
|
if err := svc.Delete(ctx, id); err != nil {
|
||||||
|
t.Fatalf("delete: %v", err)
|
||||||
|
}
|
||||||
|
if inCount("archived") != 0 {
|
||||||
|
t.Fatalf("after delete: archived=%d, want 0", inCount("archived"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFeedbackDeleteAllByAccount(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newFeedbackService()
|
||||||
|
acc := provisionAccount(t)
|
||||||
|
|
||||||
|
if err := svc.Submit(ctx, acc, "one", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.DeleteAllByAccount(ctx, acc); err != nil {
|
||||||
|
t.Fatalf("delete all: %v", err)
|
||||||
|
}
|
||||||
|
// The pending gate is clear again (no messages left), so the account can submit.
|
||||||
|
if has, err := svc.ReplyUnread(ctx, acc); err != nil || has {
|
||||||
|
t.Fatalf("reply unread after delete-all = %v (err %v)", has, err)
|
||||||
|
}
|
||||||
|
if err := svc.Submit(ctx, acc, "fresh", nil, "", "web", ""); err != nil {
|
||||||
|
t.Fatalf("submit after delete-all: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The first-move-draw suite covers the official seeding (docs/ARCHITECTURE.md §6): the draw is
|
||||||
|
// recorded with the game, decides seat 0 (the first mover), and — in auto-match — runs against
|
||||||
|
// a synthetic opponent at open time whose draw rows are back-filled when a real opponent joins.
|
||||||
|
|
||||||
|
// TestCreateRecordsFirstMoveDraws checks a directly-seated game records the draw against the
|
||||||
|
// real seated accounts and seats the drawn leader (the suite's deterministic draw elects the
|
||||||
|
// first-listed account) at seat 0.
|
||||||
|
func TestCreateRecordsFirstMoveDraws(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
a := provisionAccount(t)
|
||||||
|
b := provisionAccount(t)
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{Variant: engine.VariantEnglish, Seats: []uuid.UUID{a, b}, TurnTimeout: 24 * time.Hour, Seed: 1})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create: %v", err)
|
||||||
|
}
|
||||||
|
if g.Seats[0].AccountID != a || g.Seats[1].AccountID != b {
|
||||||
|
t.Fatalf("seats = [%s %s], want [a b]", g.Seats[0].AccountID, g.Seats[1].AccountID)
|
||||||
|
}
|
||||||
|
draws, err := svc.SetupDraws(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("setup draws: %v", err)
|
||||||
|
}
|
||||||
|
// seatZeroFirstMove resolves in one round: the first contender (a) draws a blank and wins.
|
||||||
|
if len(draws) != 2 {
|
||||||
|
t.Fatalf("draws = %d, want 2 (one round, two players)", len(draws))
|
||||||
|
}
|
||||||
|
if draws[0].Account != a || !draws[0].Blank {
|
||||||
|
t.Fatalf("draw[0] = %+v, want a having drawn a blank", draws[0])
|
||||||
|
}
|
||||||
|
if draws[1].Account != b {
|
||||||
|
t.Fatalf("draw[1] account = %s, want b", draws[1].Account)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAutoMatchDrawBackfilledOnJoin checks an open auto-match game records the draw at open
|
||||||
|
// time against the synthetic opponent (a NULL account) and back-fills those rows to the real
|
||||||
|
// opponent when they join.
|
||||||
|
func TestAutoMatchDrawBackfilledOnJoin(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
svc := newGameService()
|
||||||
|
starter := provisionAccount(t)
|
||||||
|
g := openGame(t, svc, starter, evenOpeningSeed(t))
|
||||||
|
|
||||||
|
draws, err := svc.SetupDraws(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("setup draws: %v", err)
|
||||||
|
}
|
||||||
|
if len(draws) != 2 {
|
||||||
|
t.Fatalf("open draws = %d, want 2", len(draws))
|
||||||
|
}
|
||||||
|
var nullSeen, starterSeen bool
|
||||||
|
for _, d := range draws {
|
||||||
|
switch d.Account {
|
||||||
|
case uuid.Nil:
|
||||||
|
nullSeen = true
|
||||||
|
case starter:
|
||||||
|
starterSeen = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !nullSeen || !starterSeen {
|
||||||
|
t.Fatalf("open draws = %+v, want the starter and a NULL synthetic opponent", draws)
|
||||||
|
}
|
||||||
|
|
||||||
|
joiner := provisionAccount(t)
|
||||||
|
if _, joined, err := svc.OpenOrJoin(ctx, joiner, openParams(0), time.Now().Add(time.Minute), nil); err != nil || !joined {
|
||||||
|
t.Fatalf("join = (joined %v, err %v), want joined", joined, err)
|
||||||
|
}
|
||||||
|
after, err := svc.SetupDraws(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("setup draws after join: %v", err)
|
||||||
|
}
|
||||||
|
for _, d := range after {
|
||||||
|
if d.Account == uuid.Nil {
|
||||||
|
t.Fatalf("draw still NULL after join: %+v", d)
|
||||||
|
}
|
||||||
|
if d.Account != starter && d.Account != joiner {
|
||||||
|
t.Fatalf("draw account %s is neither player", d.Account)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReplayTimeline checks the admin replay timeline reconstructs the dealt racks and one
|
||||||
|
// played move: the step count, the drawn tiles, the bag remainder, the running score and the
|
||||||
|
// turn cursor.
|
||||||
|
func TestReplayTimeline(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
a := provisionAccount(t)
|
||||||
|
b := provisionAccount(t)
|
||||||
|
seed := evenOpeningSeed(t)
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{Variant: engine.VariantEnglish, Seats: []uuid.UUID{a, b}, TurnTimeout: 24 * time.Hour, Seed: seed})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create: %v", err)
|
||||||
|
}
|
||||||
|
hint, ok := newMirror(t, seed, 2).HintView()
|
||||||
|
if !ok || len(hint.Tiles) == 0 {
|
||||||
|
t.Fatal("no opening move for the seed")
|
||||||
|
}
|
||||||
|
if _, err := svc.SubmitPlay(ctx, g.ID, a, hint.Tiles); err != nil {
|
||||||
|
t.Fatalf("play: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tl, err := svc.ReplayTimeline(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("replay timeline: %v", err)
|
||||||
|
}
|
||||||
|
if len(tl.Steps) != 2 {
|
||||||
|
t.Fatalf("steps = %d, want 2 (deal + one move)", len(tl.Steps))
|
||||||
|
}
|
||||||
|
deal := tl.Steps[0]
|
||||||
|
if deal.Move != nil {
|
||||||
|
t.Fatalf("step 0 must be the deal, got move %+v", deal.Move)
|
||||||
|
}
|
||||||
|
rackSize := len(deal.Racks[0])
|
||||||
|
if rackSize == 0 || len(deal.Racks) != 2 || len(deal.Racks[1]) != rackSize {
|
||||||
|
t.Fatalf("deal racks = %v, want two equal full racks", deal.Racks)
|
||||||
|
}
|
||||||
|
move := tl.Steps[1]
|
||||||
|
if move.Move == nil || move.Move.Action != "play" {
|
||||||
|
t.Fatalf("step 1 move = %+v, want a play", move.Move)
|
||||||
|
}
|
||||||
|
if len(move.Drawn) != len(hint.Tiles) {
|
||||||
|
t.Fatalf("drawn = %v, want %d refilled tiles", move.Drawn, len(hint.Tiles))
|
||||||
|
}
|
||||||
|
if move.BagLen != deal.BagLen-len(hint.Tiles) {
|
||||||
|
t.Fatalf("bag after play = %d, want %d", move.BagLen, deal.BagLen-len(hint.Tiles))
|
||||||
|
}
|
||||||
|
if len(move.Racks[0]) != rackSize {
|
||||||
|
t.Fatalf("mover rack after refill = %d, want %d", len(move.Racks[0]), rackSize)
|
||||||
|
}
|
||||||
|
if move.Scores[0] <= 0 {
|
||||||
|
t.Fatalf("seat 0 score after play = %d, want > 0", move.Scores[0])
|
||||||
|
}
|
||||||
|
if move.ToMove != 1 {
|
||||||
|
t.Fatalf("to_move after seat 0 play = %d, want 1", move.ToMove)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestForfeitAllResignsActiveGame checks the game-side effect of a block on a two-player game:
|
||||||
|
// ForfeitAllForAccount resigns the blocked player, finishing the game with the opponent winning.
|
||||||
|
func TestForfeitAllResignsActiveGame(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
gid, seats := newGameWithSeats(t, 2) // seats[0] = blocked, seats[1] = opponent
|
||||||
|
|
||||||
|
n, err := svc.ForfeitAllForAccount(ctx, seats[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("forfeit all: %v", err)
|
||||||
|
}
|
||||||
|
if n < 1 {
|
||||||
|
t.Fatalf("forfeit count = %d, want at least 1", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
g, err := svc.GameByID(ctx, gid)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get game: %v", err)
|
||||||
|
}
|
||||||
|
if g.Status != game.StatusFinished {
|
||||||
|
t.Errorf("status = %q, want finished", g.Status)
|
||||||
|
}
|
||||||
|
if w := seatWinner(g, seats[0]); w {
|
||||||
|
t.Error("the blocked player must not be the winner")
|
||||||
|
}
|
||||||
|
if w := seatWinner(g, seats[1]); !w {
|
||||||
|
t.Error("the opponent must win when the blocked player forfeits")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestForfeitAllCancelsOpenGame checks that a block deletes the blocked player's open auto-match
|
||||||
|
// game (no opponent to resign against), clearing it from the matchmaking pool.
|
||||||
|
func TestForfeitAllCancelsOpenGame(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
svc := newGameService()
|
||||||
|
starter := provisionAccount(t)
|
||||||
|
g := openGame(t, svc, starter, evenOpeningSeed(t))
|
||||||
|
|
||||||
|
n, err := svc.ForfeitAllForAccount(ctx, starter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("forfeit all: %v", err)
|
||||||
|
}
|
||||||
|
if n < 1 {
|
||||||
|
t.Fatalf("forfeit count = %d, want at least 1", n)
|
||||||
|
}
|
||||||
|
if c := gameRowCount(t, g.ID); c != 0 {
|
||||||
|
t.Errorf("open game rows after forfeit = %d, want 0 (deleted)", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestForfeitAllResignsSeatInMultiplayerGame checks that in a 3-player game the blocked player's
|
||||||
|
// seat is resigned while the game continues for the remaining players.
|
||||||
|
func TestForfeitAllResignsSeatInMultiplayerGame(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
gid, seats := newGameWithSeats(t, 3)
|
||||||
|
|
||||||
|
n, err := svc.ForfeitAllForAccount(ctx, seats[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("forfeit all: %v", err)
|
||||||
|
}
|
||||||
|
if n < 1 {
|
||||||
|
t.Fatalf("forfeit count = %d, want at least 1", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
g, err := svc.GameByID(ctx, gid)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get game: %v", err)
|
||||||
|
}
|
||||||
|
if g.Status != game.StatusActive {
|
||||||
|
t.Errorf("status = %q, want still active (two seats remain)", g.Status)
|
||||||
|
}
|
||||||
|
if c := resignMoveCount(t, gid, 0); c != 1 {
|
||||||
|
t.Errorf("resign moves for seat 0 = %d, want 1", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// seatWinner reports the is_winner flag for the given account's seat in g.
|
||||||
|
func seatWinner(g game.Game, accountID uuid.UUID) bool {
|
||||||
|
for _, s := range g.Seats {
|
||||||
|
if s.AccountID == accountID {
|
||||||
|
return s.IsWinner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// gameRowCount counts the rows in the games table for gameID (0 once it is deleted).
|
||||||
|
func gameRowCount(t *testing.T, gameID uuid.UUID) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := testDB.QueryRowContext(context.Background(),
|
||||||
|
`SELECT count(*) FROM backend.games WHERE game_id = $1`, gameID).Scan(&n); err != nil {
|
||||||
|
t.Fatalf("count game rows: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// resignMoveCount counts the resign moves journalled for a seat in a game.
|
||||||
|
func resignMoveCount(t *testing.T, gameID uuid.UUID, seat int) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := testDB.QueryRowContext(context.Background(),
|
||||||
|
`SELECT count(*) FROM backend.game_moves WHERE game_id = $1 AND action = 'resign' AND seat = $2`,
|
||||||
|
gameID, seat).Scan(&n); err != nil {
|
||||||
|
t.Fatalf("count resign moves: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.uber.org/zap/zaptest"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The game-limit suite covers the simultaneous quick-game cap (game.MaxActiveQuickGames):
|
||||||
|
// the counting rule (Store/Service.CountActiveQuickGames) and the HTTP gate that refuses a
|
||||||
|
// new game once the cap is reached, while accepting an incoming invitation stays allowed.
|
||||||
|
|
||||||
|
// TestCountActiveQuickGames checks the count includes active and open quick games (the
|
||||||
|
// honest-AI ones among them) and excludes finished games, friend games (created by
|
||||||
|
// invitation) and games the account is not seated in.
|
||||||
|
func TestCountActiveQuickGames(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
games := newGameService()
|
||||||
|
human := provisionAccount(t)
|
||||||
|
opp := provisionAccount(t)
|
||||||
|
|
||||||
|
if n := mustCount(t, games, human); n != 0 {
|
||||||
|
t.Fatalf("fresh account count = %d, want 0", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An open (awaiting-opponent) quick game counts.
|
||||||
|
if _, _, err := games.OpenOrJoin(ctx, human, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, TurnTimeout: 24 * time.Hour,
|
||||||
|
}, time.Now().Add(time.Minute), nil); err != nil {
|
||||||
|
t.Fatalf("open quick game: %v", err)
|
||||||
|
}
|
||||||
|
// An active quick game and an honest-AI quick game both count (neither has an invitation row).
|
||||||
|
mustCreateQuick(t, games, []uuid.UUID{human, opp}, false, 1)
|
||||||
|
mustCreateQuick(t, games, []uuid.UUID{human, opp}, true, 2)
|
||||||
|
|
||||||
|
// A finished quick game does NOT count.
|
||||||
|
fin := mustCreateQuick(t, games, []uuid.UUID{human, opp}, false, 3)
|
||||||
|
if _, err := testDB.ExecContext(ctx, `UPDATE backend.games SET status='finished' WHERE game_id=$1`, fin); err != nil {
|
||||||
|
t.Fatalf("finish game: %v", err)
|
||||||
|
}
|
||||||
|
// A game the human is not seated in does NOT count.
|
||||||
|
mustCreateQuick(t, games, []uuid.UUID{opp, provisionAccount(t)}, false, 4)
|
||||||
|
// A friend game (created by invitation) does NOT count, even though it is active.
|
||||||
|
startFriendGame(t, human)
|
||||||
|
|
||||||
|
if n := mustCount(t, games, human); n != 3 {
|
||||||
|
t.Fatalf("active quick count = %d, want 3 (active + AI + open)", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestGameLimitGate drives the cap through the assembled HTTP server: under the cap the lobby
|
||||||
|
// reports at_game_limit false; at the cap it flips to true and both new-game endpoints (quick
|
||||||
|
// enqueue and invitation creation) are refused with 409 game_limit_reached, while accepting an
|
||||||
|
// incoming invitation is still allowed.
|
||||||
|
func TestGameLimitGate(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
games := newGameService()
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: account.NewStore(testDB),
|
||||||
|
Games: games,
|
||||||
|
Matchmaker: newMatchmaker(t, newRobotService(t, newGameService()), time.Minute, 0),
|
||||||
|
Invitations: newInvitationService(),
|
||||||
|
})
|
||||||
|
|
||||||
|
human := provisionAccount(t)
|
||||||
|
opp := provisionAccount(t)
|
||||||
|
|
||||||
|
// Under the cap: the lobby reports the player is not limited.
|
||||||
|
if gamesListAtLimit(t, srv, human) {
|
||||||
|
t.Fatal("a fresh account must be under the game limit")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reach the cap with active quick games seating the human (no invitation row → quick).
|
||||||
|
for i := 0; i < game.MaxActiveQuickGames; i++ {
|
||||||
|
mustCreateQuick(t, games, []uuid.UUID{human, opp}, false, int64(i+1))
|
||||||
|
}
|
||||||
|
|
||||||
|
// At the cap: the lobby flags it and both create paths are refused with the stable code.
|
||||||
|
if !gamesListAtLimit(t, srv, human) {
|
||||||
|
t.Fatalf("at %d games at_game_limit must be true", game.MaxActiveQuickGames)
|
||||||
|
}
|
||||||
|
// erudit_ru is in the default variant preferences, so the variant gate passes and the
|
||||||
|
// game-limit gate is what fires here.
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/lobby/enqueue", human, `{"variant":"erudit_ru"}`); rec.Code != http.StatusConflict || errorCode(t, rec) != "game_limit_reached" {
|
||||||
|
t.Fatalf("enqueue at limit = (%d, %q), want (409, game_limit_reached)", rec.Code, errorCode(t, rec))
|
||||||
|
}
|
||||||
|
invBody := fmt.Sprintf(`{"variant":"erudit_ru","invitee_ids":[%q]}`, opp.String())
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/invitations", human, invBody); rec.Code != http.StatusConflict || errorCode(t, rec) != "game_limit_reached" {
|
||||||
|
t.Fatalf("invitation at limit = (%d, %q), want (409, game_limit_reached)", rec.Code, errorCode(t, rec))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accepting an incoming invitation is never blocked, even at the cap: another player invites
|
||||||
|
// the capped human, who accepts over HTTP and the game starts (friend games do not count).
|
||||||
|
inviter := provisionAccount(t)
|
||||||
|
inv := newInvitationService()
|
||||||
|
invitation, err := inv.CreateInvitation(ctx, inviter, []uuid.UUID{human}, englishInvite())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create invitation: %v", err)
|
||||||
|
}
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/invitations/"+invitation.ID.String()+"/accept", human, ""); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("accept at limit = %d (%s), want 200 — accept must bypass the cap", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// mustCount returns the account's active-quick-game count, failing on error.
|
||||||
|
func mustCount(t *testing.T, games *game.Service, id uuid.UUID) int {
|
||||||
|
t.Helper()
|
||||||
|
n, err := games.CountActiveQuickGames(context.Background(), id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("count active quick games: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// mustCreateQuick creates an active quick game (no invitation) seating the given accounts and
|
||||||
|
// returns its id; vsAI flags an honest-AI game (the service then applies the 7-day clock).
|
||||||
|
func mustCreateQuick(t *testing.T, games *game.Service, seats []uuid.UUID, vsAI bool, seed int64) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
p := game.CreateParams{Variant: engine.VariantEnglish, Seats: seats, TurnTimeout: 24 * time.Hour, Seed: seed}
|
||||||
|
if vsAI {
|
||||||
|
p.VsAI = true
|
||||||
|
p.TurnTimeout = 0 // the service applies the 7-day AI inactivity clock for vs_ai games
|
||||||
|
}
|
||||||
|
g, err := games.Create(context.Background(), p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create quick game (vsAI=%v): %v", vsAI, err)
|
||||||
|
}
|
||||||
|
return g.ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// startFriendGame has a fresh inviter invite the given account to a friend game and the invitee
|
||||||
|
// accept it, so the (active) friend game exists with its game_invitations row.
|
||||||
|
func startFriendGame(t *testing.T, invitee uuid.UUID) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
inv := newInvitationService()
|
||||||
|
inviter := provisionAccount(t)
|
||||||
|
invitation, err := inv.CreateInvitation(ctx, inviter, []uuid.UUID{invitee}, englishInvite())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create invitation: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := inv.RespondInvitation(ctx, invitation.ID, invitee, true); err != nil {
|
||||||
|
t.Fatalf("accept invitation: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// gamesListAtLimit fetches /api/v1/user/games and returns its at_game_limit flag.
|
||||||
|
func gamesListAtLimit(t *testing.T, srv *server.Server, id uuid.UUID) bool {
|
||||||
|
t.Helper()
|
||||||
|
rec := userGet(t, srv, "/api/v1/user/games", id)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("games.list status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
AtGameLimit bool `json:"at_game_limit"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatalf("decode games.list: %v", err)
|
||||||
|
}
|
||||||
|
return body.AtGameLimit
|
||||||
|
}
|
||||||
|
|
||||||
|
// userPost issues an authenticated JSON POST (X-User-ID) against the assembled server.
|
||||||
|
func userPost(t *testing.T, srv *server.Server, path string, id uuid.UUID, body string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||||
|
req.Header.Set("X-User-ID", id.String())
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
"scrabble/backend/internal/engine"
|
"scrabble/backend/internal/engine"
|
||||||
"scrabble/backend/internal/game"
|
"scrabble/backend/internal/game"
|
||||||
)
|
)
|
||||||
@@ -120,8 +121,8 @@ func TestGameLifecycleAndStats(t *testing.T) {
|
|||||||
t.Fatalf("final game not finished: %+v", last.Game)
|
t.Fatalf("final game not finished: %+v", last.Game)
|
||||||
}
|
}
|
||||||
|
|
||||||
w0, l0, d0, mg0, _, ok0 := readStats(t, seats[0])
|
w0, l0, d0, mg0, mw0, ok0 := readStats(t, seats[0])
|
||||||
w1, l1, d1, mg1, _, ok1 := readStats(t, seats[1])
|
w1, l1, d1, mg1, mw1, ok1 := readStats(t, seats[1])
|
||||||
if !ok0 || !ok1 {
|
if !ok0 || !ok1 {
|
||||||
t.Fatal("both players must have a stats row")
|
t.Fatal("both players must have a stats row")
|
||||||
}
|
}
|
||||||
@@ -133,6 +134,52 @@ func TestGameLifecycleAndStats(t *testing.T) {
|
|||||||
if !decisive && !draw {
|
if !decisive && !draw {
|
||||||
t.Errorf("inconsistent W/L/D: p0(%d/%d/%d) p1(%d/%d/%d)", w0, l0, d0, w1, l1, d1)
|
t.Errorf("inconsistent W/L/D: p0(%d/%d/%d) p1(%d/%d/%d)", w0, l0, d0, w1, l1, d1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Each player who made a scoring play gets exactly one per-variant best move (only
|
||||||
|
// scrabble_en was played here); its score equals the aggregate max_word_points and it
|
||||||
|
// carries the decoded word as tiles.
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
for _, p := range []struct {
|
||||||
|
id uuid.UUID
|
||||||
|
maxWord int
|
||||||
|
}{{seats[0], mw0}, {seats[1], mw1}} {
|
||||||
|
if p.maxWord == 0 {
|
||||||
|
continue // a player who only passed has no best move
|
||||||
|
}
|
||||||
|
st, err := accounts.GetStats(ctx, p.id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get stats: %v", err)
|
||||||
|
}
|
||||||
|
// The player made at least one scoring play (maxWord > 0), so the moves aggregate is
|
||||||
|
// positive; no hints were taken in this greedy game, so the hints aggregate stays 0.
|
||||||
|
if st.Moves <= 0 {
|
||||||
|
t.Errorf("moves = %d, want > 0", st.Moves)
|
||||||
|
}
|
||||||
|
if st.HintsUsed != 0 {
|
||||||
|
t.Errorf("hints used = %d, want 0 (no hints taken)", st.HintsUsed)
|
||||||
|
}
|
||||||
|
if len(st.BestMoves) != 1 {
|
||||||
|
t.Fatalf("want one best move (only scrabble_en played), got %d: %+v", len(st.BestMoves), st.BestMoves)
|
||||||
|
}
|
||||||
|
bm := st.BestMoves[0]
|
||||||
|
if bm.Variant != engine.VariantEnglish.String() {
|
||||||
|
t.Errorf("best move variant = %q, want %q", bm.Variant, engine.VariantEnglish.String())
|
||||||
|
}
|
||||||
|
if bm.Score != p.maxWord {
|
||||||
|
t.Errorf("best move score %d != max_word_points %d", bm.Score, p.maxWord)
|
||||||
|
}
|
||||||
|
if len(bm.Tiles) == 0 {
|
||||||
|
t.Error("best move word is empty")
|
||||||
|
}
|
||||||
|
for _, tl := range bm.Tiles {
|
||||||
|
if tl.Letter == "" {
|
||||||
|
t.Error("best move tile has empty letter")
|
||||||
|
}
|
||||||
|
if tl.Blank && tl.Value != 0 {
|
||||||
|
t.Errorf("blank tile must score 0, got %d", tl.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestReplayEquivalence plays a few moves through one service, then proves a
|
// TestReplayEquivalence plays a few moves through one service, then proves a
|
||||||
@@ -369,6 +416,15 @@ func TestHintPolicy(t *testing.T) {
|
|||||||
if _, err := svc.Hint(ctx, g.ID, seats[0]); err != nil { // spends the allowance
|
if _, err := svc.Hint(ctx, g.ID, seats[0]); err != nil { // spends the allowance
|
||||||
t.Fatalf("first hint: %v", err)
|
t.Fatalf("first hint: %v", err)
|
||||||
}
|
}
|
||||||
|
// The allowance is spent before the wallet: with an empty wallet, the state now reports no
|
||||||
|
// hints left and a zero wallet, so the per-game allowance (HintsRemaining-WalletBalance) is 0.
|
||||||
|
st, err := svc.GameState(ctx, g.ID, seats[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("state: %v", err)
|
||||||
|
}
|
||||||
|
if st.HintsRemaining != 0 || st.WalletBalance != 0 {
|
||||||
|
t.Errorf("after allowance hint: hints=%d wallet=%d, want 0/0", st.HintsRemaining, st.WalletBalance)
|
||||||
|
}
|
||||||
if _, err := svc.Hint(ctx, g.ID, seats[0]); !errors.Is(err, game.ErrNoHintsLeft) {
|
if _, err := svc.Hint(ctx, g.ID, seats[0]); !errors.Is(err, game.ErrNoHintsLeft) {
|
||||||
t.Fatalf("second hint = %v, want ErrNoHintsLeft", err)
|
t.Fatalf("second hint = %v, want ErrNoHintsLeft", err)
|
||||||
}
|
}
|
||||||
@@ -377,8 +433,18 @@ func TestHintPolicy(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("wallet hint: %v", err)
|
t.Fatalf("wallet hint: %v", err)
|
||||||
}
|
}
|
||||||
if res.HintsRemaining != 1 {
|
// The allowance stays exhausted; the wallet dropped 2->1, and WalletBalance carries it alone.
|
||||||
t.Errorf("hints remaining = %d, want 1", res.HintsRemaining)
|
if res.HintsRemaining != 1 || res.WalletBalance != 1 {
|
||||||
|
t.Errorf("wallet hint: hints=%d wallet=%d, want 1/1", res.HintsRemaining, res.WalletBalance)
|
||||||
|
}
|
||||||
|
// game_players.hints_used counts BOTH hints (1 allowance + 1 wallet) — the per-game total
|
||||||
|
// that feeds the player's lifetime hint statistics, not just the allowance.
|
||||||
|
st2, err := svc.GameState(ctx, g.ID, seats[0])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("state after wallet hint: %v", err)
|
||||||
|
}
|
||||||
|
if got := st2.Game.Seats[0].HintsUsed; got != 2 {
|
||||||
|
t.Errorf("hints_used = %d after allowance + wallet hint, want 2", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
off, err := svc.Create(ctx, game.CreateParams{
|
off, err := svc.Create(ctx, game.CreateParams{
|
||||||
@@ -477,6 +543,12 @@ func TestEvaluatePlayPreview(t *testing.T) {
|
|||||||
if bad.Valid {
|
if bad.Valid {
|
||||||
t.Error("disconnected play must be invalid")
|
t.Error("disconnected play must be invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A non-seated account cannot preview: with the game warm in the live cache, the
|
||||||
|
// membership check runs against the cached seat list (the hot path that skips GetGame).
|
||||||
|
if _, err := svc.EvaluatePlay(ctx, g.ID, provisionAccount(t), hint.Tiles); !errors.Is(err, game.ErrNotAPlayer) {
|
||||||
|
t.Errorf("evaluate by a non-player = %v, want ErrNotAPlayer", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestConcurrentSubmitSerialized confirms the per-game lock lets only one of two
|
// TestConcurrentSubmitSerialized confirms the per-game lock lets only one of two
|
||||||
|
|||||||
@@ -26,9 +26,10 @@ import (
|
|||||||
// assembly, and the stats reader. Helpers used by a single test file stay in
|
// assembly, and the stats reader. Helpers used by a single test file stay in
|
||||||
// that file; everything reused across files lives here.
|
// that file; everything reused across files lives here.
|
||||||
|
|
||||||
// newGameService builds a game service over the shared pool and registry.
|
// newGameService builds a game service over the shared pool and registry, with a
|
||||||
|
// deterministic first-move draw so the suite keeps a stable turn order.
|
||||||
func newGameService() *game.Service {
|
func newGameService() *game.Service {
|
||||||
return game.NewService(
|
svc := game.NewService(
|
||||||
game.NewStore(testDB),
|
game.NewStore(testDB),
|
||||||
account.NewStore(testDB),
|
account.NewStore(testDB),
|
||||||
testRegistry,
|
testRegistry,
|
||||||
@@ -40,6 +41,39 @@ func newGameService() *game.Service {
|
|||||||
},
|
},
|
||||||
zap.NewNop(),
|
zap.NewNop(),
|
||||||
)
|
)
|
||||||
|
svc.SetFirstMoveEntropy(seatZeroFirstMove)
|
||||||
|
return svc
|
||||||
|
}
|
||||||
|
|
||||||
|
// seatZeroFirstMove is a first-move-draw entropy factory that always elects the first
|
||||||
|
// listed account as the leader, keeping the integration suite's turn order stable
|
||||||
|
// despite the real draw's randomness: the first contender draws a blank — the best
|
||||||
|
// possible tile — and wins outright, the rest draw the first remaining tile. It is a
|
||||||
|
// factory so each game restarts the one-shot "blank" pick.
|
||||||
|
func seatZeroFirstMove() func(n int) (int, error) {
|
||||||
|
first := true
|
||||||
|
return func(n int) (int, error) {
|
||||||
|
if first {
|
||||||
|
first = false
|
||||||
|
return n - 1, nil // a blank sits last in the bag → best rank
|
||||||
|
}
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// seatOneFirstMove is a first-move-draw entropy factory that elects the second contender (in
|
||||||
|
// auto-match, the synthetic opponent) as the leader, so the caller is seated at seat 1: the
|
||||||
|
// first contender draws the first remaining tile and the second draws a blank, winning.
|
||||||
|
func seatOneFirstMove() func(n int) (int, error) {
|
||||||
|
pick := 0
|
||||||
|
return func(n int) (int, error) {
|
||||||
|
i := 0
|
||||||
|
if pick == 1 {
|
||||||
|
i = n - 1 // the second contender draws a blank → best rank
|
||||||
|
}
|
||||||
|
pick++
|
||||||
|
return i, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// newSocialService builds a social service over the shared pool, reading game
|
// newSocialService builds a social service over the shared pool, reading game
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestListForLobbyDropsLeftAIGames covers the lobby filter (game.Service.ListForLobby): a
|
||||||
|
// finished honest-AI game the player left — by resigning or by abandoning to the inactivity
|
||||||
|
// timeout — drops out of the lobby list, while it stays in ListForAccount so the admin console
|
||||||
|
// and the account-merge count keep the full set. A normally finished AI game, an active AI game
|
||||||
|
// and a left human game all stay in the lobby. The drop is a game property, not a per-resigner
|
||||||
|
// one, so it leaves every seat's lobby.
|
||||||
|
func TestListForLobbyDropsLeftAIGames(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
|
||||||
|
createAI := func(t *testing.T) (uuid.UUID, []uuid.UUID) {
|
||||||
|
t.Helper()
|
||||||
|
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: seats, TurnTimeout: time.Hour, Seed: 1, VsAI: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create AI game: %v", err)
|
||||||
|
}
|
||||||
|
return g.ID, seats
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("resign dropped from lobby, kept in account list", func(t *testing.T) {
|
||||||
|
gid, seats := createAI(t)
|
||||||
|
me := seats[0]
|
||||||
|
res, err := svc.Resign(ctx, gid, me)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resign: %v", err)
|
||||||
|
}
|
||||||
|
if res.Game.EndReason != "resign" {
|
||||||
|
t.Fatalf("end reason = %q, want resign", res.Game.EndReason)
|
||||||
|
}
|
||||||
|
if lobbyHas(t, svc, me, gid) {
|
||||||
|
t.Error("resigned AI game still in the lobby list")
|
||||||
|
}
|
||||||
|
if !containsGame(t, svc, me, gid) {
|
||||||
|
t.Error("resigned AI game missing from the full account list (the row must stay)")
|
||||||
|
}
|
||||||
|
if lobbyHas(t, svc, seats[1], gid) {
|
||||||
|
t.Error("resigned AI game still in the opponent's lobby list (drop is per-game)")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("timeout dropped from lobby", func(t *testing.T) {
|
||||||
|
gid, seats := createAI(t)
|
||||||
|
me := seats[0] // seat 0 is to move and will be timed out
|
||||||
|
// Disable the away window so the sweep is deterministic regardless of wall clock.
|
||||||
|
setAway(t, me, "UTC", "00:00", "00:00")
|
||||||
|
backdate(t, gid, time.Now().UTC().Add(-(game.AIInactivityTimeout + 2*time.Hour)))
|
||||||
|
if n, err := svc.SweepTimeouts(ctx, time.Now().UTC()); err != nil || n < 1 {
|
||||||
|
t.Fatalf("sweep swept %d (err %v), want >= 1", n, err)
|
||||||
|
}
|
||||||
|
if status, reason := gameStatus(t, svc, gid); status != game.StatusFinished || reason != "timeout" {
|
||||||
|
t.Fatalf("game not timed out: status %q reason %q", status, reason)
|
||||||
|
}
|
||||||
|
if lobbyHas(t, svc, me, gid) {
|
||||||
|
t.Error("abandoned (timed-out) AI game still in the lobby list")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("active AI game stays in lobby", func(t *testing.T) {
|
||||||
|
gid, seats := createAI(t)
|
||||||
|
if !lobbyHas(t, svc, seats[0], gid) {
|
||||||
|
t.Error("active AI game missing from the lobby list")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("normally finished AI game stays in lobby", func(t *testing.T) {
|
||||||
|
gid, seats := createAI(t)
|
||||||
|
var fin game.MoveResult
|
||||||
|
for i := 0; i < 8; i++ { // six consecutive passes end the game scoreless
|
||||||
|
r, err := svc.Pass(ctx, gid, seats[i%2])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pass %d: %v", i, err)
|
||||||
|
}
|
||||||
|
fin = r
|
||||||
|
if r.Game.Status == game.StatusFinished {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fin.Game.Status != game.StatusFinished || fin.Game.EndReason != "scoreless" {
|
||||||
|
t.Fatalf("AI game not scoreless-finished: status %q reason %q", fin.Game.Status, fin.Game.EndReason)
|
||||||
|
}
|
||||||
|
if !lobbyHas(t, svc, seats[0], gid) {
|
||||||
|
t.Error("normally finished AI game must stay in the lobby list")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("left human game stays in lobby", func(t *testing.T) {
|
||||||
|
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: seats, TurnTimeout: 24 * time.Hour, Seed: 1,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create human game: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Resign(ctx, g.ID, seats[0]); err != nil {
|
||||||
|
t.Fatalf("resign: %v", err)
|
||||||
|
}
|
||||||
|
if !lobbyHas(t, svc, seats[0], g.ID) {
|
||||||
|
t.Error("resigned human game must stay in the lobby list (only AI games are dropped)")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// lobbyHas reports whether the account's own lobby list (ListForLobby) includes gameID.
|
||||||
|
func lobbyHas(t *testing.T, svc *game.Service, accountID, gameID uuid.UUID) bool {
|
||||||
|
t.Helper()
|
||||||
|
games, err := svc.ListForLobby(context.Background(), accountID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list for lobby: %v", err)
|
||||||
|
}
|
||||||
|
for _, g := range games {
|
||||||
|
if g.ID == gameID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -74,9 +74,11 @@ func TestMatchmakingOpensThenJoins(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMatchmakingReEnqueueReturnsOwnOpenGame checks a re-enqueue is idempotent: the
|
// TestMatchmakingReEnqueueOpensNewGame checks a re-enqueue opens a fresh open game
|
||||||
// caller gets their existing open game rather than a second one.
|
// rather than returning the caller's existing one: tapping "random opponent" again while
|
||||||
func TestMatchmakingReEnqueueReturnsOwnOpenGame(t *testing.T) {
|
// still waiting starts a new search instead of bouncing the player back into the pending
|
||||||
|
// game. Both games stay open until an opponent (a human or the reaper's robot) joins each.
|
||||||
|
func TestMatchmakingReEnqueueOpensNewGame(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
clearOpenGames(t)
|
clearOpenGames(t)
|
||||||
mm := newMatchmaker(t, newRobotService(t, newGameService()), 90*time.Second, 90*time.Second)
|
mm := newMatchmaker(t, newRobotService(t, newGameService()), 90*time.Second, 90*time.Second)
|
||||||
@@ -90,8 +92,13 @@ func TestMatchmakingReEnqueueReturnsOwnOpenGame(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("re-enqueue: %v", err)
|
t.Fatalf("re-enqueue: %v", err)
|
||||||
}
|
}
|
||||||
if r2.Game.ID != r1.Game.ID || r2.Matched {
|
if r2.Matched || r2.Game.ID == r1.Game.ID {
|
||||||
t.Fatalf("re-enqueue = (game %s, matched %v), want the same open game %s unmatched", r2.Game.ID, r2.Matched, r1.Game.ID)
|
t.Fatalf("re-enqueue = (game %s, matched %v), want a new open game distinct from %s, unmatched", r2.Game.ID, r2.Matched, r1.Game.ID)
|
||||||
|
}
|
||||||
|
for _, g := range []uuid.UUID{r1.Game.ID, r2.Game.ID} {
|
||||||
|
if _, _, status, err := newGameService().Participants(ctx, g); err != nil || status != "open" {
|
||||||
|
t.Fatalf("game %s status = %q err %v, want open", g, status, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,14 +198,36 @@ func TestInvitationLazyExpiry(t *testing.T) {
|
|||||||
func TestInvitationBlockedInvitee(t *testing.T) {
|
func TestInvitationBlockedInvitee(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
svc := newInvitationService()
|
svc := newInvitationService()
|
||||||
social := newSocialService()
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
soc := newSocialService()
|
||||||
|
|
||||||
|
// The inviter has blocked an invitee: the invitation is refused outright (the inviter is aware).
|
||||||
inviter := provisionAccount(t)
|
inviter := provisionAccount(t)
|
||||||
invitee := provisionAccount(t)
|
blockedInvitee := provisionAccount(t)
|
||||||
if err := social.Block(ctx, invitee, inviter); err != nil {
|
if err := soc.Block(ctx, inviter, blockedInvitee); err != nil {
|
||||||
t.Fatalf("block: %v", err)
|
t.Fatalf("block: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := svc.CreateInvitation(ctx, inviter, []uuid.UUID{invitee}, englishInvite()); !errors.Is(err, lobby.ErrInvitationBlocked) {
|
if _, err := svc.CreateInvitation(ctx, inviter, []uuid.UUID{blockedInvitee}, englishInvite()); !errors.Is(err, lobby.ErrInvitationBlocked) {
|
||||||
t.Fatalf("create blocked = %v, want ErrInvitationBlocked", err)
|
t.Fatalf("create with a blocked invitee = %v, want ErrInvitationBlocked", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An invitee who has blocked the inviter is instead suppressed: the invitation is created
|
||||||
|
// (no error — the inviter notices nothing), but that invitee is never notified and never
|
||||||
|
// sees it in their list.
|
||||||
|
inviter2 := provisionAccount(t)
|
||||||
|
suppressed := provisionAccount(t)
|
||||||
|
if err := soc.Block(ctx, suppressed, inviter2); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.CreateInvitation(ctx, inviter2, []uuid.UUID{suppressed}, englishInvite()); err != nil {
|
||||||
|
t.Fatalf("create with a suppressing invitee = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if pub.notified(suppressed, notify.NotifyInvitation) {
|
||||||
|
t.Error("an invitee who blocked the inviter must not be notified of the invitation")
|
||||||
|
}
|
||||||
|
if list, _ := svc.ListInvitations(ctx, suppressed); len(list) != 0 {
|
||||||
|
t.Errorf("suppressed invitee's invitation list = %v, want empty", list)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,34 @@ func setStats(t *testing.T, id uuid.UUID, w, l, d, mg, mw int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setStatsCounts(t *testing.T, id uuid.UUID, moves, hints int) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := testDB.ExecContext(context.Background(),
|
||||||
|
`UPDATE backend.account_stats SET moves=$2, hints_used=$3 WHERE account_id=$1`, id, moves, hints); err != nil {
|
||||||
|
t.Fatalf("set stats counts: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setBestMove(t *testing.T, id uuid.UUID, variant string, score int) {
|
||||||
|
t.Helper()
|
||||||
|
tiles := `[{"letter":"c","value":3,"blank":false}]`
|
||||||
|
if _, err := testDB.ExecContext(context.Background(),
|
||||||
|
`INSERT INTO backend.account_best_move (account_id, variant, score, tiles) VALUES ($1,$2,$3,$4)
|
||||||
|
ON CONFLICT (account_id, variant) DO UPDATE SET score=$3, tiles=$4`, id, variant, score, tiles); err != nil {
|
||||||
|
t.Fatalf("set best move: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bestMoveCount(t *testing.T, id uuid.UUID) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := testDB.QueryRowContext(context.Background(),
|
||||||
|
`SELECT count(*) FROM backend.account_best_move WHERE account_id=$1`, id).Scan(&n); err != nil {
|
||||||
|
t.Fatalf("best move count: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
func setWallet(t *testing.T, id uuid.UUID, hints int, paid bool) {
|
func setWallet(t *testing.T, id uuid.UUID, hints int, paid bool) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
if _, err := testDB.ExecContext(context.Background(),
|
if _, err := testDB.ExecContext(context.Background(),
|
||||||
@@ -110,8 +138,15 @@ func TestAccountMergeCore(t *testing.T) {
|
|||||||
|
|
||||||
setStats(t, primary, 1, 0, 0, 100, 90)
|
setStats(t, primary, 1, 0, 0, 100, 90)
|
||||||
setStats(t, secondary, 3, 1, 2, 400, 80)
|
setStats(t, secondary, 3, 1, 2, 400, 80)
|
||||||
|
setStatsCounts(t, primary, 100, 5)
|
||||||
|
setStatsCounts(t, secondary, 50, 8)
|
||||||
setWallet(t, primary, 2, false)
|
setWallet(t, primary, 2, false)
|
||||||
setWallet(t, secondary, 5, true)
|
setWallet(t, secondary, 5, true)
|
||||||
|
// Best moves: secondary's scrabble_en (80) beats primary's (50) and is kept; secondary's
|
||||||
|
// scrabble_ru (30) is new to primary and carried over.
|
||||||
|
setBestMove(t, primary, "scrabble_en", 50)
|
||||||
|
setBestMove(t, secondary, "scrabble_en", 80)
|
||||||
|
setBestMove(t, secondary, "scrabble_ru", 30)
|
||||||
|
|
||||||
email := "merge-" + uuid.NewString() + "@example.com"
|
email := "merge-" + uuid.NewString() + "@example.com"
|
||||||
bindEmailIdentity(t, secondary, email)
|
bindEmailIdentity(t, secondary, email)
|
||||||
@@ -153,6 +188,26 @@ func TestAccountMergeCore(t *testing.T) {
|
|||||||
if mergedInto(t, secondary) != primary {
|
if mergedInto(t, secondary) != primary {
|
||||||
t.Errorf("secondary.merged_into = %s, want primary %s", mergedInto(t, secondary), primary)
|
t.Errorf("secondary.merged_into = %s, want primary %s", mergedInto(t, secondary), primary)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The moves/hints counters sum, and the per-variant best moves merge (the higher score
|
||||||
|
// per variant kept), with the secondary's best-move rows cleaned up.
|
||||||
|
st, err := store.GetStats(ctx, primary)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get merged stats: %v", err)
|
||||||
|
}
|
||||||
|
if st.Moves != 150 || st.HintsUsed != 13 {
|
||||||
|
t.Errorf("primary moves/hints = %d/%d, want 150/13", st.Moves, st.HintsUsed)
|
||||||
|
}
|
||||||
|
best := map[string]int{}
|
||||||
|
for _, b := range st.BestMoves {
|
||||||
|
best[b.Variant] = b.Score
|
||||||
|
}
|
||||||
|
if len(st.BestMoves) != 2 || best["scrabble_en"] != 80 || best["scrabble_ru"] != 30 {
|
||||||
|
t.Errorf("primary best moves = %+v, want scrabble_en:80 + scrabble_ru:30", st.BestMoves)
|
||||||
|
}
|
||||||
|
if bestMoveCount(t, secondary) != 0 {
|
||||||
|
t.Error("secondary best-move rows should be deleted after merge")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAccountMergeActiveGameConflict refuses a merge when the two share an active
|
// TestAccountMergeActiveGameConflict refuses a merge when the two share an active
|
||||||
|
|||||||
@@ -18,8 +18,9 @@ import (
|
|||||||
// The open-game suite covers an auto-match game that a player enters immediately and
|
// The open-game suite covers an auto-match game that a player enters immediately and
|
||||||
// waits inside (status 'open', the opponent seat empty) until a human or a robot joins.
|
// waits inside (status 'open', the opponent seat empty) until a human or a robot joins.
|
||||||
|
|
||||||
// evenOpeningSeed returns an even seed (so OpenOrJoin seats the starter at seat 0, which
|
// evenOpeningSeed returns a seed whose fresh two-player English opening rack (seat 0) has a
|
||||||
// moves first) whose fresh two-player English opening rack has a legal move.
|
// legal move, for tests that drive or attempt an opening play. It scans even seeds; seat
|
||||||
|
// order no longer depends on the seed — the first-move draw decides it (docs/ARCHITECTURE.md §6).
|
||||||
func evenOpeningSeed(t *testing.T) int64 {
|
func evenOpeningSeed(t *testing.T) int64 {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
for seed := int64(2); seed <= 400; seed += 2 {
|
for seed := int64(2); seed <= 400; seed += 2 {
|
||||||
@@ -49,7 +50,7 @@ func openParams(seed int64) game.CreateParams {
|
|||||||
|
|
||||||
func openGame(t *testing.T, svc *game.Service, starter uuid.UUID, seed int64) game.Game {
|
func openGame(t *testing.T, svc *game.Service, starter uuid.UUID, seed int64) game.Game {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
g, joined, err := svc.OpenOrJoin(context.Background(), starter, openParams(seed), time.Now().Add(time.Minute))
|
g, joined, err := svc.OpenOrJoin(context.Background(), starter, openParams(seed), time.Now().Add(time.Minute), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("open game: %v", err)
|
t.Fatalf("open game: %v", err)
|
||||||
}
|
}
|
||||||
@@ -59,9 +60,9 @@ func openGame(t *testing.T, svc *game.Service, starter uuid.UUID, seed int64) ga
|
|||||||
return g
|
return g
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenGameStarterMovesThenWaits checks the starter (seat 0) may move on their turn
|
// TestOpenGameStarterMovesThenWaits checks the starter may move on their turn while the game
|
||||||
// while the game is open, after which it is the empty opponent seat's turn and the
|
// is open (the first-move draw, run when the game opened, put them at seat 0), after which it
|
||||||
// starter just waits.
|
// is the empty opponent seat's turn and the starter just waits.
|
||||||
func TestOpenGameStarterMovesThenWaits(t *testing.T) {
|
func TestOpenGameStarterMovesThenWaits(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
clearOpenGames(t)
|
clearOpenGames(t)
|
||||||
@@ -89,28 +90,30 @@ func TestOpenGameStarterMovesThenWaits(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenGameStarterWaitsWhenOpponentMovesFirst checks that when the starter is seated
|
// TestOpenGameStarterWaitsWhenOpponentMovesFirst checks that when the first-move draw seats
|
||||||
// at seat 1 (odd seed), the still-empty seat 0 is to move, so the starter cannot act.
|
// the starter at seat 1 (the synthetic opponent won the open draw), the still-empty seat 0 is
|
||||||
|
// to move, so the starter cannot act until an opponent fills it.
|
||||||
func TestOpenGameStarterWaitsWhenOpponentMovesFirst(t *testing.T) {
|
func TestOpenGameStarterWaitsWhenOpponentMovesFirst(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
clearOpenGames(t)
|
clearOpenGames(t)
|
||||||
svc := newGameService()
|
svc := newGameService()
|
||||||
|
svc.SetFirstMoveEntropy(seatOneFirstMove) // the synthetic opponent wins → the caller sits at seat 1
|
||||||
starter := provisionAccount(t)
|
starter := provisionAccount(t)
|
||||||
g, _, err := svc.OpenOrJoin(ctx, starter, openParams(1), time.Now().Add(time.Minute))
|
g, _, err := svc.OpenOrJoin(ctx, starter, openParams(1), time.Now().Add(time.Minute), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("open: %v", err)
|
t.Fatalf("open: %v", err)
|
||||||
}
|
}
|
||||||
if g.ToMove != 0 || g.Seats[0].AccountID != uuid.Nil {
|
if g.ToMove != 0 || g.Seats[0].AccountID != uuid.Nil {
|
||||||
t.Fatalf("odd-seed open game: to_move %d seat0 %s, want the empty seat 0 to move", g.ToMove, g.Seats[0].AccountID)
|
t.Fatalf("opponent-won open draw: to_move %d seat0 %s, want the empty seat 0 to move", g.ToMove, g.Seats[0].AccountID)
|
||||||
}
|
}
|
||||||
if _, err := svc.Pass(ctx, g.ID, starter); !errors.Is(err, game.ErrNotYourTurn) {
|
if _, err := svc.Pass(ctx, g.ID, starter); !errors.Is(err, game.ErrNotYourTurn) {
|
||||||
t.Fatalf("starter acting on the empty seat's turn = %v, want ErrNotYourTurn", err)
|
t.Fatalf("starter acting on the empty seat's turn = %v, want ErrNotYourTurn", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestOpenGameJoinAfterStarterMoved checks a second human joins an open game even after
|
// TestOpenGameJoinAfterStarterMoved checks a second human joins an open game even after the
|
||||||
// the starter has already made their first move, landing on the board mid-opening and
|
// starter has already made their first move: the seats were fixed by the draw at open, so the
|
||||||
// able to act on their turn.
|
// joiner takes the empty seat without disturbing the journal, and can act on their turn.
|
||||||
func TestOpenGameJoinAfterStarterMoved(t *testing.T) {
|
func TestOpenGameJoinAfterStarterMoved(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
clearOpenGames(t)
|
clearOpenGames(t)
|
||||||
@@ -128,7 +131,7 @@ func TestOpenGameJoinAfterStarterMoved(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
joiner := provisionAccount(t)
|
joiner := provisionAccount(t)
|
||||||
g2, joined, err := svc.OpenOrJoin(ctx, joiner, openParams(0), time.Now().Add(time.Minute))
|
g2, joined, err := svc.OpenOrJoin(ctx, joiner, openParams(0), time.Now().Add(time.Minute), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("join: %v", err)
|
t.Fatalf("join: %v", err)
|
||||||
}
|
}
|
||||||
@@ -161,11 +164,11 @@ func TestOpenGameResignRejectedUntilOpponent(t *testing.T) {
|
|||||||
t.Fatalf("resign while open = %v, want ErrNoOpponentYet", err)
|
t.Fatalf("resign while open = %v, want ErrNoOpponentYet", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
robotID, err := robots.Pick(engine.VariantEnglish)
|
robotID, name, err := robots.PickNamed(engine.VariantEnglish)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("pick: %v", err)
|
t.Fatalf("pick: %v", err)
|
||||||
}
|
}
|
||||||
if _, attached, err := svc.AttachRobot(ctx, g.ID, robotID); err != nil || !attached {
|
if _, attached, err := svc.AttachRobot(ctx, g.ID, robotID, name); err != nil || !attached {
|
||||||
t.Fatalf("attach robot = (attached %v, err %v), want attached", attached, err)
|
t.Fatalf("attach robot = (attached %v, err %v), want attached", attached, err)
|
||||||
}
|
}
|
||||||
res, err := svc.Resign(ctx, g.ID, starter)
|
res, err := svc.Resign(ctx, g.ID, starter)
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestRobotFriendRequestIsPerGameAndReaped checks that sending a friend request to a
|
||||||
|
// disguised-robot opponent is recorded per-game in robot_friend_requests — never in the
|
||||||
|
// friendships table or against the shared robot account — that a re-send is idempotent, and
|
||||||
|
// that the reaper deletes the row once its game has been finished past the retention window
|
||||||
|
// while keeping the row for an active game.
|
||||||
|
func TestRobotFriendRequestIsPerGameAndReaped(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
accs := account.NewStore(testDB)
|
||||||
|
human := provisionAccount(t)
|
||||||
|
robot, err := accs.ProvisionRobot(ctx, "robot-friend-"+uuid.NewString(), "Robbie")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision robot: %v", err)
|
||||||
|
}
|
||||||
|
g, err := newGameService().Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robot.ID},
|
||||||
|
TurnTimeout: 24 * time.Hour, Seed: openingSeed(t),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create game: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.RequestInGame(ctx, human, robot.ID, g.ID); err != nil {
|
||||||
|
t.Fatalf("request robot: %v", err)
|
||||||
|
}
|
||||||
|
rfr, err := svc.ListRobotFriendRequests(ctx, human)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list robot friend requests: %v", err)
|
||||||
|
}
|
||||||
|
if len(rfr) != 1 || rfr[0].GameID != g.ID || rfr[0].Seat != 1 {
|
||||||
|
t.Fatalf("robot friend requests = %v, want one for game %s seat 1", rfr, g.ID)
|
||||||
|
}
|
||||||
|
// The friendships table must stay empty: no outgoing request against the shared robot account.
|
||||||
|
if out, _ := svc.ListOutgoingRequests(ctx, human); len(out) != 0 {
|
||||||
|
t.Errorf("friendships outgoing must be empty for a robot request, got %v", out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A re-send to the same game+seat is idempotent (the UNIQUE constraint collapses it).
|
||||||
|
if err := svc.RequestInGame(ctx, human, robot.ID, g.ID); err != nil {
|
||||||
|
t.Fatalf("re-request robot: %v", err)
|
||||||
|
}
|
||||||
|
if rfr, _ := svc.ListRobotFriendRequests(ctx, human); len(rfr) != 1 {
|
||||||
|
t.Fatalf("re-request must not duplicate, got %v", rfr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// While the game is active the reaper keeps the row.
|
||||||
|
if n, err := svc.ReapExpiredRobotFriendRequests(ctx); err != nil || n != 0 {
|
||||||
|
t.Fatalf("reap on active game = (%d, %v), want (0, nil)", n, err)
|
||||||
|
}
|
||||||
|
if rfr, _ := svc.ListRobotFriendRequests(ctx, human); len(rfr) != 1 {
|
||||||
|
t.Fatalf("active-game request must survive the reaper, got %v", rfr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finish the game well past the retention window: the reaper now deletes the row.
|
||||||
|
finished := time.Now().UTC().Add(-8 * 24 * time.Hour)
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.games SET status='finished', finished_at=$1 WHERE game_id=$2`, finished, g.ID); err != nil {
|
||||||
|
t.Fatalf("finish game: %v", err)
|
||||||
|
}
|
||||||
|
if n, err := svc.ReapExpiredRobotFriendRequests(ctx); err != nil || n != 1 {
|
||||||
|
t.Fatalf("reap on long-finished game = (%d, %v), want (1, nil)", n, err)
|
||||||
|
}
|
||||||
|
if rfr, _ := svc.ListRobotFriendRequests(ctx, human); len(rfr) != 0 {
|
||||||
|
t.Errorf("long-finished request not reaped: %v", rfr)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -181,8 +181,8 @@ func TestMatchmakerSubstitutesRobotEndToEnd(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRobotProactiveNudge checks the robot's lengthening proactive-nudge schedule on the
|
// TestRobotProactiveNudge checks the robot's flat proactive-nudge schedule on the human's
|
||||||
// human's turn: nothing before the ~60-90 min first gap, exactly one once it has elapsed.
|
// turn: nothing before the 9 h floor of the 9-12 h gap, exactly one once past its 12 h ceiling.
|
||||||
func TestRobotProactiveNudge(t *testing.T) {
|
func TestRobotProactiveNudge(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
svc := newGameService()
|
svc := newGameService()
|
||||||
@@ -206,18 +206,20 @@ func TestRobotProactiveNudge(t *testing.T) {
|
|||||||
t.Fatalf("create: %v", err)
|
t.Fatalf("create: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// A daytime turn start (the robot is awake for every ±3h drift between 07:30 and 12:00). No
|
// A noon turn start. The drive instants below sit at UTC hours 20:00 and (next day) 12:00,
|
||||||
// nudge before the 60-min floor of the first gap; exactly one once past its 90-min ceiling.
|
// both in [10:00, 20:00] so the robot is awake for every ±3h sleep drift — the gap, not the
|
||||||
start := time.Date(2024, 1, 1, 10, 0, 0, 0, time.UTC)
|
// sleep window, decides the outcome. No nudge at 8 h idle (before the 9 h floor); exactly one
|
||||||
|
// at 24 h idle (well past the 12 h ceiling, however the seed drew within 9-12 h).
|
||||||
|
start := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||||
setTurnStarted(t, g.ID, start)
|
setTurnStarted(t, g.ID, start)
|
||||||
|
|
||||||
robots.Drive(ctx, start.Add(30*time.Minute))
|
robots.Drive(ctx, start.Add(8*time.Hour))
|
||||||
if n := countNudges(t, g.ID, robotID); n != 0 {
|
if n := countNudges(t, g.ID, robotID); n != 0 {
|
||||||
t.Errorf("robot nudges = %d at 30m idle, want 0 (before the first gap)", n)
|
t.Errorf("robot nudges = %d at 8h idle, want 0 (before the 9h floor)", n)
|
||||||
}
|
}
|
||||||
robots.Drive(ctx, start.Add(2*time.Hour))
|
robots.Drive(ctx, start.Add(24*time.Hour))
|
||||||
if n := countNudges(t, g.ID, robotID); n != 1 {
|
if n := countNudges(t, g.ID, robotID); n != 1 {
|
||||||
t.Errorf("robot nudges = %d at 2h idle, want 1 (after the first gap)", n)
|
t.Errorf("robot nudges = %d at 24h idle, want 1 (past the 12h ceiling)", n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,3 +251,124 @@ func playHuman(t *testing.T, ctx context.Context, svc *game.Service, gameID, hum
|
|||||||
t.Fatalf("human pass: %v", err)
|
t.Fatalf("human pass: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// countMoves returns the number of committed moves in a game's journal.
|
||||||
|
func countMoves(t *testing.T, gameID uuid.UUID) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := testDB.QueryRowContext(context.Background(),
|
||||||
|
`SELECT count(*) FROM backend.game_moves WHERE game_id = $1`, gameID).Scan(&n); err != nil {
|
||||||
|
t.Fatalf("count moves: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// setLastTwoMoveTimes rewrites the created_at of a game's two most recent journal entries
|
||||||
|
// so the endgame think-time anchor (their gap, the human's last-move think time) is a known
|
||||||
|
// value, independent of the millisecond spacing of the manufactured passes.
|
||||||
|
func setLastTwoMoveTimes(t *testing.T, gameID uuid.UUID, prevAt, lastAt time.Time) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.game_moves SET created_at = $2
|
||||||
|
WHERE game_id = $1 AND seq = (SELECT max(seq) FROM backend.game_moves WHERE game_id = $1)`,
|
||||||
|
gameID, lastAt); err != nil {
|
||||||
|
t.Fatalf("set last move time: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := testDB.ExecContext(ctx,
|
||||||
|
`UPDATE backend.game_moves SET created_at = $2
|
||||||
|
WHERE game_id = $1 AND seq = (SELECT max(seq) - 1 FROM backend.game_moves WHERE game_id = $1)`,
|
||||||
|
gameID, prevAt); err != nil {
|
||||||
|
t.Fatalf("set prev move time: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRobotEndgamePassShrinksThinkTime checks the dead-drawn-endgame shrink end to end: when
|
||||||
|
// the two most recent moves are both passes, RobotTurns reports EndgamePass with the human's
|
||||||
|
// last-move think time (OppLastMove), and the driver answers on the shortened schedule — well
|
||||||
|
// before the normal late-game delay — rather than dragging out the decided game. The journal
|
||||||
|
// state is manufactured with direct passes so the test isolates the timing mechanism (the
|
||||||
|
// SQL anchor and the driver gate) from a full game to an empty bag.
|
||||||
|
func TestRobotEndgamePassShrinksThinkTime(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
robotID, err := robots.Pick(engine.VariantEnglish)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pick: %v", err)
|
||||||
|
}
|
||||||
|
human := provisionAccount(t)
|
||||||
|
seed := openingSeed(t)
|
||||||
|
|
||||||
|
g, err := svc.Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robotID},
|
||||||
|
TurnTimeout: 24 * time.Hour, Seed: seed,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create: %v", err)
|
||||||
|
}
|
||||||
|
const robotSeat = 1
|
||||||
|
store := game.NewStore(testDB)
|
||||||
|
|
||||||
|
turnOf := func(id uuid.UUID) game.RobotTurn {
|
||||||
|
t.Helper()
|
||||||
|
turns, err := store.RobotTurns(ctx, []uuid.UUID{robotID})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("robot turns: %v", err)
|
||||||
|
}
|
||||||
|
for _, rt := range turns {
|
||||||
|
if rt.GameID == id {
|
||||||
|
return rt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("no robot turn for game %s", id)
|
||||||
|
return game.RobotTurn{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One pass so far (the human): not yet a double-pass endgame.
|
||||||
|
if _, err := svc.Pass(ctx, g.ID, human); err != nil {
|
||||||
|
t.Fatalf("human pass 1: %v", err)
|
||||||
|
}
|
||||||
|
if rt := turnOf(g.ID); rt.EndgamePass {
|
||||||
|
t.Fatalf("EndgamePass after a single pass = true, want false")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Robot then human pass: the two most recent moves are now both passes and it is the
|
||||||
|
// robot's turn — the guaranteed-pass endgame state.
|
||||||
|
if _, err := svc.Pass(ctx, g.ID, robotID); err != nil {
|
||||||
|
t.Fatalf("robot pass: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.Pass(ctx, g.ID, human); err != nil {
|
||||||
|
t.Fatalf("human pass 2: %v", err)
|
||||||
|
}
|
||||||
|
if _, toMove, _, err := svc.Participants(ctx, g.ID); err != nil || toMove != robotSeat {
|
||||||
|
t.Fatalf("after two passes: toMove %d err %v, want robot seat %d", toMove, err, robotSeat)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anchor the human's last-move think time to 60s and start the robot's turn at daytime.
|
||||||
|
setLastTwoMoveTimes(t, g.ID, daytime.Add(-60*time.Second), daytime)
|
||||||
|
setTurnStarted(t, g.ID, daytime)
|
||||||
|
|
||||||
|
rt := turnOf(g.ID)
|
||||||
|
if !rt.EndgamePass {
|
||||||
|
t.Fatalf("EndgamePass after a double pass = false, want true")
|
||||||
|
}
|
||||||
|
if d := rt.OppLastMove; d < 59*time.Second || d > 61*time.Second {
|
||||||
|
t.Fatalf("OppLastMove = %s, want ~60s", d)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The normal schedule for this move is at least the early band floor (~3.75 min); the
|
||||||
|
// 60s-anchored endgame delay is at most 90s for every seed. Driving at +150s is past the
|
||||||
|
// shrunk delay but well before the normal one, so the robot acts only because of the shrink.
|
||||||
|
before := countMoves(t, g.ID)
|
||||||
|
robots.Drive(ctx, daytime.Add(150*time.Second))
|
||||||
|
if after := countMoves(t, g.ID); after != before+1 {
|
||||||
|
t.Fatalf("robot did not act on the shrunk endgame schedule: moves %d → %d (want +1)", before, after)
|
||||||
|
}
|
||||||
|
if _, toMove, _, err := svc.Participants(ctx, g.ID); err != nil || toMove == robotSeat {
|
||||||
|
t.Fatalf("after the shrunk move: still the robot's turn (toMove %d, err %v)", toMove, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/engine"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The seat display-name snapshot freezes the name an opponent sees for the life of a
|
||||||
|
// game (a later rename no longer rewrites past games) and lets a disguised robot carry a
|
||||||
|
// fresh per-game name (docs/ARCHITECTURE.md §7).
|
||||||
|
|
||||||
|
// seatByAccount returns the seat held by id and whether it was found.
|
||||||
|
func seatByAccount(g game.Game, id uuid.UUID) (game.Seat, bool) {
|
||||||
|
for _, s := range g.Seats {
|
||||||
|
if s.AccountID == id {
|
||||||
|
return s, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return game.Seat{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSeatNameFrozenAfterRename checks a human seat captures the player's display name
|
||||||
|
// when the seat is taken and keeps it after the account is later renamed.
|
||||||
|
func TestSeatNameFrozenAfterRename(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
svc := newGameService()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
|
||||||
|
starter := provisionAccount(t)
|
||||||
|
if _, err := accounts.UpdateProfile(ctx, starter, account.ProfileUpdate{
|
||||||
|
DisplayName: "Original Name", PreferredLanguage: "en", TimeZone: "UTC", VariantPreferences: []string{"erudit_ru"},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("set name: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
g := openGame(t, svc, starter, evenOpeningSeed(t))
|
||||||
|
seat, ok := seatByAccount(g, starter)
|
||||||
|
if !ok || seat.DisplayName != "Original Name" {
|
||||||
|
t.Fatalf("opened seat snapshot = %q (found %v), want %q", seat.DisplayName, ok, "Original Name")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename the account; the snapshot on the already-taken seat must not follow.
|
||||||
|
if _, err := accounts.UpdateProfile(ctx, starter, account.ProfileUpdate{
|
||||||
|
DisplayName: "Renamed Player99", PreferredLanguage: "en", TimeZone: "UTC", VariantPreferences: []string{"erudit_ru"},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("rename: %v", err)
|
||||||
|
}
|
||||||
|
reloaded, err := svc.GameByID(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload game: %v", err)
|
||||||
|
}
|
||||||
|
got, _ := seatByAccount(reloaded, starter)
|
||||||
|
if got.DisplayName != "Original Name" {
|
||||||
|
t.Errorf("seat snapshot after rename = %q, want it frozen at %q", got.DisplayName, "Original Name")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRobotSeatGetsComposedName checks the disguised auto-match robot's seat stores the
|
||||||
|
// fresh per-game name composed at attach time (PickNamed -> AttachRobot -> seat), and
|
||||||
|
// that the name is a valid human display name so the robot stays indistinguishable.
|
||||||
|
func TestRobotSeatGetsComposedName(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clearOpenGames(t)
|
||||||
|
svc := newGameService()
|
||||||
|
robots := newRobotService(t, svc)
|
||||||
|
if err := robots.EnsurePool(ctx); err != nil {
|
||||||
|
t.Fatalf("ensure pool: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
g := openGame(t, svc, provisionAccount(t), evenOpeningSeed(t))
|
||||||
|
robotID, name, err := robots.PickNamed(engine.VariantEnglish)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pick named: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := account.ValidateDisplayName(name); err != nil {
|
||||||
|
t.Fatalf("composed robot name %q is not a valid display name: %v", name, err)
|
||||||
|
}
|
||||||
|
if _, attached, err := svc.AttachRobot(ctx, g.ID, robotID, name); err != nil || !attached {
|
||||||
|
t.Fatalf("attach robot = (attached %v, err %v), want attached", attached, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
reloaded, err := svc.GameByID(ctx, g.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload game: %v", err)
|
||||||
|
}
|
||||||
|
seat, ok := seatByAccount(reloaded, robotID)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("robot seat not found after attach")
|
||||||
|
}
|
||||||
|
if seat.DisplayName != name {
|
||||||
|
t.Errorf("robot seat snapshot = %q, want the composed per-game name %q", seat.DisplayName, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,20 @@ func (c *capturePublisher) notified(user uuid.UUID, sub string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// delivered reports whether an intent of the given top-level kind (e.g. chat_message,
|
||||||
|
// nudge) was published to user — used to assert that a blocked sender's message or nudge
|
||||||
|
// never reaches the blocker.
|
||||||
|
func (c *capturePublisher) delivered(user uuid.UUID, kind string) bool {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
for _, in := range c.intents {
|
||||||
|
if in.UserID == user && in.Kind == kind {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// TestFriendRequestToRobotStaysPending checks a friend request to a robot is accepted as
|
// TestFriendRequestToRobotStaysPending checks a friend request to a robot is accepted as
|
||||||
// pending rather than blocked: robots no longer block friend requests, so the request
|
// pending rather than blocked: robots no longer block friend requests, so the request
|
||||||
// just sits unanswered and later expires — mirroring a human who ignores it.
|
// just sits unanswered and later expires — mirroring a human who ignores it.
|
||||||
@@ -121,24 +135,60 @@ func TestFriendRequestRefusedByToggleAndBlock(t *testing.T) {
|
|||||||
|
|
||||||
// Toggle: the addressee does not accept friend requests.
|
// Toggle: the addressee does not accept friend requests.
|
||||||
a, b := provisionAccount(t), provisionAccount(t)
|
a, b := provisionAccount(t), provisionAccount(t)
|
||||||
if _, err := store.UpdateProfile(ctx, b, account.ProfileUpdate{DisplayName: "Player", PreferredLanguage: "en", TimeZone: "UTC", BlockFriendRequests: true}); err != nil {
|
if _, err := store.UpdateProfile(ctx, b, account.ProfileUpdate{DisplayName: "Player", PreferredLanguage: "en", TimeZone: "UTC", BlockFriendRequests: true, VariantPreferences: []string{"erudit_ru"}}); err != nil {
|
||||||
t.Fatalf("set toggle: %v", err)
|
t.Fatalf("set toggle: %v", err)
|
||||||
}
|
}
|
||||||
if err := svc.SendFriendRequest(ctx, a, b); !errors.Is(err, social.ErrRequestBlocked) {
|
if err := svc.SendFriendRequest(ctx, a, b); !errors.Is(err, social.ErrRequestBlocked) {
|
||||||
t.Fatalf("toggle send = %v, want ErrRequestBlocked", err)
|
t.Fatalf("toggle send = %v, want ErrRequestBlocked", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Block: the addressee has blocked the requester.
|
// Block from the requester's own side: a requester who has blocked the addressee is
|
||||||
c, d := provisionAccount(t), provisionAccount(t)
|
// refused outright (they are the blocker and aware of it). The reverse direction — the
|
||||||
if err := svc.Block(ctx, d, c); err != nil {
|
// addressee having blocked the requester — is instead silently suppressed, covered by
|
||||||
|
// TestFriendRequestFromBlockedIsSuppressed.
|
||||||
|
_, seats := newGameWithSeats(t, 2)
|
||||||
|
c, d := seats[0], seats[1]
|
||||||
|
if err := svc.Block(ctx, c, d); err != nil {
|
||||||
t.Fatalf("block: %v", err)
|
t.Fatalf("block: %v", err)
|
||||||
}
|
}
|
||||||
if err := svc.SendFriendRequest(ctx, c, d); !errors.Is(err, social.ErrRequestBlocked) {
|
if err := svc.SendFriendRequest(ctx, c, d); !errors.Is(err, social.ErrRequestBlocked) {
|
||||||
t.Fatalf("blocked send = %v, want ErrRequestBlocked", err)
|
t.Fatalf("blocker's own request = %v, want ErrRequestBlocked", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBlockSeversFriendship(t *testing.T) {
|
// TestFriendRequestFromBlockedIsSuppressed checks the store-but-hide path: when the
|
||||||
|
// addressee has blocked the requester, the requester's friend request succeeds silently
|
||||||
|
// (no error — they must not notice the block), is stored, but is never delivered to nor
|
||||||
|
// surfaced for the blocker.
|
||||||
|
func TestFriendRequestFromBlockedIsSuppressed(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
svc := newSocialService()
|
||||||
|
pub := &capturePublisher{}
|
||||||
|
svc.SetNotifier(pub)
|
||||||
|
_, seats := newGameWithSeats(t, 2)
|
||||||
|
blocker, blocked := seats[0], seats[1]
|
||||||
|
if err := svc.Block(ctx, blocker, blocked); err != nil {
|
||||||
|
t.Fatalf("block: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.SendFriendRequest(ctx, blocked, blocker); err != nil {
|
||||||
|
t.Fatalf("suppressed request = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if pub.notified(blocker, notify.NotifyFriendRequest) {
|
||||||
|
t.Error("blocker must not be notified of a suppressed request")
|
||||||
|
}
|
||||||
|
if got, _ := svc.ListIncomingRequests(ctx, blocker); len(got) != 0 {
|
||||||
|
t.Errorf("blocker incoming = %v, want none (suppressed)", got)
|
||||||
|
}
|
||||||
|
// The blocked user sees an ordinary outgoing request — no leak of the block.
|
||||||
|
if got, _ := svc.ListOutgoingRequests(ctx, blocked); len(got) != 1 || got[0] != blocker {
|
||||||
|
t.Errorf("blocked outgoing = %v, want [blocker]", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBlockKeepsFriendshipHiddenFromBlocker checks a block overrides but does not delete a
|
||||||
|
// friendship: the blocker stops seeing the blocked friend, the blocked user's own list is
|
||||||
|
// unchanged (so they never notice), and an unblock cleanly restores the friendship.
|
||||||
|
func TestBlockKeepsFriendshipHiddenFromBlocker(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
svc := newSocialService()
|
svc := newSocialService()
|
||||||
_, seats := newGameWithSeats(t, 2)
|
_, seats := newGameWithSeats(t, 2)
|
||||||
@@ -153,7 +203,16 @@ func TestBlockSeversFriendship(t *testing.T) {
|
|||||||
t.Fatalf("block: %v", err)
|
t.Fatalf("block: %v", err)
|
||||||
}
|
}
|
||||||
if friends, _ := svc.ListFriends(ctx, a); len(friends) != 0 {
|
if friends, _ := svc.ListFriends(ctx, a); len(friends) != 0 {
|
||||||
t.Errorf("friendship must be severed by a block, got %v", friends)
|
t.Errorf("blocker's friend list = %v, want the blocked friend hidden", friends)
|
||||||
|
}
|
||||||
|
if friends, _ := svc.ListFriends(ctx, b); len(friends) != 1 || friends[0] != a {
|
||||||
|
t.Errorf("blocked user's friend list = %v, want [blocker] unchanged", friends)
|
||||||
|
}
|
||||||
|
if err := svc.Unblock(ctx, a, b); err != nil {
|
||||||
|
t.Fatalf("unblock: %v", err)
|
||||||
|
}
|
||||||
|
if friends, _ := svc.ListFriends(ctx, a); len(friends) != 1 || friends[0] != b {
|
||||||
|
t.Errorf("after unblock, blocker's friend list = %v, want [b] restored", friends)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,7 +353,7 @@ func TestChatPostListAndBlocks(t *testing.T) {
|
|||||||
if _, err := svc.PostMessage(ctx, other, seats2[0], "hi", ""); err != nil {
|
if _, err := svc.PostMessage(ctx, other, seats2[0], "hi", ""); err != nil {
|
||||||
t.Fatalf("post 2: %v", err)
|
t.Fatalf("post 2: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := store.UpdateProfile(ctx, seats2[1], account.ProfileUpdate{DisplayName: "Player", PreferredLanguage: "en", TimeZone: "UTC", BlockChat: true}); err != nil {
|
if _, err := store.UpdateProfile(ctx, seats2[1], account.ProfileUpdate{DisplayName: "Player", PreferredLanguage: "en", TimeZone: "UTC", BlockChat: true, VariantPreferences: []string{"erudit_ru"}}); err != nil {
|
||||||
t.Fatalf("set block_chat: %v", err)
|
t.Fatalf("set block_chat: %v", err)
|
||||||
}
|
}
|
||||||
if msgs, _ := svc.Messages(ctx, other, seats2[1]); len(msgs) != 0 {
|
if msgs, _ := svc.Messages(ctx, other, seats2[1]); len(msgs) != 0 {
|
||||||
@@ -382,6 +441,33 @@ func TestNudgeRulesAndRateLimit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestSeatNameResolvesDisplayName checks game.Service.SeatName surfaces a seated account's
|
||||||
|
// display name — the identity social.Nudge voices the nudge with — and returns "" for an account
|
||||||
|
// that holds no seat (the render then falls back to the plain phrase).
|
||||||
|
func TestSeatNameResolvesDisplayName(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gsvc := newGameService()
|
||||||
|
// ProvisionRobot is the one provisioning path that stamps a known display name (a plain
|
||||||
|
// provisioned account has none), so the seat resolves to a name we can assert.
|
||||||
|
named, err := account.NewStore(testDB).ProvisionRobot(ctx, "tg-"+uuid.NewString(), "Ann")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision named account: %v", err)
|
||||||
|
}
|
||||||
|
g, err := gsvc.Create(ctx, game.CreateParams{
|
||||||
|
Variant: engine.VariantEnglish, Seats: []uuid.UUID{provisionAccount(t), named.ID},
|
||||||
|
TurnTimeout: 24 * time.Hour, Seed: openingSeed(t),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create: %v", err)
|
||||||
|
}
|
||||||
|
if got, err := gsvc.SeatName(ctx, g.ID, named.ID); err != nil || got != "Ann" {
|
||||||
|
t.Errorf("seated SeatName = (%q, %v), want (\"Ann\", nil)", got, err)
|
||||||
|
}
|
||||||
|
if got, err := gsvc.SeatName(ctx, g.ID, provisionAccount(t)); err != nil || got != "" {
|
||||||
|
t.Errorf("non-seated SeatName = (%q, %v), want (\"\", nil)", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestNudgeCooldownResetsOnAction checks the nudge cooldown clears once the player has
|
// TestNudgeCooldownResetsOnAction checks the nudge cooldown clears once the player has
|
||||||
// acted (moved or chatted) since their last nudge, even within the hour.
|
// acted (moved or chatted) since their last nudge, even within the hour.
|
||||||
func TestNudgeCooldownResetsOnAction(t *testing.T) {
|
func TestNudgeCooldownResetsOnAction(t *testing.T) {
|
||||||
@@ -502,32 +588,6 @@ func TestRespondPublishesToRequester(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestNudgeRoutedByGameLanguage checks a nudge's out-of-app push carries the game's language, so
|
|
||||||
// it is delivered by the game's bot rather than the recipient's last-login bot.
|
|
||||||
func TestNudgeRoutedByGameLanguage(t *testing.T) {
|
|
||||||
ctx := context.Background()
|
|
||||||
svc := newSocialService()
|
|
||||||
pub := &capturePublisher{}
|
|
||||||
svc.SetNotifier(pub)
|
|
||||||
|
|
||||||
gameID, seats := newGameWithSeats(t, 2) // an English game; seat 0 is to move
|
|
||||||
if _, err := svc.Nudge(ctx, gameID, seats[1]); err != nil {
|
|
||||||
t.Fatalf("nudge: %v", err)
|
|
||||||
}
|
|
||||||
found := false
|
|
||||||
for _, in := range pub.intents {
|
|
||||||
if in.Kind == notify.KindNudge {
|
|
||||||
found = true
|
|
||||||
if in.Language != "en" {
|
|
||||||
t.Errorf("nudge language = %q, want en (the game's language)", in.Language)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Fatal("no nudge intent published")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestAdminListMessages checks the admin moderation list: real messages only
|
// TestAdminListMessages checks the admin moderation list: real messages only
|
||||||
// (nudges excluded), the game / sender pins, the sender glob masks, and the source label.
|
// (nudges excluded), the game / sender pins, the sender glob masks, and the source label.
|
||||||
func TestAdminListMessages(t *testing.T) {
|
func TestAdminListMessages(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.uber.org/zap/zaptest"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/game"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestConsoleBlockAndUnblock drives the admin console block flow through HTTP: blocking a user
|
||||||
|
// records the suspension and forfeits their active game, the user card renders both branches,
|
||||||
|
// and unblocking lifts it.
|
||||||
|
func TestConsoleBlockAndUnblock(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
games := newGameService()
|
||||||
|
srv := consoleServer(t, accounts, games)
|
||||||
|
|
||||||
|
gid, seats := newGameWithSeats(t, 2)
|
||||||
|
blocked := seats[0]
|
||||||
|
|
||||||
|
// The card renders the not-blocked branch before any block.
|
||||||
|
if rec := consoleGet(t, srv, "/_gm/users/"+blocked.String()); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("user card before block = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block permanently via the console.
|
||||||
|
if rec := consolePost(t, srv, "/_gm/users/"+blocked.String()+"/block", url.Values{"duration": {"permanent"}}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("console block = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if _, ok, err := accounts.CurrentSuspension(ctx, blocked); err != nil || !ok {
|
||||||
|
t.Fatalf("after console block: blocked=%v err=%v, want blocked", ok, err)
|
||||||
|
}
|
||||||
|
if g, err := games.GameByID(ctx, gid); err != nil || g.Status != game.StatusFinished {
|
||||||
|
t.Fatalf("game after block: status=%q err=%v, want finished", g.Status, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The card renders the blocked branch.
|
||||||
|
if rec := consoleGet(t, srv, "/_gm/users/"+blocked.String()); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("user card after block = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unblock via the console.
|
||||||
|
if rec := consolePost(t, srv, "/_gm/users/"+blocked.String()+"/unblock", url.Values{}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("console unblock = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if _, ok, err := accounts.CurrentSuspension(ctx, blocked); err != nil || ok {
|
||||||
|
t.Fatalf("after console unblock: blocked=%v err=%v, want not blocked", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConsoleReasonsCRUD drives reason creation through the console and checks the page renders.
|
||||||
|
func TestConsoleReasonsCRUD(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
srv := consoleServer(t, accounts, newGameService())
|
||||||
|
|
||||||
|
if rec := consoleGet(t, srv, "/_gm/reasons"); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("reasons page = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
form := url.Values{"text_en": {"Console reason"}, "text_ru": {"Причина из консоли"}}
|
||||||
|
if rec := consolePost(t, srv, "/_gm/reasons", form); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("console create reason = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
reasons, err := accounts.ListReasons(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list reasons: %v", err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, r := range reasons {
|
||||||
|
if r.TextEn == "Console reason" && r.TextRu == "Причина из консоли" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Error("reason created via the console was not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// consoleServer assembles a server with the admin console mounted (it needs accounts, games and a
|
||||||
|
// registry).
|
||||||
|
func consoleServer(t *testing.T, accounts *account.Store, games *game.Service) *server.Server {
|
||||||
|
t.Helper()
|
||||||
|
return server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: accounts,
|
||||||
|
Games: games,
|
||||||
|
Registry: testRegistry,
|
||||||
|
DictDir: dictDir(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// consoleGet issues a console GET (a safe method, so the same-origin guard passes).
|
||||||
|
func consoleGet(t *testing.T, srv *server.Server, path string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://example.com"+path, nil))
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// consolePost issues a same-origin form POST to the console.
|
||||||
|
func consolePost(t *testing.T, srv *server.Server, path string, form url.Values) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "http://example.com"+path, strings.NewReader(form.Encode()))
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("Origin", "http://example.com")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.uber.org/zap/zaptest"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// blockStatusBody mirrors the backend's /block-status JSON for the test.
|
||||||
|
type blockStatusBody struct {
|
||||||
|
Blocked bool `json:"blocked"`
|
||||||
|
Permanent bool `json:"permanent"`
|
||||||
|
Until string `json:"until"`
|
||||||
|
Reason string `json:"reason"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionGate drives the gate end-to-end through the assembled HTTP server: a blocked
|
||||||
|
// account is refused on a normal user route with 403 + account_blocked, the block-status probe
|
||||||
|
// stays reachable and resolves the reason to the account's language, and an unblock restores
|
||||||
|
// access.
|
||||||
|
func TestSuspensionGate(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: accounts,
|
||||||
|
})
|
||||||
|
|
||||||
|
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "ru", "", "Blocked")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision: %v", err)
|
||||||
|
}
|
||||||
|
id := acc.ID
|
||||||
|
|
||||||
|
// Not blocked: a normal route passes and block-status reports false.
|
||||||
|
if rec := userGet(t, srv, "/api/v1/user/profile", id); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("profile before block = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if bs := blockStatus(t, srv, id); bs.Blocked {
|
||||||
|
t.Fatal("fresh account should not be blocked")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block permanently with a reason.
|
||||||
|
if _, err := accounts.Suspend(ctx, id, nil, "Spam", "Спам", nil); err != nil {
|
||||||
|
t.Fatalf("suspend: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A normal route is now refused with the stable code.
|
||||||
|
rec := userGet(t, srv, "/api/v1/user/profile", id)
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("profile while blocked = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
if code := errorCode(t, rec); code != "account_blocked" {
|
||||||
|
t.Fatalf("error code = %q, want account_blocked", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The block-status probe stays reachable and resolves the reason to the account's language.
|
||||||
|
bs := blockStatus(t, srv, id)
|
||||||
|
if !bs.Blocked || !bs.Permanent {
|
||||||
|
t.Fatalf("block-status = %+v, want blocked+permanent", bs)
|
||||||
|
}
|
||||||
|
if bs.Reason != "Спам" {
|
||||||
|
t.Errorf("reason = %q, want the Russian snapshot Спам", bs.Reason)
|
||||||
|
}
|
||||||
|
if bs.Until != "" {
|
||||||
|
t.Errorf("until = %q, want empty for a permanent block", bs.Until)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unblock restores access.
|
||||||
|
if err := accounts.LiftSuspension(ctx, id); err != nil {
|
||||||
|
t.Fatalf("lift: %v", err)
|
||||||
|
}
|
||||||
|
if rec := userGet(t, srv, "/api/v1/user/profile", id); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("profile after unblock = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionGateTemporaryUntil checks a temporary block reports its expiry through
|
||||||
|
// block-status as a future RFC3339 instant and not permanent.
|
||||||
|
func TestSuspensionGateTemporaryUntil(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
accounts := account.NewStore(testDB)
|
||||||
|
srv := server.New(":0", server.Deps{Logger: zaptest.NewLogger(t), DB: testDB, Accounts: accounts})
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
until := time.Now().Add(24 * time.Hour)
|
||||||
|
if _, err := accounts.Suspend(ctx, id, &until, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend: %v", err)
|
||||||
|
}
|
||||||
|
bs := blockStatus(t, srv, id)
|
||||||
|
if !bs.Blocked || bs.Permanent {
|
||||||
|
t.Fatalf("block-status = %+v, want blocked, not permanent", bs)
|
||||||
|
}
|
||||||
|
parsed, err := time.Parse(time.RFC3339, bs.Until)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("until %q is not RFC3339: %v", bs.Until, err)
|
||||||
|
}
|
||||||
|
if !parsed.After(time.Now()) {
|
||||||
|
t.Errorf("until = %v, want a future instant", parsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// userGet issues an authenticated GET (X-User-ID) against the assembled server.
|
||||||
|
func userGet(t *testing.T, srv *server.Server, path string, id uuid.UUID) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||||
|
req.Header.Set("X-User-ID", id.String())
|
||||||
|
srv.Handler().ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// blockStatus fetches and decodes the /block-status payload, asserting a 200.
|
||||||
|
func blockStatus(t *testing.T, srv *server.Server, id uuid.UUID) blockStatusBody {
|
||||||
|
t.Helper()
|
||||||
|
rec := userGet(t, srv, "/api/v1/user/block-status", id)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("block-status status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
var b blockStatusBody
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &b); err != nil {
|
||||||
|
t.Fatalf("decode block-status: %v", err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// errorCode extracts the stable code from the backend error envelope.
|
||||||
|
func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||||
|
t.Helper()
|
||||||
|
var e struct {
|
||||||
|
Error struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
} `json:"error"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &e); err != nil {
|
||||||
|
t.Fatalf("decode error envelope: %v", err)
|
||||||
|
}
|
||||||
|
return e.Error.Code
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSuspensionRoundTrip covers a permanent block: a fresh account is not blocked, Suspend with
|
||||||
|
// a reason makes CurrentSuspension report it (permanent, with the en/ru snapshot resolved per
|
||||||
|
// language), and LiftSuspension reverses it.
|
||||||
|
func TestSuspensionRoundTrip(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
store := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
if _, ok, err := store.CurrentSuspension(ctx, id); err != nil || ok {
|
||||||
|
t.Fatalf("fresh CurrentSuspension = (ok %v, err %v), want (false, nil)", ok, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := store.Suspend(ctx, id, nil, "Spam", "Спам", nil); err != nil {
|
||||||
|
t.Fatalf("suspend: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
susp, ok, err := store.CurrentSuspension(ctx, id)
|
||||||
|
if err != nil || !ok {
|
||||||
|
t.Fatalf("CurrentSuspension after suspend = (ok %v, err %v), want (true, nil)", ok, err)
|
||||||
|
}
|
||||||
|
if !susp.Permanent() {
|
||||||
|
t.Errorf("Permanent() = false, want true for a nil-until block")
|
||||||
|
}
|
||||||
|
if got := susp.LocalizedReason("en"); got != "Spam" {
|
||||||
|
t.Errorf("LocalizedReason(en) = %q, want Spam", got)
|
||||||
|
}
|
||||||
|
if got := susp.LocalizedReason("ru"); got != "Спам" {
|
||||||
|
t.Errorf("LocalizedReason(ru) = %q, want Спам", got)
|
||||||
|
}
|
||||||
|
if got := susp.LocalizedReason("fr"); got != "Spam" {
|
||||||
|
t.Errorf("LocalizedReason(fr) = %q, want the English fallback Spam", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := store.LiftSuspension(ctx, id); err != nil {
|
||||||
|
t.Fatalf("lift: %v", err)
|
||||||
|
}
|
||||||
|
if _, ok, err := store.CurrentSuspension(ctx, id); err != nil || ok {
|
||||||
|
t.Fatalf("CurrentSuspension after lift = (ok %v, err %v), want (false, nil)", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTemporarySuspensionExpiry checks the until boundary: a future expiry is in force (and not
|
||||||
|
// permanent), while a past expiry is already not in force.
|
||||||
|
func TestTemporarySuspensionExpiry(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
store := account.NewStore(testDB)
|
||||||
|
|
||||||
|
future := provisionAccount(t)
|
||||||
|
until := time.Now().Add(time.Hour)
|
||||||
|
if _, err := store.Suspend(ctx, future, &until, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend future: %v", err)
|
||||||
|
}
|
||||||
|
susp, ok, err := store.CurrentSuspension(ctx, future)
|
||||||
|
if err != nil || !ok {
|
||||||
|
t.Fatalf("future CurrentSuspension = (ok %v, err %v), want (true, nil)", ok, err)
|
||||||
|
}
|
||||||
|
if susp.Permanent() {
|
||||||
|
t.Error("Permanent() = true, want false for a dated block")
|
||||||
|
}
|
||||||
|
if susp.BlockedUntil == nil || !susp.BlockedUntil.After(time.Now()) {
|
||||||
|
t.Errorf("BlockedUntil = %v, want a future instant", susp.BlockedUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
past := provisionAccount(t)
|
||||||
|
expired := time.Now().Add(-time.Hour)
|
||||||
|
if _, err := store.Suspend(ctx, past, &expired, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend past: %v", err)
|
||||||
|
}
|
||||||
|
if _, ok, err := store.CurrentSuspension(ctx, past); err != nil || ok {
|
||||||
|
t.Fatalf("expired CurrentSuspension = (ok %v, err %v), want (false, nil)", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionStrongestWins checks that with overlapping blocks CurrentSuspension returns the
|
||||||
|
// strongest — a permanent block outranks any dated one — and that LiftSuspension clears them all.
|
||||||
|
func TestSuspensionStrongestWins(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
store := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
soon := time.Now().Add(time.Hour)
|
||||||
|
if _, err := store.Suspend(ctx, id, &soon, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend dated: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := store.Suspend(ctx, id, nil, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend permanent: %v", err)
|
||||||
|
}
|
||||||
|
later := time.Now().Add(2 * time.Hour)
|
||||||
|
if _, err := store.Suspend(ctx, id, &later, "", "", nil); err != nil {
|
||||||
|
t.Fatalf("suspend dated-later: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
susp, ok, err := store.CurrentSuspension(ctx, id)
|
||||||
|
if err != nil || !ok {
|
||||||
|
t.Fatalf("CurrentSuspension = (ok %v, err %v), want (true, nil)", ok, err)
|
||||||
|
}
|
||||||
|
if !susp.Permanent() {
|
||||||
|
t.Error("strongest block should be the permanent one")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := store.LiftSuspension(ctx, id); err != nil {
|
||||||
|
t.Fatalf("lift: %v", err)
|
||||||
|
}
|
||||||
|
if _, ok, err := store.CurrentSuspension(ctx, id); err != nil || ok {
|
||||||
|
t.Fatalf("CurrentSuspension after lift = (ok %v, err %v), want (false, nil)", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReasonsCRUD covers the operator-editable picklist: create, list, get, update, delete, and
|
||||||
|
// the ErrNotFound paths.
|
||||||
|
func TestReasonsCRUD(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
store := account.NewStore(testDB)
|
||||||
|
|
||||||
|
created, err := store.CreateReason(ctx, "Cheating", "Читерство")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create reason: %v", err)
|
||||||
|
}
|
||||||
|
if created.ID == uuid.Nil || created.TextEn != "Cheating" || created.TextRu != "Читерство" {
|
||||||
|
t.Fatalf("created reason = %+v, want populated en/ru and id", created)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := store.GetReason(ctx, created.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get reason: %v", err)
|
||||||
|
}
|
||||||
|
if got.TextEn != "Cheating" {
|
||||||
|
t.Errorf("get TextEn = %q, want Cheating", got.TextEn)
|
||||||
|
}
|
||||||
|
|
||||||
|
list, err := store.ListReasons(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list reasons: %v", err)
|
||||||
|
}
|
||||||
|
if !containsReason(list, created.ID) {
|
||||||
|
t.Error("created reason missing from ListReasons")
|
||||||
|
}
|
||||||
|
|
||||||
|
updated, err := store.UpdateReason(ctx, created.ID, "Abuse", "Оскорбления")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("update reason: %v", err)
|
||||||
|
}
|
||||||
|
if updated.TextEn != "Abuse" || updated.TextRu != "Оскорбления" {
|
||||||
|
t.Errorf("updated reason = %+v, want Abuse/Оскорбления", updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := store.DeleteReason(ctx, created.ID); err != nil {
|
||||||
|
t.Fatalf("delete reason: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := store.GetReason(ctx, created.ID); !errors.Is(err, account.ErrNotFound) {
|
||||||
|
t.Errorf("get deleted reason = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
if _, err := store.UpdateReason(ctx, uuid.New(), "x", "y"); !errors.Is(err, account.ErrNotFound) {
|
||||||
|
t.Errorf("update missing reason = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSuspensionReasonSnapshotSurvivesDelete checks that a block keeps the reason text it was
|
||||||
|
// stamped with even after the picklist entry is deleted (the FK nulls reason_id, the snapshot
|
||||||
|
// stays).
|
||||||
|
func TestSuspensionReasonSnapshotSurvivesDelete(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
store := account.NewStore(testDB)
|
||||||
|
id := provisionAccount(t)
|
||||||
|
|
||||||
|
reason, err := store.CreateReason(ctx, "Toxicity", "Токсичность")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create reason: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := store.Suspend(ctx, id, nil, reason.TextEn, reason.TextRu, &reason.ID); err != nil {
|
||||||
|
t.Fatalf("suspend with reason: %v", err)
|
||||||
|
}
|
||||||
|
if err := store.DeleteReason(ctx, reason.ID); err != nil {
|
||||||
|
t.Fatalf("delete reason: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
susp, ok, err := store.CurrentSuspension(ctx, id)
|
||||||
|
if err != nil || !ok {
|
||||||
|
t.Fatalf("CurrentSuspension = (ok %v, err %v), want (true, nil)", ok, err)
|
||||||
|
}
|
||||||
|
if susp.LocalizedReason("en") != "Toxicity" || susp.LocalizedReason("ru") != "Токсичность" {
|
||||||
|
t.Errorf("reason snapshot lost after delete: en=%q ru=%q", susp.LocalizedReason("en"), susp.LocalizedReason("ru"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// containsReason reports whether list holds a reason with the given id.
|
||||||
|
func containsReason(list []account.Reason, id uuid.UUID) bool {
|
||||||
|
for _, r := range list {
|
||||||
|
if r.ID == id {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ func TestUserListFilter(t *testing.T) {
|
|||||||
st := account.NewStore(testDB)
|
st := account.NewStore(testDB)
|
||||||
uniq := uuid.NewString()
|
uniq := uuid.NewString()
|
||||||
|
|
||||||
human, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman")
|
human, _, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("provision human: %v", err)
|
t.Fatalf("provision human: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package inttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.uber.org/zap/zaptest"
|
||||||
|
|
||||||
|
"scrabble/backend/internal/account"
|
||||||
|
"scrabble/backend/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestVariantPreferenceGate covers the New Game gate: a player may start a quick game
|
||||||
|
// or create a friend invitation only in a variant they have enabled in their profile
|
||||||
|
// (a fresh account defaults to Erudit only), and any other variant is refused with 400.
|
||||||
|
// The complementary case — an invited friend accepting an invitation in a variant they
|
||||||
|
// have NOT enabled — is exercised by TestGameLimitGate, where a default-Erudit human
|
||||||
|
// accepts an English invitation over HTTP.
|
||||||
|
func TestVariantPreferenceGate(t *testing.T) {
|
||||||
|
clearOpenGames(t)
|
||||||
|
srv := server.New(":0", server.Deps{
|
||||||
|
Logger: zaptest.NewLogger(t),
|
||||||
|
DB: testDB,
|
||||||
|
Accounts: account.NewStore(testDB),
|
||||||
|
Games: newGameService(),
|
||||||
|
Matchmaker: newMatchmaker(t, newRobotService(t, newGameService()), time.Minute, 0),
|
||||||
|
Invitations: newInvitationService(),
|
||||||
|
})
|
||||||
|
|
||||||
|
human := provisionAccount(t) // default preferences: erudit_ru only
|
||||||
|
opp := provisionAccount(t)
|
||||||
|
|
||||||
|
// A variant outside the player's preferences is refused on both create paths.
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/lobby/enqueue", human, `{"variant":"scrabble_en"}`); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("enqueue non-preferred variant = %d (%s), want 400", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
invBody := fmt.Sprintf(`{"variant":"scrabble_en","invitee_ids":[%q]}`, opp.String())
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/invitations", human, invBody); rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("invitation non-preferred variant = %d (%s), want 400", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The default-enabled variant (Erudit) is allowed: the quick enqueue opens a game.
|
||||||
|
if rec := userPost(t, srv, "/api/v1/user/lobby/enqueue", human, `{"variant":"erudit_ru"}`); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("enqueue preferred variant = %d (%s), want 200", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
clearOpenGames(t)
|
||||||
|
}
|
||||||
@@ -150,6 +150,14 @@ func (svc *InvitationService) emitInvitationUpdate(ctx context.Context, inv Invi
|
|||||||
}
|
}
|
||||||
intents := make([]notify.Intent, 0, len(recipients))
|
intents := make([]notify.Intent, 0, len(recipients))
|
||||||
for _, id := range recipients {
|
for _, id := range recipients {
|
||||||
|
// An invitee who has blocked the inviter never sees this invitation, so they must not
|
||||||
|
// receive its updates either (an update would otherwise re-add it to their lobby). The
|
||||||
|
// inviter always gets updates; on a lookup error suppress rather than risk a leak.
|
||||||
|
if id != inv.InviterID {
|
||||||
|
if blk, err := svc.blocker.Blocks(ctx, id, inv.InviterID); err != nil || blk {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
intents = append(intents, notify.NotificationInvitationUpdate(id, summary))
|
intents = append(intents, notify.NotificationInvitationUpdate(id, summary))
|
||||||
}
|
}
|
||||||
svc.pub.Publish(intents...)
|
svc.pub.Publish(intents...)
|
||||||
@@ -211,6 +219,11 @@ func (svc *InvitationService) CreateInvitation(ctx context.Context, inviterID uu
|
|||||||
return Invitation{}, fmt.Errorf("%w: turn timeout %s not allowed", ErrInvalidInvitation, settings.TurnTimeout)
|
return Invitation{}, fmt.Errorf("%w: turn timeout %s not allowed", ErrInvalidInvitation, settings.TurnTimeout)
|
||||||
}
|
}
|
||||||
seen := map[uuid.UUID]bool{inviterID: true}
|
seen := map[uuid.UUID]bool{inviterID: true}
|
||||||
|
// suppressed collects invitees who have blocked the inviter: the invitation is still
|
||||||
|
// created and persisted for them, but they are never notified and never see it (their
|
||||||
|
// friendship with the inviter survived the block, so they can still appear in the
|
||||||
|
// inviter's picker — they must not learn of the block).
|
||||||
|
suppressed := make(map[uuid.UUID]bool)
|
||||||
for _, id := range inviteeIDs {
|
for _, id := range inviteeIDs {
|
||||||
if seen[id] {
|
if seen[id] {
|
||||||
return Invitation{}, fmt.Errorf("%w: %s invited twice or is the inviter", ErrInvalidInvitation, id)
|
return Invitation{}, fmt.Errorf("%w: %s invited twice or is the inviter", ErrInvalidInvitation, id)
|
||||||
@@ -222,13 +235,22 @@ func (svc *InvitationService) CreateInvitation(ctx context.Context, inviterID uu
|
|||||||
}
|
}
|
||||||
return Invitation{}, err
|
return Invitation{}, err
|
||||||
}
|
}
|
||||||
blocked, err := svc.blocker.IsBlocked(ctx, inviterID, id)
|
// A block the inviter placed refuses the invite (the inviter is aware; the picker hides
|
||||||
|
// the invitee anyway). A block the invitee placed on the inviter is instead suppressed.
|
||||||
|
iBlock, err := svc.blocker.Blocks(ctx, inviterID, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Invitation{}, err
|
return Invitation{}, err
|
||||||
}
|
}
|
||||||
if blocked {
|
if iBlock {
|
||||||
return Invitation{}, ErrInvitationBlocked
|
return Invitation{}, ErrInvitationBlocked
|
||||||
}
|
}
|
||||||
|
theyBlock, err := svc.blocker.Blocks(ctx, id, inviterID)
|
||||||
|
if err != nil {
|
||||||
|
return Invitation{}, err
|
||||||
|
}
|
||||||
|
if theyBlock {
|
||||||
|
suppressed[id] = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
id, err := uuid.NewV7()
|
id, err := uuid.NewV7()
|
||||||
@@ -253,7 +275,18 @@ func (svc *InvitationService) CreateInvitation(ctx context.Context, inviterID uu
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return Invitation{}, err
|
return Invitation{}, err
|
||||||
}
|
}
|
||||||
svc.emitInvitation(ctx, inv, inviteeIDs)
|
// Notify every invitee except those who have blocked the inviter (their copy stays
|
||||||
|
// stored but unseen — the store-but-hide that keeps the block invisible).
|
||||||
|
notifyIDs := inviteeIDs
|
||||||
|
if len(suppressed) > 0 {
|
||||||
|
notifyIDs = make([]uuid.UUID, 0, len(inviteeIDs))
|
||||||
|
for _, id := range inviteeIDs {
|
||||||
|
if !suppressed[id] {
|
||||||
|
notifyIDs = append(notifyIDs, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
svc.emitInvitation(ctx, inv, notifyIDs)
|
||||||
return inv, nil
|
return inv, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,6 +380,17 @@ func (svc *InvitationService) ListInvitations(ctx context.Context, accountID uui
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
// Hide an invitation whose inviter the viewer has blocked: it stays stored but must
|
||||||
|
// never surface to the blocker. The viewer's own invitations (as inviter) are unaffected.
|
||||||
|
if inv.InviterID != accountID {
|
||||||
|
blocked, err := svc.blocker.Blocks(ctx, accountID, inv.InviterID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if blocked {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
out = append(out, inv)
|
out = append(out, inv)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
|
|||||||
@@ -33,13 +33,20 @@ type GameCreator interface {
|
|||||||
// available so the matchmaker can defer substitution.
|
// available so the matchmaker can defer substitution.
|
||||||
type RobotProvider interface {
|
type RobotProvider interface {
|
||||||
Pick(variant engine.Variant) (uuid.UUID, error)
|
Pick(variant engine.Variant) (uuid.UUID, error)
|
||||||
|
// PickNamed selects a robot and composes a fresh per-game display name for it, for
|
||||||
|
// the disguised auto-match path (the name is stamped on the robot's seat).
|
||||||
|
PickNamed(variant engine.Variant) (uuid.UUID, string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blocker reports whether two accounts have a block between them (either
|
// Blocker exposes the per-user block graph the lobby needs. social.Service satisfies it.
|
||||||
// direction). social.Service satisfies it; the lobby uses it to refuse
|
// Invitations consult the exact direction (Blocks) so the inviter's block refuses while a
|
||||||
// invitations between blocked accounts.
|
// block the invitee placed on the inviter is silently suppressed; auto-match consults
|
||||||
|
// BlockedWith so a block either way keeps the pair out of the same anonymous game.
|
||||||
type Blocker interface {
|
type Blocker interface {
|
||||||
IsBlocked(ctx context.Context, a, b uuid.UUID) (bool, error)
|
// Blocks reports whether blocker has blocked blocked (exact direction).
|
||||||
|
Blocks(ctx context.Context, blocker, blocked uuid.UUID) (bool, error)
|
||||||
|
// BlockedWith returns every account in a block with accountID in either direction.
|
||||||
|
BlockedWith(ctx context.Context, accountID uuid.UUID) ([]uuid.UUID, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-match defaults: a casual two-player game on the longest move clock with one
|
// Auto-match defaults: a casual two-player game on the longest move clock with one
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user