Compare commits
47 Commits
1933849dba
...
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 |
+64
-40
@@ -26,6 +26,13 @@ on:
|
||||
push:
|
||||
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:
|
||||
# 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.
|
||||
@@ -86,7 +93,6 @@ jobs:
|
||||
# The engine consumes the published scrabble-solver module from this Gitea;
|
||||
# GOPRIVATE makes go fetch it directly (skipping the public proxy/checksum DB).
|
||||
GOPRIVATE: gitea.iliadenisov.ru/*
|
||||
DICT_VERSION: v1.0.0
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -134,7 +140,6 @@ jobs:
|
||||
# suite's TestMain terminates its own container, so disable it.
|
||||
TESTCONTAINERS_RYUK_DISABLED: "true"
|
||||
GOPRIVATE: gitea.iliadenisov.ru/*
|
||||
DICT_VERSION: v1.0.0
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -254,25 +259,24 @@ jobs:
|
||||
AWG_CONF: ${{ secrets.TEST_AWG_CONF }}
|
||||
GM_BASICAUTH_HASH: ${{ secrets.TEST_GM_BASICAUTH_HASH }}
|
||||
GRAFANA_ADMIN_PASSWORD: ${{ secrets.TEST_GRAFANA_ADMIN_PASSWORD }}
|
||||
TELEGRAM_BOT_TOKEN_EN: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN_EN }}
|
||||
TELEGRAM_BOT_TOKEN_RU: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN_RU }}
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TEST_TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_PROMO_BOT_TOKEN: ${{ secrets.TEST_TELEGRAM_PROMO_BOT_TOKEN }}
|
||||
GM_BASICAUTH_USER: ${{ vars.TEST_GM_BASICAUTH_USER }}
|
||||
GRAFANA_ROOT_URL: ${{ vars.TEST_GRAFANA_ROOT_URL }}
|
||||
CADDY_SITE_ADDRESS: ${{ vars.TEST_CADDY_SITE_ADDRESS }}
|
||||
TELEGRAM_MINIAPP_URL: ${{ vars.TEST_TELEGRAM_MINIAPP_URL }}
|
||||
TELEGRAM_GAME_CHANNEL_ID_EN: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID_EN }}
|
||||
TELEGRAM_GAME_CHANNEL_ID_RU: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID_RU }}
|
||||
TELEGRAM_GAME_CHANNEL_ID: ${{ vars.TEST_TELEGRAM_GAME_CHANNEL_ID }}
|
||||
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,
|
||||
# not an operator variable. The prod workflow leaves it false.
|
||||
TELEGRAM_TEST_ENV: "true"
|
||||
VITE_TELEGRAM_BOT_ID: ${{ vars.TEST_VITE_TELEGRAM_BOT_ID }}
|
||||
VITE_TELEGRAM_LINK: ${{ vars.TEST_VITE_TELEGRAM_LINK }}
|
||||
VITE_TELEGRAM_LINK_EN: ${{ vars.TEST_VITE_TELEGRAM_LINK_EN }}
|
||||
VITE_TELEGRAM_LINK_RU: ${{ vars.TEST_VITE_TELEGRAM_LINK_RU }}
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_EN: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME_EN }}
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_RU: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME_RU }}
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME: ${{ vars.TEST_VITE_TELEGRAM_GAME_CHANNEL_NAME }}
|
||||
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.
|
||||
POSTGRES_DB: ${{ vars.TEST_POSTGRES_DB }}
|
||||
POSTGRES_USER: ${{ vars.TEST_POSTGRES_USER }}
|
||||
@@ -289,62 +293,82 @@ jobs:
|
||||
mkdir -p "$conf"
|
||||
cp -r caddy otelcol prometheus tempo grafana "$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
|
||||
# (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)"
|
||||
docker compose --ansi never build --progress plain
|
||||
docker compose --ansi never up -d --remove-orphans
|
||||
# The telegram-local profile brings the bot + its VPN sidecar; prod runs the
|
||||
# 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`
|
||||
# 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
|
||||
# pick up the fresh config.
|
||||
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: |
|
||||
set -u
|
||||
# Two probes through the contour caddy: "/" is the static
|
||||
# landing container, "/app/" is the gateway-served SPA shell.
|
||||
# Three probes. "/" is the static landing container and "/app/" the
|
||||
# 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
|
||||
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
|
||||
echo "healthy: GET http://scrabble/ (landing) + /app/ (gateway)"
|
||||
docker run --rm --network edge alpine:3.20 wget -q -T 5 -O /dev/null http://scrabble/app/ &&
|
||||
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
|
||||
fi
|
||||
sleep 3
|
||||
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-gateway || true
|
||||
docker logs --tail 50 scrabble-backend || true
|
||||
exit 1
|
||||
|
||||
- name: Probe the Telegram connector liveness
|
||||
- name: Probe the Telegram validator and bot liveness
|
||||
run: |
|
||||
set -u
|
||||
# The gateway probe cannot see a crash-looping connector (it long-polls and
|
||||
# egresses through the VPN sidecar, with no public ingress). Inspect the
|
||||
# container directly: it must be running, not restarting, with a stable
|
||||
# restart count. A grace period lets the VPN handshake settle (the connector
|
||||
# may restart a few times first).
|
||||
# The gateway/backend probes cannot see a crash-looping validator or bot
|
||||
# (the validator answers only internal gRPC; the bot long-polls + egresses
|
||||
# through the VPN sidecar with no public ingress). Inspect the containers
|
||||
# directly: each must be running, not restarting, with a stable restart
|
||||
# count. A grace period lets the VPN handshake and the bot-link dial settle.
|
||||
sleep 20
|
||||
for i in $(seq 1 20); do
|
||||
status="$(docker inspect -f '{{.State.Status}}' scrabble-telegram 2>/dev/null || echo missing)"
|
||||
restarting="$(docker inspect -f '{{.State.Restarting}}' scrabble-telegram 2>/dev/null || echo true)"
|
||||
if [ "$status" = "running" ] && [ "$restarting" = "false" ]; then
|
||||
c1="$(docker inspect -f '{{.RestartCount}}' scrabble-telegram)"
|
||||
sleep 5
|
||||
c2="$(docker inspect -f '{{.RestartCount}}' scrabble-telegram)"
|
||||
if [ "$c1" = "$c2" ]; then
|
||||
echo "connector healthy: status=$status restarts=$c2"
|
||||
exit 0
|
||||
for name in scrabble-telegram-validator scrabble-telegram-bot; do
|
||||
ok=
|
||||
for i in $(seq 1 20); do
|
||||
status="$(docker inspect -f '{{.State.Status}}' "$name" 2>/dev/null || echo missing)"
|
||||
restarting="$(docker inspect -f '{{.State.Restarting}}' "$name" 2>/dev/null || echo true)"
|
||||
if [ "$status" = "running" ] && [ "$restarting" = "false" ]; then
|
||||
c1="$(docker inspect -f '{{.RestartCount}}' "$name")"
|
||||
sleep 5
|
||||
c2="$(docker inspect -f '{{.RestartCount}}' "$name")"
|
||||
if [ "$c1" = "$c2" ]; then
|
||||
echo "$name healthy: status=$status restarts=$c2"
|
||||
ok=1
|
||||
break
|
||||
fi
|
||||
echo "$name still restarting ($c1 -> $c2); waiting"
|
||||
fi
|
||||
echo "connector still restarting ($c1 -> $c2); waiting"
|
||||
sleep 3
|
||||
done
|
||||
if [ -z "$ok" ]; then
|
||||
echo "$name not healthy; recent logs:"
|
||||
docker logs --tail 80 "$name" || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "connector not healthy; recent logs:"
|
||||
docker logs --tail 80 scrabble-telegram || true
|
||||
exit 1
|
||||
|
||||
- name: Prune dangling images
|
||||
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
|
||||
|
||||
# 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/scheduled_tasks.lock
|
||||
|
||||
@@ -125,9 +125,9 @@ backend/ # module scrabble/backend
|
||||
internal/inttest/ # //go:build integration Postgres-backed tests
|
||||
docs/ .gitea/workflows/ PLAN.md CLAUDE.md README.md
|
||||
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)
|
||||
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
|
||||
```
|
||||
|
||||
@@ -138,7 +138,7 @@ go build ./backend/... # per module ('./...' from the root won't span t
|
||||
go vet ./backend/...
|
||||
gofmt -l . # must print nothing
|
||||
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
|
||||
|
||||
cd ui && pnpm install && pnpm check && pnpm test:unit && pnpm build # the UI (Stage 7+)
|
||||
|
||||
@@ -51,7 +51,7 @@ independent (see ARCHITECTURE §9.1).
|
||||
| 15 | Dual Telegram bots & language-gated variants | **done** |
|
||||
| 16 | Deploy infra & test contour (Dockerfiles, gateway static UI, compose, observability) | **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
|
||||
@@ -281,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`)
|
||||
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)*
|
||||
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
|
||||
@@ -407,18 +413,28 @@ raw list is kept here as the record of what the first contour run surfaced.
|
||||
"что-то пошло не так". при этом "new -> эрудит" работает. Попробуй посмотреть в логах сейчас, может что-то есть. Или как-то иначе проанализируй, или давай вместе будем смотреть, если не получится.
|
||||
|
||||
### Stage 18 — Prod contour deploy
|
||||
Scope: the **production contour** on a remote host over SSH. Deploy by **container export/import**
|
||||
(`docker save` → `scp`/ssh → `docker load` → `docker compose up` on the remote), the SSH key + host IP
|
||||
in Gitea secrets; **strictly manual** (`workflow_dispatch`) after `development` is merged to `master`
|
||||
(the Stage 16 branch model: `feature/* → development → master`, merge gated green). Two-contour config
|
||||
uses **`TEST_`/`PROD_` secret/variable prefixes** — Gitea 1.26 has no deployment environments (verified:
|
||||
the `environments` API 404s), so a flat prefixed namespace is the convention.
|
||||
Reuses the Stage 16 `deploy/docker-compose.yml` as-is, mapping the **`PROD_`** set onto the same
|
||||
unprefixed compose vars. **No host caddy on prod**, so the contour's own caddy terminates TLS — set
|
||||
`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).
|
||||
Open details (re-interview): export/import vs a registry trade-off; prod domain/cert source (ACME vs a
|
||||
provided cert) at the contour caddy; prod VPN; rollback.
|
||||
Scope: the **production contour** on **two remote hosts** over SSH — main (full stack, `erudit-game.ru`)
|
||||
and tg (the bot only). Resolved open details (re-interviewed):
|
||||
- **Transport: a registry** (not export/import) — build + push to `docker.iliadenisov.ru`, the hosts pull by tag.
|
||||
- **Cert: ACME** at the contour caddy (`CADDY_SITE_ADDRESS=erudit-game.ru www.erudit-game.ru`, no host caddy).
|
||||
- **No prod VPN** — the bot host has native Bot API egress (verified `api.telegram.org` → 200).
|
||||
- **Rollback** — rolling per-service deploy (least → most dependent), health-gated, auto-rollback to the
|
||||
previous image tag; a maintenance window + consistent `pg_dump` only on a schema migration
|
||||
(expand-contract keeps the auto-rollback image-only; the dump is a manual safety net).
|
||||
|
||||
**Strictly manual** (`workflow_dispatch` from `master`, `confirm=deploy`) after `development → master`
|
||||
is merged green. `TEST_`/`PROD_` prefixed Gitea secrets/variables (Gitea 1.26 has no deployment
|
||||
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
|
||||
|
||||
+85
-3
@@ -37,6 +37,11 @@ the edge before prod. Each phase maps back to the owner's raw pre-release TODO l
|
||||
| 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) |
|
||||
|
||||
## Key findings (these reshaped the raw list — read before starting a phase)
|
||||
@@ -80,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** —
|
||||
a *soft, reversible* "suspected high-rate" marker for operator review, tunable threshold,
|
||||
**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
|
||||
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
|
||||
@@ -88,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
|
||||
schema is edited in the baseline (no prod data); `game_players.account_id` is nullable for the
|
||||
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
|
||||
|
||||
@@ -279,7 +311,7 @@ Then Stage 18.
|
||||
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
|
||||
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,
|
||||
separate hardware, pool/limit sizing).
|
||||
- **CI:** `./loadtest/...` added to the path filter + vet/build/test; `go.work.sum` carries the new deps.
|
||||
@@ -422,7 +454,12 @@ Then Stage 18.
|
||||
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
|
||||
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
|
||||
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).
|
||||
@@ -432,7 +469,7 @@ Then Stage 18.
|
||||
**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
|
||||
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`.
|
||||
|
||||
- **UI — Tab-bar navigation redesign** (owner ad-hoc, not on the raw TODO list): drop the hamburger
|
||||
@@ -548,3 +585,48 @@ Then Stage 18.
|
||||
(`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 -----------------------------------------------------
|
||||
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 mkdir -p /dawg \
|
||||
&& 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
|
||||
# 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 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 -----------------------------------------------------------------
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
|
||||
+34
-13
@@ -103,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
|
||||
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
|
||||
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
|
||||
`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
|
||||
with no identity, excluded from statistics. The server-rendered
|
||||
**admin console** at `/_gm` (`internal/adminconsole` + `internal/server/handlers_admin_console.go`;
|
||||
@@ -116,16 +123,15 @@ 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` +
|
||||
`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 Telegram-connector client (`internal/connector`, `BACKEND_CONNECTOR_ADDR`) — each
|
||||
broadcast picks the delivering bot by an operator-chosen language. `accounts.service_language`
|
||||
holds the language tag of the bot a Telegram
|
||||
user last signed in through, written on every login and returned by
|
||||
`/internal/push-target` (falling back to `preferred_language`) so out-of-app push routes
|
||||
to the right bot. The console also manages the **advertising banner** (`/_gm/banners` +
|
||||
backend client (`internal/connector`, `BACKEND_CONNECTOR_ADDR`) that calls the gateway's
|
||||
**bot-link relay** — each broadcast renders through the bot in an operator-chosen language
|
||||
and the relay awaits the bot's delivery ack. There is one bot,
|
||||
so `/internal/push-target` returns the recipient's `preferred_language` as the render
|
||||
language for out-of-app push; no per-bot routing remains. The console also manages the **advertising banner** (`/_gm/banners` +
|
||||
`/_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 `service_language`); changing those inputs
|
||||
&& !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.
|
||||
|
||||
@@ -149,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
|
||||
**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
|
||||
|
||||
```
|
||||
@@ -172,8 +185,9 @@ internal/lobby/ # auto-match (DB-backed open games + robot substitution) +
|
||||
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/ads/ # advertising banner: campaigns + bilingual messages + display timings, weighted-rotation feed (ActiveSet)
|
||||
internal/connector/ # backend gRPC client to the Telegram connector (operator broadcasts)
|
||||
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/banview/ # gateway active-ban mirror: the console's Active IP bans panel + the operator unban backchannel
|
||||
```
|
||||
|
||||
## Configuration (environment)
|
||||
@@ -192,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_METRICS_EXPORTER` | `none` | `none`, `stdout` or `otlp`. |
|
||||
| `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_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. |
|
||||
@@ -203,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_PASSWORD` | — | SMTP password. |
|
||||
| `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_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. |
|
||||
@@ -214,7 +228,7 @@ internal/ratewatch/ # gateway rate-limit reports: episode window for the consol
|
||||
```sh
|
||||
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):
|
||||
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_DICT_DIR=/tmp/dawg \
|
||||
GOPRIVATE='gitea.iliadenisov.ru/*' \
|
||||
@@ -253,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)
|
||||
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
|
||||
(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
|
||||
|
||||
|
||||
@@ -15,11 +15,13 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/accountmerge"
|
||||
"scrabble/backend/internal/ads"
|
||||
"scrabble/backend/internal/banview"
|
||||
"scrabble/backend/internal/config"
|
||||
"scrabble/backend/internal/connector"
|
||||
"scrabble/backend/internal/engine"
|
||||
@@ -159,6 +161,15 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
zap.Duration("interval", cfg.GuestReapInterval),
|
||||
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,
|
||||
// so they are handed to the server (like the route groups) for the handlers.
|
||||
mailer := newMailer(cfg.SMTP, logger)
|
||||
@@ -211,6 +222,10 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
zap.Int("flag_threshold", cfg.RateWatch.FlagThreshold),
|
||||
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))
|
||||
@@ -233,6 +248,7 @@ func run(ctx context.Context, cfg config.Config, logger *zap.Logger) error {
|
||||
DictDir: cfg.Game.DictDir,
|
||||
Connector: conn,
|
||||
RateWatch: rateWatch,
|
||||
BanView: banView,
|
||||
Ads: adsSvc,
|
||||
Notifier: hub,
|
||||
})
|
||||
|
||||
@@ -55,12 +55,12 @@ type Account struct {
|
||||
HintBalance int
|
||||
BlockChat bool
|
||||
BlockFriendRequests bool
|
||||
// ServiceLanguage is the language tag (en/ru) of the bot the account last
|
||||
// authenticated through (its last Telegram ValidateInitData); it routes the
|
||||
// account's out-of-app push back through the right bot. Empty when the account
|
||||
// has never signed in through a tagged bot. Distinct from PreferredLanguage (the
|
||||
// interface language) and from a game's variant language.
|
||||
ServiceLanguage string
|
||||
// VariantPreferences is the set of game variants (engine.Variant stable labels:
|
||||
// "scrabble_en", "scrabble_ru", "erudit_ru") the player is willing to be matched
|
||||
// into. It gates the New Game picker, the matchmaker and the friend-invite the
|
||||
// player creates; an invited friend may still accept any variant. A new account
|
||||
// defaults to Erudit only. Never empty — enforced on update and by a DB check.
|
||||
VariantPreferences []string
|
||||
// IsGuest marks an ephemeral guest account: a durable row with no identity,
|
||||
// excluded from statistics, friends and history.
|
||||
IsGuest bool
|
||||
@@ -151,14 +151,26 @@ func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName stri
|
||||
return modelToAccount(row), nil
|
||||
}
|
||||
|
||||
// ProvisionTelegram provisions (or finds) the account bound to a Telegram
|
||||
// identity. On first contact only, it seeds the new account's preferred language
|
||||
// from the Telegram client languageCode (when it maps to a supported language) and
|
||||
// its display name sanitized from firstName (falling back to username, then to a
|
||||
// generated placeholder when neither yields any letters); an already-existing
|
||||
// account is returned unchanged, so a later profile edit is never overwritten.
|
||||
func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode, username, firstName string) (Account, error) {
|
||||
return s.provision(ctx, KindTelegram, externalID, telegramSeed(languageCode, username, firstName))
|
||||
// ProvisionTelegram provisions (or finds) the account bound to a Telegram identity,
|
||||
// reporting whether this call created it (first contact). On first contact only, it
|
||||
// seeds the new account's preferred language from the Telegram client languageCode
|
||||
// (when it maps to a supported language) and its display name sanitized from firstName
|
||||
// (falling back to username, then to a generated placeholder when neither yields any
|
||||
// letters); an already-existing account is returned unchanged, so a later profile edit
|
||||
// is never overwritten. The created flag lets the auth handler re-evaluate moderated-
|
||||
// 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,
|
||||
@@ -303,6 +315,14 @@ func (s *Store) CountAccounts(ctx context.Context) (int, error) {
|
||||
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,
|
||||
// or ErrNotFound.
|
||||
func (s *Store) findByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
||||
@@ -491,36 +511,12 @@ func (s *Store) ClearHighRateFlag(ctx context.Context, id uuid.UUID) error {
|
||||
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.
|
||||
func modelToAccount(row model.Accounts) Account {
|
||||
var mergedInto uuid.UUID
|
||||
if row.MergedInto != nil {
|
||||
mergedInto = *row.MergedInto
|
||||
}
|
||||
var serviceLanguage string
|
||||
if row.ServiceLanguage != nil {
|
||||
serviceLanguage = *row.ServiceLanguage
|
||||
}
|
||||
var flaggedHighRateAt time.Time
|
||||
if row.FlaggedHighRateAt != nil {
|
||||
flaggedHighRateAt = *row.FlaggedHighRateAt
|
||||
@@ -529,7 +525,7 @@ func modelToAccount(row model.Accounts) Account {
|
||||
ID: row.AccountID,
|
||||
DisplayName: row.DisplayName,
|
||||
PreferredLanguage: row.PreferredLanguage,
|
||||
ServiceLanguage: serviceLanguage,
|
||||
VariantPreferences: []string(row.VariantPreferences),
|
||||
TimeZone: row.TimeZone,
|
||||
AwayStart: row.AwayStart,
|
||||
AwayEnd: row.AwayEnd,
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/go-jet/jet/v2/postgres"
|
||||
"github.com/go-jet/jet/v2/qrm"
|
||||
"github.com/google/uuid"
|
||||
"github.com/lib/pq"
|
||||
|
||||
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||
@@ -58,6 +59,46 @@ type ProfileUpdate struct {
|
||||
BlockChat bool
|
||||
BlockFriendRequests 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
|
||||
@@ -79,17 +120,26 @@ func (s *Store) UpdateProfile(ctx context.Context, id uuid.UUID, p ProfileUpdate
|
||||
if err := validateAwayWindow(p.AwayStart, p.AwayEnd); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
prefs, err := validateVariantPreferences(p.VariantPreferences)
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
|
||||
stmt := table.Accounts.UPDATE(
|
||||
table.Accounts.DisplayName, table.Accounts.PreferredLanguage, table.Accounts.TimeZone,
|
||||
table.Accounts.AwayStart, table.Accounts.AwayEnd,
|
||||
table.Accounts.BlockChat, table.Accounts.BlockFriendRequests,
|
||||
table.Accounts.NotificationsInAppOnly, table.Accounts.UpdatedAt,
|
||||
table.Accounts.NotificationsInAppOnly, table.Accounts.VariantPreferences,
|
||||
table.Accounts.UpdatedAt,
|
||||
).SET(
|
||||
postgres.String(name), postgres.String(lang), postgres.String(tz),
|
||||
postgres.TimeT(p.AwayStart), postgres.TimeT(p.AwayEnd),
|
||||
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))).
|
||||
RETURNING(table.Accounts.AllColumns)
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -16,7 +17,7 @@ import (
|
||||
// offset/IANA timezone), not just their unit tests in validate_test.go.
|
||||
func TestUpdateProfileValidation(t *testing.T) {
|
||||
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) }
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -28,6 +29,8 @@ func TestUpdateProfileValidation(t *testing.T) {
|
||||
{"over-long name", func(p *ProfileUpdate) { p.DisplayName = strings.Repeat("x", maxDisplayName+1) }},
|
||||
{"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) }},
|
||||
{"empty variant preferences", func(p *ProfileUpdate) { p.VariantPreferences = nil }},
|
||||
{"unknown variant preference", func(p *ProfileUpdate) { p.VariantPreferences = []string{"chess"} }},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,11 +24,19 @@ const (
|
||||
// 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}
|
||||
var KnownRoles = []string{RoleFeedbackBanned, RoleNoBanner, RoleChatMuted}
|
||||
|
||||
// IsKnownRole reports whether role is a recognised account role.
|
||||
func IsKnownRole(role string) bool {
|
||||
|
||||
@@ -161,6 +161,31 @@ func (s *Store) queryCurrentSuspension(ctx context.Context, accountID uuid.UUID,
|
||||
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) {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -43,7 +43,7 @@ func TestRendererRendersEveryPage(t *testing.T) {
|
||||
{"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", BotLanguage: "ru", Body: "please fix the board", HasAttachment: true, AttachmentName: "shot.png", IsImage: true, Banned: true}, "bot: ru"},
|
||||
{"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"},
|
||||
{"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"},
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
{{if .ConnectorEnabled}}
|
||||
<form class="form col" method="post" action="/_gm/broadcast">
|
||||
<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>
|
||||
</form>
|
||||
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<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}}{{if .BotLanguage}} (bot: {{.BotLanguage}}){{end}}</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>
|
||||
|
||||
@@ -5,6 +5,26 @@
|
||||
list is in-memory and resets on a backend restart. An account sustaining
|
||||
{{.FlagThreshold}}+ rejected calls within {{.FlagWindow}} is soft-flagged for review
|
||||
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>
|
||||
<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>
|
||||
|
||||
@@ -137,7 +137,6 @@
|
||||
{{if .ConnectorEnabled}}
|
||||
<form class="form col" method="post" action="/_gm/users/{{.ID}}/message">
|
||||
<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>
|
||||
</form>
|
||||
{{else}}<p class="note">connector not configured (set BACKEND_CONNECTOR_ADDR)</p>{{end}}
|
||||
|
||||
@@ -389,17 +389,27 @@ type BroadcastView struct {
|
||||
ConnectorEnabled bool
|
||||
}
|
||||
|
||||
// ThrottledView is the rate-limit observability page: the recent gateway-reported
|
||||
// throttle episodes (in-memory, reset on restart) and the accounts currently
|
||||
// carrying the high-rate flag. FlagThreshold and FlagWindow caption the active
|
||||
// auto-flag tuning.
|
||||
// ThrottledView is the rate-limit observability page: the temporary IP bans the
|
||||
// gateway is currently enforcing, the recent gateway-reported throttle episodes
|
||||
// (in-memory, reset on restart) and the accounts currently carrying the high-rate
|
||||
// flag. FlagThreshold and FlagWindow caption the active auto-flag tuning.
|
||||
type ThrottledView struct {
|
||||
Bans []BanRow
|
||||
Episodes []ThrottleEpisodeRow
|
||||
Flagged []FlaggedAccountRow
|
||||
FlagThreshold int
|
||||
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
|
||||
// user card and is set only for the user class (the other classes key by IP).
|
||||
type ThrottleEpisodeRow struct {
|
||||
@@ -531,11 +541,8 @@ type FeedbackDetailView struct {
|
||||
SenderName string
|
||||
Source string
|
||||
Channel string
|
||||
// InterfaceLanguage is the sender's interface language (account preference);
|
||||
// BotLanguage is the connector bot they last used (en/ru), set only for a
|
||||
// message that arrived through an external connector (Telegram).
|
||||
// InterfaceLanguage is the sender's interface language (account preference).
|
||||
InterfaceLanguage string
|
||||
BotLanguage string
|
||||
IP string
|
||||
Body string
|
||||
HasAttachment bool
|
||||
|
||||
@@ -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
|
||||
// connector side-service. The admin console uses it to send operator broadcasts:
|
||||
// a direct message to one user, or a post to a game channel. Each broadcast
|
||||
// selects the delivering bot by language (an operator choice, since the connector
|
||||
// hosts one bot per service language). The connector lives on the trusted internal
|
||||
// network, so the connection uses insecure (plaintext) transport credentials
|
||||
// (docs/ARCHITECTURE.md §12). It mirrors gateway/internal/connector, narrowed to
|
||||
// the two broadcast methods the admin surface needs.
|
||||
// Package connector is the backend's gRPC client for operator broadcasts: a direct
|
||||
// message to one user, or a post to the game channel. It calls the gateway's
|
||||
// bot-link relay (which forwards the send to the remote bot over the reverse mTLS
|
||||
// link and reports back whether it was delivered). The relay lives on the trusted
|
||||
// internal network, so the connection uses insecure (plaintext) transport
|
||||
// credentials (docs/ARCHITECTURE.md §12). It speaks the Telegram service contract,
|
||||
// narrowed to the two broadcast methods the admin surface needs.
|
||||
package connector
|
||||
|
||||
import (
|
||||
@@ -37,22 +36,21 @@ func New(addr string) (*Client, error) {
|
||||
func (c *Client) Close() error { return c.conn.Close() }
|
||||
|
||||
// SendToUser sends an operator text message to one user, addressed by their
|
||||
// platform external_id, through the bot for the given language. delivered reports
|
||||
// whether the connector actually sent it (false when the user has not started that
|
||||
// bot).
|
||||
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, Language: language})
|
||||
// platform external_id, through the bot. delivered reports whether the connector
|
||||
// actually sent it (false when the user has not started the bot).
|
||||
func (c *Client) SendToUser(ctx context.Context, externalID, text string) (bool, error) {
|
||||
resp, err := c.c.SendToUser(ctx, &telegramv1.SendToUserRequest{ExternalId: externalID, Text: text})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return resp.GetDelivered(), nil
|
||||
}
|
||||
|
||||
// SendToGameChannel posts an operator text message to the game channel of the bot
|
||||
// for the given language. delivered reports whether the connector sent it (false
|
||||
// when that bot has no channel configured).
|
||||
func (c *Client) SendToGameChannel(ctx context.Context, text, language string) (bool, error) {
|
||||
resp, err := c.c.SendToGameChannel(ctx, &telegramv1.SendToGameChannelRequest{Text: text, Language: language})
|
||||
// SendToGameChannel posts an operator text message to the bot's game channel.
|
||||
// delivered reports whether the connector sent it (false when the bot has no
|
||||
// channel configured).
|
||||
func (c *Client) SendToGameChannel(ctx context.Context, text string) (bool, error) {
|
||||
resp, err := c.c.SendToGameChannel(ctx, &telegramv1.SendToGameChannelRequest{Text: text})
|
||||
if err != nil {
|
||||
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
|
||||
// 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>/
|
||||
// at runtime is resident again after a restart. A subdirectory named like the
|
||||
// boot version is skipped (the flat dir already is the boot version). A partially
|
||||
// loaded registry is closed before any error is returned.
|
||||
// at runtime is resident again after a restart. The flat dir's version is resolved
|
||||
// from its .seed_version marker (see resolveSeedVersion): a fresh dir records
|
||||
// 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) {
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
for _, e := range entries {
|
||||
// Skip non-directories, the boot version (already loaded as the flat dir)
|
||||
// and dot-prefixed directories (the upload staging area, dir/.staging/).
|
||||
if !e.IsDir() || e.Name() == bootVersion || strings.HasPrefix(e.Name(), ".") {
|
||||
// Skip non-directories, the resolved seed version (already loaded as the flat
|
||||
// dir) and dot-prefixed directories (the upload staging area, dir/.staging/).
|
||||
if !e.IsDir() || e.Name() == seed || strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
if _, err := r.LoadAvailable(filepath.Join(dir, e.Name()), e.Name()); err != nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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
|
||||
// already resident, moves the latest pointer and keeps the earlier version.
|
||||
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
|
||||
}
|
||||
@@ -112,14 +112,9 @@ func (svc *Service) Submit(ctx context.Context, accountID uuid.UUID, body string
|
||||
attachmentName = "" // a name without bytes carries no attachment
|
||||
}
|
||||
ch := normalizeChannel(channel)
|
||||
// Snapshot the languages at submit time (acc is already loaded for the guest check):
|
||||
// the sender's interface language, and the connector bot language when the message
|
||||
// came through an external connector (currently Telegram).
|
||||
var channelLang string
|
||||
if ch == "telegram" {
|
||||
channelLang = acc.ServiceLanguage
|
||||
}
|
||||
_, err = svc.store.Insert(ctx, accountID, body, attachment, attachmentName, ch, acc.PreferredLanguage, channelLang, parseIP(senderIP))
|
||||
// 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
|
||||
}
|
||||
|
||||
|
||||
@@ -34,11 +34,10 @@ func NewStore(db *sql.DB) *Store {
|
||||
|
||||
// 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) and channelLang
|
||||
// (the connector bot language, empty for a non-connector channel) are snapshots 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, channelLang string, ip *string) (uuid.UUID, error) {
|
||||
// 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)
|
||||
@@ -49,9 +48,9 @@ func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, body string, at
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO backend.feedback_messages
|
||||
(message_id, account_id, body, attachment, attachment_name, channel, lang, channel_lang, sender_ip)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
id, accountID, body, att, nullStr(attachmentName), channel, nullStr(lang), nullStr(channelLang), ip); err != nil {
|
||||
(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
|
||||
@@ -228,10 +227,8 @@ type AdminMessage struct {
|
||||
Source string
|
||||
Body string
|
||||
Channel string
|
||||
// Lang is the sender's interface language and ChannelLang the connector bot language
|
||||
// (en/ru, empty for a non-connector channel) — both snapshotted at submit time.
|
||||
// Lang is the sender's interface language, snapshotted at submit time.
|
||||
Lang string
|
||||
ChannelLang string
|
||||
SenderIP string
|
||||
HasAttachment bool
|
||||
AttachmentName string
|
||||
@@ -346,7 +343,7 @@ 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.channel_lang, ''),
|
||||
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
|
||||
@@ -355,7 +352,7 @@ func (s *Store) AdminGet(ctx context.Context, id uuid.UUID) (AdminMessage, error
|
||||
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.ChannelLang,
|
||||
&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) {
|
||||
|
||||
@@ -63,6 +63,7 @@ type gameCache struct {
|
||||
|
||||
type cachedGame struct {
|
||||
game *engine.Game
|
||||
seats []Seat
|
||||
variant string
|
||||
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}
|
||||
}
|
||||
|
||||
// get returns the live game for id and refreshes its idle timer, or (nil, false).
|
||||
func (c *gameCache) get(id uuid.UUID) (*engine.Game, bool) {
|
||||
// get returns the live game and its immutable seat list for id and refreshes its idle
|
||||
// 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()
|
||||
defer c.mu.Unlock()
|
||||
e, ok := c.entries[id]
|
||||
if !ok {
|
||||
return nil, false
|
||||
return nil, nil, false
|
||||
}
|
||||
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-
|
||||
// games gauge can report counts by variant without inspecting engine internals.
|
||||
func (c *gameCache) put(id uuid.UUID, g *engine.Game, variant string) {
|
||||
// put stores g as the live game for id together with its seat list. variant labels the
|
||||
// entry so the active-games gauge can report counts by variant without inspecting engine
|
||||
// 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()
|
||||
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
|
||||
|
||||
@@ -68,10 +68,6 @@ func TestEmitMoveNotifiesActor(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
// 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,
|
||||
@@ -106,7 +102,4 @@ func TestEmitMoveAnnouncesGameOver(t *testing.T) {
|
||||
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())
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +94,8 @@ func TestGameCacheEviction(t *testing.T) {
|
||||
cur := time.Unix(1_700_000_000, 0)
|
||||
cache := newGameCache(time.Hour, func() time.Time { return cur })
|
||||
id := uuid.New()
|
||||
cache.put(id, nil, "scrabble_en")
|
||||
if _, ok := cache.get(id); !ok {
|
||||
cache.put(id, nil, "scrabble_en", nil)
|
||||
if _, _, ok := cache.get(id); !ok {
|
||||
t.Fatal("game must be resident after put")
|
||||
}
|
||||
cur = cur.Add(30 * time.Minute)
|
||||
@@ -104,7 +104,7 @@ func TestGameCacheEviction(t *testing.T) {
|
||||
if n := cache.sweep(); n != 1 {
|
||||
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")
|
||||
}
|
||||
if cache.size() != 0 {
|
||||
|
||||
@@ -287,12 +287,12 @@ func (svc *Service) Create(ctx context.Context, params CreateParams) (Game, erro
|
||||
if err := svc.store.CreateGame(ctx, ins, seats, seeding.draws); err != nil {
|
||||
return Game{}, err
|
||||
}
|
||||
svc.cache.put(id, g, params.Variant.String())
|
||||
svc.metrics.recordStarted(ctx, params.Variant, params.VsAI)
|
||||
created, err := 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)
|
||||
@@ -554,16 +554,6 @@ func (svc *Service) GameVariant(ctx context.Context, gameID uuid.UUID) (engine.V
|
||||
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
|
||||
// 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) {
|
||||
@@ -740,9 +730,6 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
||||
}
|
||||
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 {
|
||||
case StatusActive:
|
||||
// Honest-AI games suppress your_turn: the robot replies instantly, so a "your turn"
|
||||
@@ -757,7 +744,6 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
||||
}
|
||||
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.Language = lang
|
||||
intents = append(intents, yourTurn)
|
||||
}
|
||||
case StatusFinished:
|
||||
@@ -769,7 +755,6 @@ func (svc *Service) emitMove(ctx context.Context, post Game, rec engine.MoveReco
|
||||
continue
|
||||
}
|
||||
over := notify.GameOver(s.AccountID, post.ID, seatResult(post.Seats, s.Seat), scoreLine(post, s.Seat), summary)
|
||||
over.Language = lang
|
||||
intents = append(intents, over)
|
||||
}
|
||||
}
|
||||
@@ -905,26 +890,35 @@ func (svc *Service) timeoutGame(ctx context.Context, gameID uuid.UUID, now time.
|
||||
// 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.
|
||||
func (svc *Service) EvaluatePlay(ctx context.Context, gameID, accountID uuid.UUID, tiles []engine.TileRecord) (EvalResult, error) {
|
||||
pre, err := svc.store.GetGame(ctx, gameID)
|
||||
if err != nil {
|
||||
return EvalResult{}, err
|
||||
}
|
||||
if _, ok := pre.seatOf(accountID); !ok {
|
||||
return EvalResult{}, ErrNotAPlayer
|
||||
}
|
||||
if pre.Status == StatusFinished {
|
||||
return EvalResult{}, ErrFinished
|
||||
}
|
||||
|
||||
unlock := svc.locks.lock(gameID)
|
||||
defer unlock()
|
||||
g, err := svc.liveGame(ctx, pre)
|
||||
if err != nil {
|
||||
return EvalResult{}, err
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
return EvalResult{}, err
|
||||
}
|
||||
if pre.Status == StatusFinished {
|
||||
return EvalResult{}, ErrFinished
|
||||
}
|
||||
if g, err = svc.liveGame(ctx, pre); err != nil {
|
||||
return EvalResult{}, err
|
||||
}
|
||||
seats = pre.Seats
|
||||
}
|
||||
if !seatedIn(seats, accountID) {
|
||||
return EvalResult{}, ErrNotAPlayer
|
||||
}
|
||||
|
||||
validateStart := time.Now()
|
||||
rec, err := g.EvaluatePlay(tiles)
|
||||
svc.metrics.recordValidate(ctx, pre.Variant, validateStart)
|
||||
svc.metrics.recordValidate(ctx, g.Variant(), validateStart)
|
||||
if err != nil {
|
||||
if errors.Is(err, engine.ErrIllegalPlay) {
|
||||
return EvalResult{Valid: false}, nil
|
||||
@@ -1374,7 +1368,7 @@ func (svc *Service) ExportGCG(ctx context.Context, gameID uuid.UUID) (string, er
|
||||
// liveGame returns the live engine.Game for pre, rebuilding it from the journal
|
||||
// on a cache miss. Callers must hold the per-game lock.
|
||||
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
|
||||
}
|
||||
g, err := svc.replay(ctx, pre)
|
||||
@@ -1389,7 +1383,7 @@ func (svc *Service) liveGame(ctx context.Context, pre Game) (*engine.Game, error
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -355,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
|
||||
// ErrNotFound.
|
||||
func (s *Store) GetGame(ctx context.Context, id uuid.UUID) (Game, error) {
|
||||
gstmt := postgres.SELECT(table.Games.AllColumns).
|
||||
FROM(table.Games).
|
||||
// One round-trip: the game joined with its seats. A LEFT JOIN keeps a (would-be)
|
||||
// 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))).
|
||||
LIMIT(1)
|
||||
var grow model.Games
|
||||
if err := gstmt.QueryContext(ctx, s.db, &grow); err != nil {
|
||||
if errors.Is(err, qrm.ErrNoRows) {
|
||||
return Game{}, ErrNotFound
|
||||
}
|
||||
ORDER_BY(table.GamePlayers.Seat.ASC())
|
||||
var rows []struct {
|
||||
model.Games
|
||||
model.GamePlayers
|
||||
}
|
||||
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||
return Game{}, fmt.Errorf("game: get %s: %w", id, err)
|
||||
}
|
||||
|
||||
sstmt := postgres.SELECT(table.GamePlayers.AllColumns).
|
||||
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)
|
||||
if len(rows) == 0 {
|
||||
return Game{}, ErrNotFound
|
||||
}
|
||||
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
|
||||
|
||||
@@ -184,6 +184,18 @@ func (g Game) seatOf(accountID uuid.UUID) (int, bool) {
|
||||
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
|
||||
// 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
|
||||
|
||||
@@ -118,10 +118,13 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
store := account.NewStore(testDB)
|
||||
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 {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Error("created = false on first contact, want true")
|
||||
}
|
||||
if acc.PreferredLanguage != "ru" {
|
||||
t.Errorf("PreferredLanguage = %q, want ru", acc.PreferredLanguage)
|
||||
}
|
||||
@@ -133,10 +136,13 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
t.Fatalf("re-provision telegram: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Error("created = true on a repeat login, want false")
|
||||
}
|
||||
if again.ID != acc.ID {
|
||||
t.Errorf("re-provision id = %s, want %s", again.ID, acc.ID)
|
||||
}
|
||||
@@ -150,7 +156,7 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
// language CHECK.
|
||||
func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
||||
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 {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -159,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
|
||||
// is unflagged, FlagHighRate stamps it exactly once (a second sustained episode
|
||||
// never moves the timestamp), ClearHighRateFlag reverses it, and a re-flag after
|
||||
@@ -206,7 +172,7 @@ func TestServiceLanguageRoundTrip(t *testing.T) {
|
||||
func TestHighRateFlagRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
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 {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -262,7 +228,7 @@ func TestIdentityExternalID(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
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 {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -287,7 +253,7 @@ func TestIdentityExternalID(t *testing.T) {
|
||||
func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
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 {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -299,6 +265,7 @@ func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
||||
PreferredLanguage: "en",
|
||||
TimeZone: "UTC",
|
||||
NotificationsInAppOnly: false,
|
||||
VariantPreferences: []string{"erudit_ru"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update profile: %v", err)
|
||||
|
||||
@@ -222,7 +222,7 @@ func TestConsoleGameDetailRobotSchedule(t *testing.T) {
|
||||
func TestConsoleThrottledViewAndFlagClear(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
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 {
|
||||
t.Fatalf("provision: %v", err)
|
||||
}
|
||||
|
||||
@@ -256,7 +256,8 @@ func TestBannerSurvivesProfileUpdate(t *testing.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}`
|
||||
`"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())
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -134,12 +135,20 @@ func TestUpdateProfilePersists(t *testing.T) {
|
||||
store := account.NewStore(testDB)
|
||||
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{
|
||||
DisplayName: "Kaya",
|
||||
PreferredLanguage: "ru",
|
||||
TimeZone: "Europe/Moscow",
|
||||
BlockChat: true,
|
||||
BlockFriendRequests: true,
|
||||
VariantPreferences: []string{"scrabble_en", "erudit_ru"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update profile: %v", err)
|
||||
@@ -157,6 +166,10 @@ func TestUpdateProfilePersists(t *testing.T) {
|
||||
if reloaded.TimeZone != "Europe/Moscow" || !reloaded.BlockChat {
|
||||
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
|
||||
@@ -167,9 +180,10 @@ func TestUpdateProfileOffsetTimezone(t *testing.T) {
|
||||
acc := provisionAccount(t)
|
||||
|
||||
updated, err := store.UpdateProfile(ctx, acc, account.ProfileUpdate{
|
||||
DisplayName: "Kaya",
|
||||
PreferredLanguage: "en",
|
||||
TimeZone: "+03:00",
|
||||
DisplayName: "Kaya",
|
||||
PreferredLanguage: "en",
|
||||
TimeZone: "+03:00",
|
||||
VariantPreferences: []string{"erudit_ru"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update with offset timezone: %v", err)
|
||||
|
||||
@@ -145,48 +145,33 @@ func TestFeedbackReplyHiddenAfterNewMessage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackSnapshotsLanguages(t *testing.T) {
|
||||
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', service_language = 'ru' WHERE account_id = $1`, acc); err != nil {
|
||||
t.Fatalf("set languages: %v", err)
|
||||
`UPDATE backend.accounts SET preferred_language = 'en' WHERE account_id = $1`, acc); err != nil {
|
||||
t.Fatalf("set language: %v", err)
|
||||
}
|
||||
// A Telegram (connector) message snapshots both the interface language and the bot.
|
||||
// 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" || m.ChannelLang != "ru" {
|
||||
t.Fatalf("snapshot = lang %q / channel_lang %q, want en / ru", m.Lang, m.ChannelLang)
|
||||
} 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', service_language = 'en' WHERE account_id = $1`, acc); err != nil {
|
||||
t.Fatalf("change languages: %v", err)
|
||||
`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" || m.ChannelLang != "ru" {
|
||||
t.Fatalf("snapshot drifted after account change = lang %q / channel_lang %q", m.Lang, m.ChannelLang)
|
||||
}
|
||||
|
||||
// A non-connector channel records no bot language even when the account has one.
|
||||
acc2 := provisionAccount(t)
|
||||
if _, err := testDB.ExecContext(ctx,
|
||||
`UPDATE backend.accounts SET preferred_language = 'en', service_language = 'ru' WHERE account_id = $1`, acc2); err != nil {
|
||||
t.Fatalf("set languages 2: %v", err)
|
||||
}
|
||||
if err := svc.Submit(ctx, acc2, "from web", nil, "", "web", ""); err != nil {
|
||||
t.Fatalf("submit web: %v", err)
|
||||
}
|
||||
if m, err := svc.AdminGet(ctx, latestFeedbackID(t, svc, acc2)); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if m.Lang != "en" || m.ChannelLang != "" {
|
||||
t.Fatalf("web snapshot = lang %q / channel_lang %q, want en / empty", m.Lang, m.ChannelLang)
|
||||
} else if m.Lang != "en" {
|
||||
t.Fatalf("snapshot drifted after account change = lang %q, want en", m.Lang)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,10 +97,12 @@ func TestGameLimitGate(t *testing.T) {
|
||||
if !gamesListAtLimit(t, srv, human) {
|
||||
t.Fatalf("at %d games at_game_limit must be true", game.MaxActiveQuickGames)
|
||||
}
|
||||
if rec := userPost(t, srv, "/api/v1/user/lobby/enqueue", human, `{"variant":"scrabble_en"}`); rec.Code != http.StatusConflict || errorCode(t, rec) != "game_limit_reached" {
|
||||
// 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":"scrabble_en","invitee_ids":[%q]}`, opp.String())
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -543,6 +543,12 @@ func TestEvaluatePlayPreview(t *testing.T) {
|
||||
if bad.Valid {
|
||||
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
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestSeatNameFrozenAfterRename(t *testing.T) {
|
||||
|
||||
starter := provisionAccount(t)
|
||||
if _, err := accounts.UpdateProfile(ctx, starter, account.ProfileUpdate{
|
||||
DisplayName: "Original Name", PreferredLanguage: "en", TimeZone: "UTC",
|
||||
DisplayName: "Original Name", PreferredLanguage: "en", TimeZone: "UTC", VariantPreferences: []string{"erudit_ru"},
|
||||
}); err != nil {
|
||||
t.Fatalf("set name: %v", err)
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func TestSeatNameFrozenAfterRename(t *testing.T) {
|
||||
|
||||
// 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",
|
||||
DisplayName: "Renamed Player99", PreferredLanguage: "en", TimeZone: "UTC", VariantPreferences: []string{"erudit_ru"},
|
||||
}); err != nil {
|
||||
t.Fatalf("rename: %v", err)
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestFriendRequestRefusedByToggleAndBlock(t *testing.T) {
|
||||
|
||||
// Toggle: the addressee does not accept friend requests.
|
||||
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)
|
||||
}
|
||||
if err := svc.SendFriendRequest(ctx, a, b); !errors.Is(err, social.ErrRequestBlocked) {
|
||||
@@ -353,7 +353,7 @@ func TestChatPostListAndBlocks(t *testing.T) {
|
||||
if _, err := svc.PostMessage(ctx, other, seats2[0], "hi", ""); err != nil {
|
||||
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)
|
||||
}
|
||||
if msgs, _ := svc.Messages(ctx, other, seats2[1]); len(msgs) != 0 {
|
||||
@@ -588,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
|
||||
// (nudges excluded), the game / sender pins, the sender glob masks, and the source label.
|
||||
func TestAdminListMessages(t *testing.T) {
|
||||
|
||||
@@ -38,7 +38,7 @@ func TestSuspensionGate(t *testing.T) {
|
||||
Accounts: accounts,
|
||||
})
|
||||
|
||||
acc, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "ru", "", "Blocked")
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "ru", "", "Blocked")
|
||||
if err != nil {
|
||||
t.Fatalf("provision: %v", err)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestUserListFilter(t *testing.T) {
|
||||
st := account.NewStore(testDB)
|
||||
uniq := uuid.NewString()
|
||||
|
||||
human, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman")
|
||||
human, _, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman")
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
@@ -206,7 +206,6 @@ func (m *Matchmaker) announceOpponent(ctx context.Context, g game.Game, joinerID
|
||||
return
|
||||
}
|
||||
intent := notify.OpponentJoined(starter, g.ID, state)
|
||||
intent.Language = g.Variant.Language()
|
||||
m.pub.Publish(intent)
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,16 @@ func BannerChanged(userID uuid.UUID) Intent {
|
||||
return Notification(userID, NotifyBanner)
|
||||
}
|
||||
|
||||
// ChatAccessChanged signals that userID's eligibility to write in the moderated
|
||||
// Telegram discussion chat may have changed (an admin block/unblock, a chat_muted
|
||||
// grant/revoke, or a temporary block lapsing). It carries no payload: the gateway
|
||||
// resolves the user's Telegram identity and current eligibility and pushes the
|
||||
// resulting chat-gate command to the bot. Unlike the lobby notifications it is an
|
||||
// infra signal — a distinct top-level kind, never an out-of-app rendered message.
|
||||
func ChatAccessChanged(userID uuid.UUID) Intent {
|
||||
return Intent{UserID: userID, Kind: KindChatAccessChanged, EventID: eventID()}
|
||||
}
|
||||
|
||||
// eventID returns a best-effort correlation id for one emitted event.
|
||||
func eventID() string {
|
||||
if id, err := uuid.NewV7(); err == nil {
|
||||
|
||||
@@ -35,6 +35,13 @@ const (
|
||||
// KindGameOver announces a finished game to each seated player, driving the
|
||||
// out-of-app "game over" push.
|
||||
KindGameOver = "game_over"
|
||||
// KindChatAccessChanged signals that a player's eligibility to write in the
|
||||
// moderated Telegram discussion chat may have changed (an admin block or unblock,
|
||||
// a chat_muted grant or revoke, or a temporary block lapsing). It carries no
|
||||
// payload and is never fanned out to in-app clients: the gateway consumes it to
|
||||
// resolve the player's Telegram identity and current eligibility and push the
|
||||
// resulting chat-gate command to the bot.
|
||||
KindChatAccessChanged = "chat_access_changed"
|
||||
)
|
||||
|
||||
// Notification sub-kinds carried in a KindNotification event payload; the client
|
||||
@@ -82,11 +89,6 @@ type Intent struct {
|
||||
Kind string
|
||||
Payload []byte
|
||||
EventID string
|
||||
// Language routes an out-of-app push to a specific per-language bot: for a
|
||||
// game event it is the game's language ("en"/"ru"), so the notification comes from the
|
||||
// game's bot rather than the recipient's last-login bot. Empty falls back to the
|
||||
// recipient's service language at the gateway.
|
||||
Language string
|
||||
}
|
||||
|
||||
// Publisher accepts live-event intents. Implementations must be safe for
|
||||
|
||||
@@ -9,6 +9,7 @@ package model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/lib/pq"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -29,6 +30,6 @@ type Accounts struct {
|
||||
PaidAccount bool
|
||||
MergedInto *uuid.UUID
|
||||
MergedAt *time.Time
|
||||
ServiceLanguage *string
|
||||
FlaggedHighRateAt *time.Time
|
||||
VariantPreferences pq.StringArray
|
||||
}
|
||||
|
||||
@@ -20,12 +20,11 @@ type FeedbackMessages struct {
|
||||
AttachmentName *string
|
||||
SenderIP *string
|
||||
Channel string
|
||||
Lang *string
|
||||
ChannelLang *string
|
||||
ReadAt *time.Time
|
||||
ArchivedAt *time.Time
|
||||
ReplyBody *string
|
||||
RepliedAt *time.Time
|
||||
ReplyReadAt *time.Time
|
||||
CreatedAt time.Time
|
||||
Lang *string
|
||||
}
|
||||
|
||||
@@ -33,8 +33,8 @@ type accountsTable struct {
|
||||
PaidAccount postgres.ColumnBool
|
||||
MergedInto postgres.ColumnString
|
||||
MergedAt postgres.ColumnTimestampz
|
||||
ServiceLanguage postgres.ColumnString
|
||||
FlaggedHighRateAt postgres.ColumnTimestampz
|
||||
VariantPreferences postgres.ColumnStringArray
|
||||
|
||||
AllColumns postgres.ColumnList
|
||||
MutableColumns postgres.ColumnList
|
||||
@@ -92,11 +92,11 @@ func newAccountsTableImpl(schemaName, tableName, alias string) accountsTable {
|
||||
PaidAccountColumn = postgres.BoolColumn("paid_account")
|
||||
MergedIntoColumn = postgres.StringColumn("merged_into")
|
||||
MergedAtColumn = postgres.TimestampzColumn("merged_at")
|
||||
ServiceLanguageColumn = postgres.StringColumn("service_language")
|
||||
FlaggedHighRateAtColumn = postgres.TimestampzColumn("flagged_high_rate_at")
|
||||
allColumns = postgres.ColumnList{AccountIDColumn, DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn, MergedIntoColumn, MergedAtColumn, ServiceLanguageColumn, FlaggedHighRateAtColumn}
|
||||
mutableColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn, MergedIntoColumn, MergedAtColumn, ServiceLanguageColumn, FlaggedHighRateAtColumn}
|
||||
defaultColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn}
|
||||
VariantPreferencesColumn = postgres.StringArrayColumn("variant_preferences")
|
||||
allColumns = postgres.ColumnList{AccountIDColumn, DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn, MergedIntoColumn, MergedAtColumn, FlaggedHighRateAtColumn, VariantPreferencesColumn}
|
||||
mutableColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn, MergedIntoColumn, MergedAtColumn, FlaggedHighRateAtColumn, VariantPreferencesColumn}
|
||||
defaultColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn, AwayStartColumn, AwayEndColumn, HintBalanceColumn, IsGuestColumn, NotificationsInAppOnlyColumn, PaidAccountColumn, VariantPreferencesColumn}
|
||||
)
|
||||
|
||||
return accountsTable{
|
||||
@@ -119,8 +119,8 @@ func newAccountsTableImpl(schemaName, tableName, alias string) accountsTable {
|
||||
PaidAccount: PaidAccountColumn,
|
||||
MergedInto: MergedIntoColumn,
|
||||
MergedAt: MergedAtColumn,
|
||||
ServiceLanguage: ServiceLanguageColumn,
|
||||
FlaggedHighRateAt: FlaggedHighRateAtColumn,
|
||||
VariantPreferences: VariantPreferencesColumn,
|
||||
|
||||
AllColumns: allColumns,
|
||||
MutableColumns: mutableColumns,
|
||||
|
||||
@@ -24,14 +24,13 @@ type feedbackMessagesTable struct {
|
||||
AttachmentName postgres.ColumnString
|
||||
SenderIP postgres.ColumnString
|
||||
Channel postgres.ColumnString
|
||||
Lang postgres.ColumnString
|
||||
ChannelLang postgres.ColumnString
|
||||
ReadAt postgres.ColumnTimestampz
|
||||
ArchivedAt postgres.ColumnTimestampz
|
||||
ReplyBody postgres.ColumnString
|
||||
RepliedAt postgres.ColumnTimestampz
|
||||
ReplyReadAt postgres.ColumnTimestampz
|
||||
CreatedAt postgres.ColumnTimestampz
|
||||
Lang postgres.ColumnString
|
||||
|
||||
AllColumns postgres.ColumnList
|
||||
MutableColumns postgres.ColumnList
|
||||
@@ -80,16 +79,15 @@ func newFeedbackMessagesTableImpl(schemaName, tableName, alias string) feedbackM
|
||||
AttachmentNameColumn = postgres.StringColumn("attachment_name")
|
||||
SenderIPColumn = postgres.StringColumn("sender_ip")
|
||||
ChannelColumn = postgres.StringColumn("channel")
|
||||
LangColumn = postgres.StringColumn("lang")
|
||||
ChannelLangColumn = postgres.StringColumn("channel_lang")
|
||||
ReadAtColumn = postgres.TimestampzColumn("read_at")
|
||||
ArchivedAtColumn = postgres.TimestampzColumn("archived_at")
|
||||
ReplyBodyColumn = postgres.StringColumn("reply_body")
|
||||
RepliedAtColumn = postgres.TimestampzColumn("replied_at")
|
||||
ReplyReadAtColumn = postgres.TimestampzColumn("reply_read_at")
|
||||
CreatedAtColumn = postgres.TimestampzColumn("created_at")
|
||||
allColumns = postgres.ColumnList{MessageIDColumn, AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, LangColumn, ChannelLangColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn}
|
||||
mutableColumns = postgres.ColumnList{AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, LangColumn, ChannelLangColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn}
|
||||
LangColumn = postgres.StringColumn("lang")
|
||||
allColumns = postgres.ColumnList{MessageIDColumn, AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn}
|
||||
mutableColumns = postgres.ColumnList{AccountIDColumn, BodyColumn, AttachmentColumn, AttachmentNameColumn, SenderIPColumn, ChannelColumn, ReadAtColumn, ArchivedAtColumn, ReplyBodyColumn, RepliedAtColumn, ReplyReadAtColumn, CreatedAtColumn, LangColumn}
|
||||
defaultColumns = postgres.ColumnList{CreatedAtColumn}
|
||||
)
|
||||
|
||||
@@ -104,14 +102,13 @@ func newFeedbackMessagesTableImpl(schemaName, tableName, alias string) feedbackM
|
||||
AttachmentName: AttachmentNameColumn,
|
||||
SenderIP: SenderIPColumn,
|
||||
Channel: ChannelColumn,
|
||||
Lang: LangColumn,
|
||||
ChannelLang: ChannelLangColumn,
|
||||
ReadAt: ReadAtColumn,
|
||||
ArchivedAt: ArchivedAtColumn,
|
||||
ReplyBody: ReplyBodyColumn,
|
||||
RepliedAt: RepliedAtColumn,
|
||||
ReplyReadAt: ReplyReadAtColumn,
|
||||
CreatedAt: CreatedAtColumn,
|
||||
Lang: LangColumn,
|
||||
|
||||
AllColumns: allColumns,
|
||||
MutableColumns: mutableColumns,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Allow end_reason = 'aborted': a game whose journal can no longer be reconstructed (a
|
||||
-- recorded move became illegal under tightened rules) is closed as a draw rather than left
|
||||
-- unopenable. See engine.EndAborted and Service.voidGame.
|
||||
SET search_path = backend, pg_catalog;
|
||||
ALTER TABLE games DROP CONSTRAINT games_end_reason_chk;
|
||||
ALTER TABLE games ADD CONSTRAINT games_end_reason_chk CHECK (
|
||||
end_reason IS NULL OR end_reason IN ('out_of_tiles', 'scoreless', 'resign', 'timeout', 'aborted')
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
ALTER TABLE games DROP CONSTRAINT games_end_reason_chk;
|
||||
ALTER TABLE games ADD CONSTRAINT games_end_reason_chk CHECK (
|
||||
end_reason IS NULL OR end_reason IN ('out_of_tiles', 'scoreless', 'resign', 'timeout')
|
||||
);
|
||||
@@ -1,45 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Manual account blocking ("suspension"), the operator's hard counterpart to the soft,
|
||||
-- reversible accounts.flagged_high_rate_at marker. Named "suspension" throughout the schema
|
||||
-- and Go to stay distinct from the peer-to-peer `blocks` table (one player muting another);
|
||||
-- the wire/UI vocabulary the player sees is "blocked". A suspension forces the player to
|
||||
-- forfeit every active game and replaces their whole UI with a terminal "blocked" screen until
|
||||
-- it is lifted or (for a temporary one) expires. See docs/ARCHITECTURE.md §12.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
-- The operator-editable reason picklist, one row per reason with its English and Russian text.
|
||||
-- A suspension snapshots the chosen text (account_suspensions.reason_en/ru), so editing or
|
||||
-- deleting a reason here never changes or breaks a reason already shown to a blocked player.
|
||||
CREATE TABLE suspension_reasons (
|
||||
reason_id uuid PRIMARY KEY,
|
||||
text_en text NOT NULL,
|
||||
text_ru text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- The block history: one row per block. blocked_until is NULL for a permanent block and the
|
||||
-- expiry instant for a temporary one; lifted_at is stamped when an operator unblocks early.
|
||||
-- reason_en/reason_ru are the text snapshot taken at block time (NULL when no reason was
|
||||
-- cited); reason_id keeps a loose link to the picklist entry for later analytics and is nulled
|
||||
-- if that entry is deleted (the snapshot remains the source of truth shown to the player). An
|
||||
-- account is currently blocked when its newest row has lifted_at IS NULL AND (blocked_until IS
|
||||
-- NULL OR blocked_until > now()).
|
||||
CREATE TABLE account_suspensions (
|
||||
suspension_id uuid PRIMARY KEY,
|
||||
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
blocked_at timestamptz NOT NULL DEFAULT now(),
|
||||
blocked_until timestamptz,
|
||||
reason_en text,
|
||||
reason_ru text,
|
||||
reason_id uuid REFERENCES suspension_reasons (reason_id) ON DELETE SET NULL,
|
||||
lifted_at timestamptz
|
||||
);
|
||||
-- The enforcement gate looks up the newest suspension for an account on every authenticated
|
||||
-- request; this index serves that "latest by account" probe.
|
||||
CREATE INDEX account_suspensions_account_idx ON account_suspensions (account_id, blocked_at DESC);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE IF EXISTS account_suspensions;
|
||||
DROP TABLE IF EXISTS suspension_reasons;
|
||||
@@ -1,55 +0,0 @@
|
||||
-- +goose Up
|
||||
-- User feedback ("Обратная связь"): a flat list of messages a registered player sends to the
|
||||
-- operators from Settings -> Info, each with an optional single attachment, plus the operator's
|
||||
-- inline reply shown back to the player. Distinct from the in-game chat_messages (peer-to-peer)
|
||||
-- and from the out-of-app Telegram messages. Also introduces account_roles, the project's first
|
||||
-- per-account role table, replacing per-feature boolean flags. See docs/ARCHITECTURE.md.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
-- One feedback message. read_at marks "the operator has dealt with this" (set by every console
|
||||
-- action: read / reply / archive; never by merely opening the detail). The anti-spam gate forbids
|
||||
-- a new submission while the player has any read_at IS NULL message. archived_at files a handled
|
||||
-- message away. The reply lives on the same row: reply_body/replied_at are stamped when the
|
||||
-- operator answers; reply_read_at is stamped when the player's app first fetches the reply for
|
||||
-- display ("delivered = read"), and the reply is hidden from the player one week after that.
|
||||
-- attachment is the raw bytes (capped at 1,000,000 in Go); attachment_name carries the original
|
||||
-- file name (its extension drives the safe content-type at serve time). sender_ip is the
|
||||
-- gateway-forwarded client IP (validated, like chat); channel is the submitting platform
|
||||
-- (telegram/ios/android/web, validated in Go). The sender's interface/bot language snapshots
|
||||
-- (lang, channel_lang) are added additively in 00005.
|
||||
CREATE TABLE feedback_messages (
|
||||
message_id uuid PRIMARY KEY,
|
||||
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
body text NOT NULL,
|
||||
attachment bytea,
|
||||
attachment_name text,
|
||||
sender_ip text,
|
||||
channel text NOT NULL,
|
||||
read_at timestamptz,
|
||||
archived_at timestamptz,
|
||||
reply_body text,
|
||||
replied_at timestamptz,
|
||||
reply_read_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
-- The per-player probes (anti-spam "has unread", "latest message", "latest reply") and the
|
||||
-- console's user-scoped search all look an account up newest-first.
|
||||
CREATE INDEX feedback_messages_account_idx ON feedback_messages (account_id, created_at DESC);
|
||||
-- The console queue lists messages newest-first across all accounts.
|
||||
CREATE INDEX feedback_messages_created_idx ON feedback_messages (created_at DESC);
|
||||
|
||||
-- Named per-account roles. A reusable replacement for per-feature boolean flags: the first role,
|
||||
-- 'feedback_banned', forbids only feedback submission (not the whole account, unlike a
|
||||
-- suspension). Roles are validated in Go (no CHECK here) so new ones need no migration. Granted
|
||||
-- from the feedback console (the "block" checkbox on delete) and granted/revoked from /users.
|
||||
CREATE TABLE account_roles (
|
||||
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
granted_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (account_id, role)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE IF EXISTS account_roles;
|
||||
DROP TABLE IF EXISTS feedback_messages;
|
||||
@@ -1,15 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Snapshot the sender's languages on each feedback message, taken at submit time so the
|
||||
-- operator console shows the state as it was, not the account's current settings (the same
|
||||
-- snapshot discipline as a suspension's reason). lang is the sender's interface language;
|
||||
-- channel_lang is the connector bot language (en/ru) when the message arrived through an
|
||||
-- external connector (Telegram), else NULL. Additive over 00004 so it applies forward-safe.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
ALTER TABLE feedback_messages ADD COLUMN lang text;
|
||||
ALTER TABLE feedback_messages ADD COLUMN channel_lang text;
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
ALTER TABLE feedback_messages DROP COLUMN IF EXISTS channel_lang;
|
||||
ALTER TABLE feedback_messages DROP COLUMN IF EXISTS lang;
|
||||
@@ -1,86 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Server-driven advertising banner ("advertising network"): operator-managed campaigns rotated in
|
||||
-- the client's one-line announcement strip. A campaign is one placement order with a show weight
|
||||
-- (percent); simultaneously active campaigns compete for shows in proportion to their weights. The
|
||||
-- single perpetual default campaign fills the unsold remainder up to 100%. Each campaign carries
|
||||
-- one or more bilingual messages (en + ru, both mandatory), shown by the viewer's bot (service)
|
||||
-- language. Display timings are global (one settings row). Eligibility (who sees a banner at all)
|
||||
-- reuses account fields + the no_banner role, so it needs no schema here. See docs/ARCHITECTURE.md
|
||||
-- and internal/ads.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
-- One advertising campaign = one placement order. weight is the show percentage (1..100). is_default
|
||||
-- marks the single perpetual house campaign that fills the remainder up to 100% and is never deleted;
|
||||
-- it has no validity window (its stored weight is nominal — the rotation derives its effective weight
|
||||
-- as max(0, 100 - sum of active timed weights)). A time-limited campaign is active while now() lies in
|
||||
-- [starts_at, ends_at] (a null bound is open-ended on that side). enabled toggles a campaign without
|
||||
-- deleting it.
|
||||
CREATE TABLE ad_campaigns (
|
||||
campaign_id uuid PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
weight integer NOT NULL,
|
||||
is_default boolean NOT NULL DEFAULT false,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
starts_at timestamptz,
|
||||
ends_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT ad_campaigns_weight_chk CHECK (weight BETWEEN 1 AND 100),
|
||||
-- The default campaign is perpetual (no window).
|
||||
CONSTRAINT ad_campaigns_default_window_chk CHECK (NOT is_default OR (starts_at IS NULL AND ends_at IS NULL)),
|
||||
-- A closed window must not be inverted.
|
||||
CONSTRAINT ad_campaigns_window_chk CHECK (starts_at IS NULL OR ends_at IS NULL OR starts_at <= ends_at)
|
||||
);
|
||||
-- At most one default campaign.
|
||||
CREATE UNIQUE INDEX ad_campaigns_default_idx ON ad_campaigns (is_default) WHERE is_default;
|
||||
|
||||
-- One bilingual message of a campaign. Both languages 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 when the campaign wins a display slot). body_* is minimal markdown (text + links).
|
||||
CREATE TABLE ad_messages (
|
||||
message_id uuid PRIMARY KEY,
|
||||
campaign_id uuid NOT NULL REFERENCES ad_campaigns (campaign_id) ON DELETE CASCADE,
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
body_en text NOT NULL,
|
||||
body_ru text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
-- Messages of a campaign are read in display order.
|
||||
CREATE INDEX ad_messages_campaign_idx ON ad_messages (campaign_id, position);
|
||||
|
||||
-- Global banner display timings, a single row (id is always TRUE). The client rotator reads these:
|
||||
-- hold_ms is how long one message shows; edge_pause_ms and scroll_px_per_sec drive the scroll of a
|
||||
-- message wider than the strip; the transition between messages is fade_out_ms -> gap_ms -> fade_in_ms.
|
||||
-- All are clamped in Go on update.
|
||||
CREATE TABLE ad_settings (
|
||||
id boolean PRIMARY KEY DEFAULT true,
|
||||
hold_ms integer NOT NULL,
|
||||
edge_pause_ms integer NOT NULL,
|
||||
scroll_px_per_sec integer NOT NULL,
|
||||
fade_out_ms integer NOT NULL,
|
||||
gap_ms integer NOT NULL,
|
||||
fade_in_ms integer NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT ad_settings_singleton_chk CHECK (id)
|
||||
);
|
||||
|
||||
-- Seed the perpetual default campaign with one bilingual house message, and the default timings
|
||||
-- (the previous hardcoded UI defaults plus the new fade sequence). Fixed UUIDs keep the seed
|
||||
-- deterministic across environments.
|
||||
INSERT INTO ad_campaigns (campaign_id, name, weight, is_default, enabled)
|
||||
VALUES ('00000000-0000-0000-0000-0000000000ad', 'Default (house)', 100, true, true);
|
||||
INSERT INTO ad_messages (message_id, campaign_id, position, body_en, body_ru)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-0000000000a1', '00000000-0000-0000-0000-0000000000ad', 0,
|
||||
'Tip: a play using all 7 tiles earns a +50 bonus.',
|
||||
'Совет: ход всеми 7 фишками приносит бонус +50 очков.'
|
||||
);
|
||||
INSERT INTO ad_settings (id, hold_ms, edge_pause_ms, scroll_px_per_sec, fade_out_ms, gap_ms, fade_in_ms)
|
||||
VALUES (true, 60000, 5000, 40, 1000, 250, 1000);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE IF EXISTS ad_settings;
|
||||
DROP TABLE IF EXISTS ad_messages;
|
||||
DROP TABLE IF EXISTS ad_campaigns;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
-- A per-seat snapshot of the player's display name, captured when the seat is taken:
|
||||
-- the human's then-current display name, or a disguised robot's freshly composed
|
||||
-- per-game name. Storing the name on the seat (rather than always reading the account)
|
||||
-- freezes what the opponent sees for the life of the game — a later rename no longer
|
||||
-- rewrites past games — and lets the small robot pool present an ever-changing crowd of
|
||||
-- differently named opponents. An empty value means "no snapshot": the reader falls back
|
||||
-- to the account's current display name (legacy rows / pre-migration games). See
|
||||
-- docs/ARCHITECTURE.md §7.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
ALTER TABLE game_players ADD COLUMN display_name text NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
ALTER TABLE game_players DROP COLUMN display_name;
|
||||
@@ -1,20 +0,0 @@
|
||||
-- +goose Up
|
||||
-- A per-message bitmask of the seats that have NOT yet read this chat entry: bit i is
|
||||
-- set while seat i still has the message unread, and is cleared when that seat reads it
|
||||
-- (opens the move history / chat, or — for a nudge — takes its move). A text message
|
||||
-- starts with the bits of every seated recipient except the sender; a nudge starts with
|
||||
-- only the awaited player's bit. The mask is inverted so "anything unread" is a plain
|
||||
-- `unread_seats <> 0`, which the lobby badge, the admin filter and the unread gauge all
|
||||
-- use. The read time itself is not retained. See docs/ARCHITECTURE.md §8 (Read receipts).
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
ALTER TABLE chat_messages ADD COLUMN unread_seats smallint NOT NULL DEFAULT 0;
|
||||
|
||||
-- Partial index serving the unread scans (per-viewer lobby lookup, admin unread filter,
|
||||
-- the unread-count gauge): only the comparatively few still-unread rows are indexed.
|
||||
CREATE INDEX chat_messages_unread_idx ON chat_messages (game_id) WHERE unread_seats <> 0;
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP INDEX chat_messages_unread_idx;
|
||||
ALTER TABLE chat_messages DROP COLUMN unread_seats;
|
||||
@@ -1,25 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Per-account, per-variant best single move: the highest-scoring play the account has
|
||||
-- ever made in each game variant. It exists so the statistics screen can show the word
|
||||
-- itself broken down by variant, not just the dimensionless aggregate
|
||||
-- account_stats.max_word_points. tiles is the move's main word as an ordered JSON array of
|
||||
-- {letter, value, blank} objects (value 0 and blank true for a wildcard), so the client
|
||||
-- renders it as game tiles without needing the variant's alphabet table. score is the
|
||||
-- play's total points (every word it formed plus the all-tiles bonus), matching
|
||||
-- max_word_points. A row is replaced only by a strictly higher-scoring play. It is written
|
||||
-- at game finish alongside account_stats; guest and honest-AI games never record statistics,
|
||||
-- so they never write here. See docs/ARCHITECTURE.md §9.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
CREATE TABLE account_best_move (
|
||||
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
variant text NOT NULL,
|
||||
score integer NOT NULL,
|
||||
tiles jsonb NOT NULL,
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (account_id, variant)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE IF EXISTS account_best_move;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
-- account_stats gains two lifetime counters for the player's statistics screen: moves — the
|
||||
-- player's plays (tile placements; passes and exchanges do not count) — and hints_used — every
|
||||
-- hint the player took (the free per-game allowance plus the wallet-charged ones). Both are
|
||||
-- summed at game finish over the same games that feed the rest of account_stats (durable
|
||||
-- non-guest accounts; honest-AI games are skipped), so the screen can show the "hint share"
|
||||
-- = hints_used / moves. See docs/ARCHITECTURE.md §9.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
ALTER TABLE account_stats ADD COLUMN moves integer NOT NULL DEFAULT 0;
|
||||
ALTER TABLE account_stats ADD COLUMN hints_used integer NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
ALTER TABLE account_stats DROP COLUMN hints_used;
|
||||
ALTER TABLE account_stats DROP COLUMN moves;
|
||||
@@ -1,27 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Per-game blocks of a disguised-robot opponent. A disguised robot is a shared pool
|
||||
-- account reused across games under different per-game names, so it must never go into
|
||||
-- `blocks` (that would make the same robot look blocked in the blocker's other games under
|
||||
-- other names, leaking that it is a bot, and show its pool name instead of the one seen).
|
||||
-- Each such block is recorded here against the specific game + seat, snapshotting the name
|
||||
-- the player saw, so the blocked list shows it as a distinct personality and the in-game
|
||||
-- card re-marks that one seat. The real robot account is never blocked, so the matchmaker
|
||||
-- leaves robots free. Unblocking deletes the row.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
CREATE TABLE robot_blocks (
|
||||
id uuid PRIMARY KEY,
|
||||
blocker_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
game_id uuid NOT NULL REFERENCES games (game_id) ON DELETE CASCADE,
|
||||
seat smallint NOT NULL,
|
||||
robot_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
display_name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (blocker_id, game_id, seat)
|
||||
);
|
||||
|
||||
CREATE INDEX robot_blocks_blocker_idx ON robot_blocks (blocker_id);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE robot_blocks;
|
||||
@@ -1,28 +0,0 @@
|
||||
-- +goose Up
|
||||
-- Per-game friend requests sent to a disguised-robot opponent. A disguised robot is a
|
||||
-- shared pool account reused across games under different per-game names, so such a
|
||||
-- request must never go into `friendships` (that would befriend/await the shared robot
|
||||
-- account, leak that it is a bot across the requester's other games under other names,
|
||||
-- and pin the in-game "request sent" state to the shared account instead of this seat).
|
||||
-- Each request is recorded here against the specific game + seat, snapshotting the name
|
||||
-- the player saw, so the in-game scoreboard can re-mark that one seat as already
|
||||
-- requested. The robot ignores it (it never becomes a friendship); a background reaper
|
||||
-- deletes a row once its game has been finished for more than the retention window.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
CREATE TABLE robot_friend_requests (
|
||||
id uuid PRIMARY KEY,
|
||||
requester_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
game_id uuid NOT NULL REFERENCES games (game_id) ON DELETE CASCADE,
|
||||
seat smallint NOT NULL,
|
||||
robot_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
display_name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (requester_id, game_id, seat)
|
||||
);
|
||||
|
||||
CREATE INDEX robot_friend_requests_requester_idx ON robot_friend_requests (requester_id);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE robot_friend_requests;
|
||||
@@ -1,31 +0,0 @@
|
||||
-- +goose Up
|
||||
-- The first-move draw (docs/ARCHITECTURE.md §6): before a game starts, each seated
|
||||
-- player draws one tile from the bag and the tile closest to "A" decides who moves
|
||||
-- first (a blank supersedes all letters); players tied for the best tile re-draw
|
||||
-- until a single leader remains. Each draw uses fresh entropy (not the game's
|
||||
-- deterministic bag seed), so this record — not a seed — is the only account of how
|
||||
-- the order was chosen. It is kept for tournaments, where the draw becomes a manual
|
||||
-- per-tile call. The record is dictionary-independent: the decoded letter, the blank
|
||||
-- flag and the numeric draw rank describe each draw without any alphabet table. The
|
||||
-- winner is reflected as seat 0 in game_players, so no order column is duplicated
|
||||
-- here. In auto-match the opponent is unknown at draw time (the draw runs against a
|
||||
-- synthetic placeholder when the game opens), so their draw rows carry a NULL account_id,
|
||||
-- back-filled when a real opponent joins. Hidden from players for now; surfaced only in the
|
||||
-- admin console.
|
||||
SET search_path = backend, pg_catalog;
|
||||
|
||||
CREATE TABLE game_setup_draws (
|
||||
game_id uuid NOT NULL REFERENCES games (game_id) ON DELETE CASCADE,
|
||||
round smallint NOT NULL,
|
||||
pick_no smallint NOT NULL,
|
||||
account_id uuid REFERENCES accounts (account_id) ON DELETE CASCADE,
|
||||
letter text NOT NULL,
|
||||
is_blank boolean NOT NULL DEFAULT false,
|
||||
draw_rank smallint NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (game_id, round, pick_no)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
SET search_path = backend, pg_catalog;
|
||||
DROP TABLE game_setup_draws;
|
||||
@@ -54,11 +54,10 @@ func (s *Service) Subscribe(req *pushv1.SubscribeRequest, stream grpc.ServerStre
|
||||
return nil
|
||||
}
|
||||
ev := &pushv1.Event{
|
||||
UserId: in.UserID.String(),
|
||||
Kind: in.Kind,
|
||||
Payload: in.Payload,
|
||||
EventId: in.EventID,
|
||||
Language: in.Language,
|
||||
UserId: in.UserID.String(),
|
||||
Kind: in.Kind,
|
||||
Payload: in.Payload,
|
||||
EventId: in.EventID,
|
||||
}
|
||||
if err := stream.Send(ev); err != nil {
|
||||
return err
|
||||
|
||||
@@ -88,13 +88,9 @@ func (s *Server) bannerFor(ctx context.Context, acc account.Account) *bannerDTO
|
||||
}
|
||||
}
|
||||
|
||||
// bannerLang resolves the message language for a viewer: the bot (service)
|
||||
// language they last signed in through, falling back to the interface language
|
||||
// and then English.
|
||||
// bannerLang resolves the message language for a viewer: their interface language
|
||||
// (Russian, or English by default).
|
||||
func bannerLang(acc account.Account) string {
|
||||
if acc.ServiceLanguage == "ru" || acc.ServiceLanguage == "en" {
|
||||
return acc.ServiceLanguage
|
||||
}
|
||||
if acc.PreferredLanguage == "ru" {
|
||||
return "ru"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/notify"
|
||||
)
|
||||
|
||||
// chatAccessRequest is the gateway's chat write-eligibility query, addressed either
|
||||
// by Telegram identity (ExternalID — the join path, when the bot sees a user enter
|
||||
// the chat) or by account id (UserID — the change path, resolving an emitted
|
||||
// chat-access-changed event). Exactly one field is set.
|
||||
type chatAccessRequest struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
// chatAccessResponse is the resolved eligibility. ExternalID echoes the account's
|
||||
// Telegram identity (empty when it has none — the gateway then has nothing to gate);
|
||||
// Registered reports whether the lookup found an account at all; Eligible is the
|
||||
// final gate the bot applies (registered and neither admin-suspended nor chat-muted).
|
||||
type chatAccessResponse struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
Registered bool `json:"registered"`
|
||||
Eligible bool `json:"eligible"`
|
||||
}
|
||||
|
||||
// handleChatAccess resolves whether a Telegram user may write in the moderated
|
||||
// discussion chat. It is gateway-internal: the gateway's bot-link serves the bot's
|
||||
// join-time query (by external_id) and resolves an emitted chat-access-changed event
|
||||
// (by user_id) through it.
|
||||
func (s *Server) handleChatAccess(c *gin.Context) {
|
||||
var req chatAccessRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
abortBadRequest(c, "invalid body")
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case req.ExternalID != "":
|
||||
s.respondChatAccessByExternalID(c, req.ExternalID)
|
||||
case req.UserID != "":
|
||||
s.respondChatAccessByUserID(c, req.UserID)
|
||||
default:
|
||||
abortBadRequest(c, "external_id or user_id required")
|
||||
}
|
||||
}
|
||||
|
||||
// respondChatAccessByExternalID answers the join-path query: an unknown identity is
|
||||
// reported unregistered (and left muted); a known one carries its current eligibility.
|
||||
func (s *Server) respondChatAccessByExternalID(c *gin.Context, externalID string) {
|
||||
ctx := c.Request.Context()
|
||||
resp := chatAccessResponse{ExternalID: externalID}
|
||||
acc, err := s.accounts.AccountByIdentity(ctx, account.KindTelegram, externalID)
|
||||
if errors.Is(err, account.ErrNotFound) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
resp.Registered = true
|
||||
eligible, err := s.chatEligible(ctx, acc.ID)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
resp.Eligible = eligible
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// respondChatAccessByUserID answers the change-path query: an account with no
|
||||
// Telegram identity carries an empty external_id (nothing for the gateway to gate);
|
||||
// otherwise it carries the identity and the current eligibility.
|
||||
func (s *Server) respondChatAccessByUserID(c *gin.Context, raw string) {
|
||||
ctx := c.Request.Context()
|
||||
uid, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
abortBadRequest(c, "invalid user_id")
|
||||
return
|
||||
}
|
||||
var resp chatAccessResponse
|
||||
ext, err := s.accounts.IdentityExternalID(ctx, uid, account.KindTelegram)
|
||||
if errors.Is(err, account.ErrNotFound) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
resp.ExternalID = ext
|
||||
resp.Registered = true
|
||||
eligible, err := s.chatEligible(ctx, uid)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
resp.Eligible = eligible
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// chatEligible reports whether the account may write in the moderated discussion
|
||||
// chat: not currently admin-suspended and not holding the chat_muted role. A
|
||||
// suspension dominates — it mutes regardless of the role. Registration is established
|
||||
// by the caller's identity lookup.
|
||||
func (s *Server) chatEligible(ctx context.Context, accountID uuid.UUID) (bool, error) {
|
||||
if _, blocked, err := s.accounts.CurrentSuspension(ctx, accountID); err != nil {
|
||||
return false, err
|
||||
} else if blocked {
|
||||
return false, nil
|
||||
}
|
||||
muted, err := s.accounts.HasRole(ctx, accountID, account.RoleChatMuted)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return !muted, nil
|
||||
}
|
||||
|
||||
// publishChatAccessChange emits the chat-access-changed signal for the account, so
|
||||
// the gateway re-resolves the player's chat eligibility and pushes the chat-gate
|
||||
// command to the bot. Best-effort (notify.Nop when no notifier is wired).
|
||||
func (s *Server) publishChatAccessChange(id uuid.UUID) {
|
||||
s.notifier.Publish(notify.ChatAccessChanged(id))
|
||||
}
|
||||
@@ -16,11 +16,10 @@ import (
|
||||
|
||||
// sessionResponse is the credential returned by every auth endpoint.
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"user_id"`
|
||||
IsGuest bool `json:"is_guest"`
|
||||
DisplayName string `json:"display_name"`
|
||||
ServiceLanguage string `json:"service_language"`
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"user_id"`
|
||||
IsGuest bool `json:"is_guest"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
// okResponse is a simple success acknowledgement.
|
||||
@@ -49,6 +48,10 @@ type profileResponse struct {
|
||||
BlockFriendRequests bool `json:"block_friend_requests"`
|
||||
IsGuest bool `json:"is_guest"`
|
||||
NotificationsInAppOnly bool `json:"notifications_in_app_only"`
|
||||
// VariantPreferences is the set of game variants the player allows themselves to
|
||||
// be matched into (engine.Variant stable labels), Erudit-first. It gates the New
|
||||
// Game picker and the matchmaker; never empty.
|
||||
VariantPreferences []string `json:"variant_preferences"`
|
||||
// Banner is the advertising-banner block: present only for a viewer eligible to
|
||||
// see the banner (a free account with an empty hint wallet and without the
|
||||
// no_banner role), absent otherwise. See banner.go.
|
||||
@@ -177,11 +180,10 @@ type errorBody struct {
|
||||
// sessionResponseFor builds the credential payload for a minted session.
|
||||
func sessionResponseFor(token string, acc account.Account) sessionResponse {
|
||||
return sessionResponse{
|
||||
Token: token,
|
||||
UserID: acc.ID.String(),
|
||||
IsGuest: acc.IsGuest,
|
||||
DisplayName: acc.DisplayName,
|
||||
ServiceLanguage: acc.ServiceLanguage,
|
||||
Token: token,
|
||||
UserID: acc.ID.String(),
|
||||
IsGuest: acc.IsGuest,
|
||||
DisplayName: acc.DisplayName,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +201,7 @@ func profileResponseFor(acc account.Account) profileResponse {
|
||||
BlockFriendRequests: acc.BlockFriendRequests,
|
||||
IsGuest: acc.IsGuest,
|
||||
NotificationsInAppOnly: acc.NotificationsInAppOnly,
|
||||
VariantPreferences: acc.VariantPreferences,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,11 +37,23 @@ func (s *Server) registerRoutes() {
|
||||
// before delivering an out-of-app notification.
|
||||
in.POST("/push-target", s.handlePushTarget)
|
||||
}
|
||||
if s.accounts != nil {
|
||||
// Moderated-chat write eligibility for the Telegram bot: resolve a Telegram
|
||||
// identity (the bot's join-time query) or an account id (a chat-access-changed
|
||||
// event) to whether the user may write in the discussion chat. It needs only the
|
||||
// account store, not the session service, so it registers independently.
|
||||
s.internal.POST("/chat-access", s.handleChatAccess)
|
||||
}
|
||||
if s.ratewatch != nil {
|
||||
// The gateway's periodic rate-limiter rejection summary: feeds the
|
||||
// admin console's throttled view and the high-rate auto-flag.
|
||||
s.internal.POST("/ratelimit/report", s.handleRateLimitReport)
|
||||
}
|
||||
if s.banview != nil {
|
||||
// The gateway's periodic active-ban sync: feeds the admin console's
|
||||
// active-bans panel and returns the operator's pending unbans.
|
||||
s.internal.POST("/bans/sync", s.handleBanSync)
|
||||
}
|
||||
u := s.user
|
||||
if s.accounts != nil {
|
||||
u.GET("/profile", s.handleProfile)
|
||||
|
||||
@@ -18,14 +18,15 @@ import (
|
||||
// updateProfileRequest is the full editable profile. away_start/away_end are
|
||||
// "HH:MM" local-time bounds of the daily away window.
|
||||
type updateProfileRequest struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
AwayStart string `json:"away_start"`
|
||||
AwayEnd string `json:"away_end"`
|
||||
BlockChat bool `json:"block_chat"`
|
||||
BlockFriendRequests bool `json:"block_friend_requests"`
|
||||
NotificationsInAppOnly bool `json:"notifications_in_app_only"`
|
||||
DisplayName string `json:"display_name"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
AwayStart string `json:"away_start"`
|
||||
AwayEnd string `json:"away_end"`
|
||||
BlockChat bool `json:"block_chat"`
|
||||
BlockFriendRequests bool `json:"block_friend_requests"`
|
||||
NotificationsInAppOnly bool `json:"notifications_in_app_only"`
|
||||
VariantPreferences []string `json:"variant_preferences"`
|
||||
}
|
||||
|
||||
// statsDTO is a durable account's lifetime statistics (the derived games-played and
|
||||
@@ -92,6 +93,7 @@ func (s *Server) handleUpdateProfile(c *gin.Context) {
|
||||
BlockChat: req.BlockChat,
|
||||
BlockFriendRequests: req.BlockFriendRequests,
|
||||
NotificationsInAppOnly: req.NotificationsInAppOnly,
|
||||
VariantPreferences: req.VariantPreferences,
|
||||
})
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
|
||||
@@ -66,6 +66,7 @@ func (s *Server) registerConsole(router *gin.Engine) {
|
||||
gm.POST("/reasons/:id/update", s.consoleUpdateReason)
|
||||
gm.POST("/reasons/:id/delete", s.consoleDeleteReason)
|
||||
gm.GET("/throttled", s.consoleThrottled)
|
||||
gm.POST("/bans/unban", s.consoleUnban)
|
||||
gm.GET("/games", s.consoleGames)
|
||||
gm.GET("/games/:id", s.consoleGameDetail)
|
||||
gm.GET("/complaints", s.consoleComplaints)
|
||||
@@ -424,7 +425,6 @@ func (s *Server) consoleUserMessage(c *gin.Context) {
|
||||
}
|
||||
back := "/_gm/users/" + id.String()
|
||||
text := trimForm(c, "text")
|
||||
language := trimForm(c, "language")
|
||||
switch {
|
||||
case text == "":
|
||||
s.renderConsoleMessage(c, "Nothing sent", "the message was empty", back)
|
||||
@@ -436,14 +436,14 @@ func (s *Server) consoleUserMessage(c *gin.Context) {
|
||||
s.renderConsoleMessage(c, "No Telegram", "this account has no Telegram identity", back)
|
||||
return
|
||||
}
|
||||
delivered, err := s.connector.SendToUser(ctx, ext, text, language)
|
||||
delivered, err := s.connector.SendToUser(ctx, ext, text)
|
||||
if err != nil {
|
||||
s.consoleError(c, err)
|
||||
return
|
||||
}
|
||||
body := "message delivered"
|
||||
if !delivered {
|
||||
body = "not delivered (the user may not have started that bot)"
|
||||
body = "not delivered (the user may not have started the bot)"
|
||||
}
|
||||
s.renderConsoleMessage(c, "Sent", body, back)
|
||||
}
|
||||
@@ -833,21 +833,20 @@ func (s *Server) consoleBroadcast(c *gin.Context) {
|
||||
// consolePostBroadcast posts an operator message to the connector's game channel.
|
||||
func (s *Server) consolePostBroadcast(c *gin.Context) {
|
||||
text := trimForm(c, "text")
|
||||
language := trimForm(c, "language")
|
||||
switch {
|
||||
case text == "":
|
||||
s.renderConsoleMessage(c, "Nothing sent", "the message was empty", "/_gm/broadcast")
|
||||
case s.connector == nil:
|
||||
s.renderConsoleMessage(c, "Not configured", "the connector is not configured (set BACKEND_CONNECTOR_ADDR)", "/_gm/broadcast")
|
||||
default:
|
||||
delivered, err := s.connector.SendToGameChannel(c.Request.Context(), text, language)
|
||||
delivered, err := s.connector.SendToGameChannel(c.Request.Context(), text)
|
||||
if err != nil {
|
||||
s.consoleError(c, err)
|
||||
return
|
||||
}
|
||||
body := "posted to the game channel"
|
||||
if !delivered {
|
||||
body = "not delivered (that bot has no game channel configured)"
|
||||
body = "not delivered (the bot has no game channel configured)"
|
||||
}
|
||||
s.renderConsoleMessage(c, "Broadcast", body, "/_gm/broadcast")
|
||||
}
|
||||
@@ -876,6 +875,13 @@ func (s *Server) consoleThrottled(c *gin.Context) {
|
||||
view.Episodes = append(view.Episodes, row)
|
||||
}
|
||||
}
|
||||
if s.banview != nil {
|
||||
for _, b := range s.banview.Recent() {
|
||||
view.Bans = append(view.Bans, adminconsole.BanRow{
|
||||
IP: b.IP, Reason: b.Reason, Since: fmtTime(b.Since), Expires: fmtTime(b.Expires),
|
||||
})
|
||||
}
|
||||
}
|
||||
flagged, err := s.accounts.ListFlaggedHighRate(ctx)
|
||||
if err != nil {
|
||||
s.consoleError(c, err)
|
||||
@@ -889,6 +895,21 @@ func (s *Server) consoleThrottled(c *gin.Context) {
|
||||
s.renderConsole(c, "throttled", "throttled", "Throttled", view)
|
||||
}
|
||||
|
||||
// consoleUnban lifts a temporary IP ban — the operator's manual override. The
|
||||
// gateway applies it on its next active-ban sync, so the ban clears within the
|
||||
// sync interval rather than immediately.
|
||||
func (s *Server) consoleUnban(c *gin.Context) {
|
||||
ip := trimForm(c, "ip")
|
||||
if ip == "" {
|
||||
s.renderConsoleMessage(c, "Invalid", "an IP address is required", "/_gm/throttled")
|
||||
return
|
||||
}
|
||||
if s.banview != nil {
|
||||
s.banview.RequestUnban(ip)
|
||||
}
|
||||
s.renderConsoleMessage(c, "Unban requested", fmt.Sprintf("%s will be unbanned on the next gateway sync", ip), "/_gm/throttled")
|
||||
}
|
||||
|
||||
// consoleClearHighRateFlag clears the soft high-rate marker — the operator's
|
||||
// reversible review action.
|
||||
func (s *Server) consoleClearHighRateFlag(c *gin.Context) {
|
||||
@@ -966,6 +987,9 @@ func (s *Server) consoleBlockUser(c *gin.Context) {
|
||||
s.consoleError(c, err)
|
||||
return
|
||||
}
|
||||
// Re-evaluate the player's moderated-chat write access: a block mutes them in
|
||||
// the discussion chat if they are currently in it.
|
||||
s.publishChatAccessChange(id)
|
||||
s.renderConsoleMessage(c, "Blocked", fmt.Sprintf("account blocked; %d game(s) forfeited", forfeited), back)
|
||||
}
|
||||
|
||||
@@ -980,6 +1004,9 @@ func (s *Server) consoleUnblockUser(c *gin.Context) {
|
||||
s.consoleError(c, err)
|
||||
return
|
||||
}
|
||||
// Re-evaluate the player's moderated-chat write access: an unblock restores it
|
||||
// (unless they are still chat-muted) for a member currently in the chat.
|
||||
s.publishChatAccessChange(id)
|
||||
s.renderConsoleMessage(c, "Unblocked", "the block was lifted; lost games are not restored", "/_gm/users/"+id.String())
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ func (s *Server) consoleFeedbackDetail(c *gin.Context) {
|
||||
}
|
||||
view := adminconsole.FeedbackDetailView{
|
||||
ID: m.ID.String(), AccountID: m.AccountID.String(), SenderName: m.SenderName,
|
||||
Source: m.Source, Channel: m.Channel, InterfaceLanguage: m.Lang, BotLanguage: m.ChannelLang,
|
||||
Source: m.Source, Channel: m.Channel, InterfaceLanguage: m.Lang,
|
||||
IP: m.SenderIP, Body: m.Body,
|
||||
HasAttachment: m.HasAttachment, AttachmentName: m.AttachmentName, IsImage: feedback.IsImage(m.AttachmentName),
|
||||
Read: m.Read, Archived: m.Archived, Replied: m.Replied, ReplyBody: m.ReplyBody,
|
||||
@@ -248,6 +248,9 @@ func (s *Server) consoleGrantRole(c *gin.Context) {
|
||||
if role == account.RoleNoBanner {
|
||||
s.publishBannerChange(id)
|
||||
}
|
||||
if role == account.RoleChatMuted {
|
||||
s.publishChatAccessChange(id)
|
||||
}
|
||||
s.renderConsoleMessage(c, "Role granted", "granted "+role, back)
|
||||
}
|
||||
|
||||
@@ -270,6 +273,9 @@ func (s *Server) consoleRevokeRole(c *gin.Context) {
|
||||
if role == account.RoleNoBanner {
|
||||
s.publishBannerChange(id)
|
||||
}
|
||||
if role == account.RoleChatMuted {
|
||||
s.publishChatAccessChange(id)
|
||||
}
|
||||
s.renderConsoleMessage(c, "Role revoked", "revoked "+role, back)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,36 +19,33 @@ import (
|
||||
// telegramAuthRequest carries the identity the connector extracted from a
|
||||
// validated initData payload. Username, FirstName and LanguageCode seed a
|
||||
// brand-new account's display name and language (first contact only).
|
||||
// ServiceLanguage is the validating bot's language tag (en/ru); it is recorded on
|
||||
// every login (the bot the user last came through) and routes their out-of-app push.
|
||||
type telegramAuthRequest struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
Username string `json:"username"`
|
||||
FirstName string `json:"first_name"`
|
||||
LanguageCode string `json:"language_code"`
|
||||
ServiceLanguage string `json:"service_language"`
|
||||
ExternalID string `json:"external_id"`
|
||||
Username string `json:"username"`
|
||||
FirstName string `json:"first_name"`
|
||||
LanguageCode string `json:"language_code"`
|
||||
}
|
||||
|
||||
// handleTelegramAuth provisions (or finds) the account bound to a Telegram
|
||||
// identity and mints a session for it, seeding a new account's display name and
|
||||
// language from the supplied Telegram fields and recording the validating bot's
|
||||
// service language (updated every login) so out-of-app push routes to that bot.
|
||||
// language from the supplied Telegram fields (first contact only).
|
||||
func (s *Server) handleTelegramAuth(c *gin.Context) {
|
||||
var req telegramAuthRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.ExternalID == "" {
|
||||
abortBadRequest(c, "external_id is required")
|
||||
return
|
||||
}
|
||||
acc, err := s.accounts.ProvisionTelegram(c.Request.Context(), req.ExternalID, req.LanguageCode, req.Username, req.FirstName)
|
||||
acc, created, err := s.accounts.ProvisionTelegram(c.Request.Context(), req.ExternalID, req.LanguageCode, req.Username, req.FirstName)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.accounts.SetServiceLanguage(c.Request.Context(), acc.ID, req.ServiceLanguage); err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
if created {
|
||||
// First registration: re-evaluate moderated-chat write access, so a user who
|
||||
// joined the chat before registering is granted on the spot (no chat_member
|
||||
// event fires on registration).
|
||||
s.publishChatAccessChange(acc.ID)
|
||||
}
|
||||
acc.ServiceLanguage = req.ServiceLanguage // reflect this login's bot in the session response
|
||||
s.mintSession(c, acc)
|
||||
}
|
||||
|
||||
@@ -59,10 +56,9 @@ type pushTargetRequest struct {
|
||||
|
||||
// pushTargetResponse carries what the gateway needs to route an out-of-app push:
|
||||
// the recipient's Telegram external_id (empty when they have no Telegram
|
||||
// identity, e.g. a guest or email-only account), the language that both selects the
|
||||
// delivering bot and renders the message (the account's service language, the bot
|
||||
// it last signed in through, falling back to its preferred language), and whether
|
||||
// they confined notifications to the in-app stream.
|
||||
// identity, e.g. a guest or email-only account), the language the single bot renders
|
||||
// the message in (the account's interface language), and whether they confined
|
||||
// notifications to the in-app stream.
|
||||
type pushTargetResponse struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
Language string `json:"language"`
|
||||
@@ -94,15 +90,9 @@ func (s *Server) handlePushTarget(c *gin.Context) {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
// Route by the bot the user last signed in through; fall back to the interface
|
||||
// language for an account that has never come through a tagged bot.
|
||||
language := acc.ServiceLanguage
|
||||
if language == "" {
|
||||
language = acc.PreferredLanguage
|
||||
}
|
||||
c.JSON(http.StatusOK, pushTargetResponse{
|
||||
ExternalID: ext,
|
||||
Language: language,
|
||||
Language: acc.PreferredLanguage,
|
||||
NotificationsInAppOnly: acc.NotificationsInAppOnly,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"scrabble/backend/internal/banview"
|
||||
)
|
||||
|
||||
// banSyncRequest mirrors the gateway's active-ban report: every entry is one
|
||||
// currently-enforced IP ban.
|
||||
type banSyncRequest struct {
|
||||
Active []banSyncEntry `json:"active"`
|
||||
}
|
||||
|
||||
// banSyncEntry is one active ban in the sync request.
|
||||
type banSyncEntry struct {
|
||||
IP string `json:"ip"`
|
||||
Reason string `json:"reason"`
|
||||
Since time.Time `json:"since"`
|
||||
Expires time.Time `json:"expires"`
|
||||
}
|
||||
|
||||
// banSyncResponse returns the IPs an operator has marked for unban for the gateway
|
||||
// to apply on its next sync.
|
||||
type banSyncResponse struct {
|
||||
Unban []string `json:"unban"`
|
||||
}
|
||||
|
||||
// handleBanSync ingests the gateway's active-ban report into the ban view (the
|
||||
// admin console's active-bans panel) and returns the operator's pending unbans.
|
||||
// Internal, gateway-only: like the rate-limit report it trusts the network
|
||||
// segment and carries no user identity.
|
||||
func (s *Server) handleBanSync(c *gin.Context) {
|
||||
var req banSyncRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
abortBadRequest(c, "invalid ban sync")
|
||||
return
|
||||
}
|
||||
bans := make([]banview.Ban, 0, len(req.Active))
|
||||
for _, e := range req.Active {
|
||||
bans = append(bans, banview.Ban{IP: e.IP, Reason: e.Reason, Since: e.Since, Expires: e.Expires})
|
||||
}
|
||||
s.banview.Ingest(bans)
|
||||
c.JSON(http.StatusOK, banSyncResponse{Unban: s.banview.DrainUnbans()})
|
||||
}
|
||||
@@ -104,6 +104,9 @@ func (s *Server) handleCreateInvitation(c *gin.Context) {
|
||||
abortBadRequest(c, "unknown variant")
|
||||
return
|
||||
}
|
||||
if !s.ensureVariantAllowed(c, uid, variant.String()) {
|
||||
return
|
||||
}
|
||||
settings := lobby.InvitationSettings{
|
||||
Variant: variant,
|
||||
HintsAllowed: req.HintsAllowed,
|
||||
|
||||
@@ -2,8 +2,10 @@ package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/engine"
|
||||
)
|
||||
@@ -134,6 +136,24 @@ func (s *Server) handleGameState(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dto)
|
||||
}
|
||||
|
||||
// ensureVariantAllowed reports whether the caller's profile permits creating a game
|
||||
// of variant — it must be one of their VariantPreferences. It aborts the request
|
||||
// with 400 and returns false otherwise. Only the player who creates a game (quick
|
||||
// match, vs-AI or a friend invitation) is gated this way; an invited friend may
|
||||
// accept an invitation in any variant.
|
||||
func (s *Server) ensureVariantAllowed(c *gin.Context, uid uuid.UUID, variant string) bool {
|
||||
acc, err := s.accounts.GetByID(c.Request.Context(), uid)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return false
|
||||
}
|
||||
if !slices.Contains(acc.VariantPreferences, variant) {
|
||||
abortBadRequest(c, "variant is not in your preferences")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// enqueueRequest enters per-variant auto-match under a per-turn word rule. VsAI true
|
||||
// starts an honest-AI game against a robot instead of the open/wait matchmaking path.
|
||||
type enqueueRequest struct {
|
||||
@@ -162,6 +182,9 @@ func (s *Server) handleEnqueue(c *gin.Context) {
|
||||
abortBadRequest(c, "unknown variant")
|
||||
return
|
||||
}
|
||||
if !s.ensureVariantAllowed(c, uid, variant.String()) {
|
||||
return
|
||||
}
|
||||
if !s.ensureUnderGameLimit(c, uid) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"scrabble/backend/internal/account"
|
||||
"scrabble/backend/internal/adminconsole"
|
||||
"scrabble/backend/internal/ads"
|
||||
"scrabble/backend/internal/banview"
|
||||
"scrabble/backend/internal/connector"
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/feedback"
|
||||
@@ -83,6 +84,10 @@ type Deps struct {
|
||||
// admin console's throttled view + the high-rate auto-flag. A nil RateWatch
|
||||
// disables the internal report endpoint and the console view.
|
||||
RateWatch *ratewatch.Watch
|
||||
// BanView mirrors the gateway's active IP bans for the admin console and
|
||||
// collects operator unban requests. A nil BanView disables the internal
|
||||
// ban-sync endpoint and the console's active-bans panel.
|
||||
BanView *banview.View
|
||||
// Ads is the advertising-banner domain service: campaign rotation feeding the
|
||||
// profile.get banner block, plus the banner admin console section. A nil Ads
|
||||
// omits the banner block and disables the banner console.
|
||||
@@ -115,6 +120,7 @@ type Server struct {
|
||||
dictDir string
|
||||
connector *connector.Client
|
||||
ratewatch *ratewatch.Watch
|
||||
banview *banview.View
|
||||
ads *ads.Service
|
||||
notifier notify.Publisher
|
||||
console *adminconsole.Renderer
|
||||
@@ -164,6 +170,7 @@ func New(addr string, deps Deps) *Server {
|
||||
dictDir: deps.DictDir,
|
||||
connector: deps.Connector,
|
||||
ratewatch: deps.RateWatch,
|
||||
banview: deps.BanView,
|
||||
ads: deps.Ads,
|
||||
notifier: notifier,
|
||||
http: &http.Server{Addr: addr, Handler: engine},
|
||||
|
||||
@@ -206,9 +206,6 @@ func (svc *Service) Nudge(ctx context.Context, gameID, senderID uuid.UUID) (Mess
|
||||
// read "<name>: …"; an unresolved name (best-effort) falls back to the plain phrase.
|
||||
senderName, _ := svc.games.SeatName(ctx, gameID, senderID)
|
||||
nudge := notify.Nudge(target, gameID, senderID, senderName)
|
||||
if lang, err := svc.games.GameLanguage(ctx, gameID); err == nil {
|
||||
nudge.Language = lang // route by the game's bot, not the recipient's last-login one
|
||||
}
|
||||
svc.pub.Publish(nudge)
|
||||
}
|
||||
return msg, nil
|
||||
|
||||
@@ -44,9 +44,6 @@ type GameReader interface {
|
||||
// one-chat-message-per-turn limit (a message counts toward the current turn when it
|
||||
// was posted at or after this time).
|
||||
TurnStartedAt(ctx context.Context, gameID uuid.UUID) (time.Time, error)
|
||||
// GameLanguage is the game's language tag ("en"/"ru"), so a nudge's out-of-app push routes
|
||||
// to the game's bot rather than the recipient's last-login bot.
|
||||
GameLanguage(ctx context.Context, gameID uuid.UUID) (string, error)
|
||||
// VsAI reports whether the game is an honest-AI game, in which chat and nudge are
|
||||
// both disabled (the game still reports status 'active').
|
||||
VsAI(ctx context.Context, gameID uuid.UUID) (bool, error)
|
||||
|
||||
+21
-20
@@ -10,12 +10,13 @@ POSTGRES_USER=scrabble
|
||||
POSTGRES_PASSWORD=change-me # required
|
||||
|
||||
# --- Dictionary -------------------------------------------------------------
|
||||
# scrabble-dictionary release tag baked into the image as the SEED dictionary
|
||||
# (image build-arg; also labels the resident seed version). After first boot the
|
||||
# dawg-data volume preserves versions uploaded through the admin console, and the
|
||||
# active version lives in the DB — so bumping this on a later deploy does NOT change
|
||||
# a running contour; update the dictionary through /_gm/dictionary instead.
|
||||
DICT_VERSION=v1.0.0
|
||||
# scrabble-dictionary release tag baked into the image as the SEED dictionary for a
|
||||
# FRESH volume (image build-arg; also labels the resident seed version). After first
|
||||
# boot the dawg-data volume preserves versions uploaded through the admin console and
|
||||
# the active version lives in the DB. On a live volume a changed value is ignored (the
|
||||
# recorded .seed_version marker wins — the seed-drift guard); change a running
|
||||
# contour's dictionary through /_gm/dictionary (ARCHITECTURE.md §5).
|
||||
DICT_VERSION=v1.2.1
|
||||
|
||||
# --- Logging ----------------------------------------------------------------
|
||||
LOG_LEVEL=info
|
||||
@@ -29,26 +30,26 @@ GM_BASICAUTH_HASH= # required; `caddy hash-password` bcrypt
|
||||
|
||||
# --- UI build args (baked into the gateway image) ---------------------------
|
||||
VITE_TELEGRAM_BOT_ID=
|
||||
VITE_TELEGRAM_LINK= # fallback friend-invite Mini App link (per-bot below)
|
||||
VITE_TELEGRAM_LINK_EN= # friend-invite Mini App link, English bot (full URL, e.g. https://t.me/<bot>/<app>)
|
||||
VITE_TELEGRAM_LINK_RU= # friend-invite Mini App link, Russian bot (full URL)
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_EN= # landing "Play in Telegram" link, English bot
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME_RU= # landing "Play in Telegram" link, Russian bot
|
||||
VITE_TELEGRAM_LINK= # friend-invite Mini App link (full URL, e.g. https://t.me/<bot>/<app>)
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME= # landing "Play in Telegram" link, the bot's game channel
|
||||
VITE_GATEWAY_URL=
|
||||
|
||||
# --- Gateway ----------------------------------------------------------------
|
||||
GATEWAY_DEFAULT_SUPPORTED_LANGUAGES=en,ru
|
||||
|
||||
# --- Grafana ----------------------------------------------------------------
|
||||
GRAFANA_ROOT_URL=/_gm/grafana/ # set the full https URL behind a real domain
|
||||
GRAFANA_ADMIN_PASSWORD=admin
|
||||
|
||||
# --- Telegram connector -----------------------------------------------------
|
||||
AWG_CONF= # required; AmneziaWG sidecar config
|
||||
TELEGRAM_BOT_TOKEN_EN= # at least one of EN/RU required
|
||||
TELEGRAM_BOT_TOKEN_RU=
|
||||
TELEGRAM_GAME_CHANNEL_ID_EN=
|
||||
TELEGRAM_GAME_CHANNEL_ID_RU=
|
||||
# --- Telegram validator + bot -----------------------------------------------
|
||||
# The token is shared: the validator uses it as the HMAC secret, the bot for the
|
||||
# Bot API. The bot-link wiring (validator/relay/mTLS addresses) is hard-wired in
|
||||
# docker-compose.yml; the mTLS material is NOT here — run `deploy/gen-certs.sh`
|
||||
# (writes deploy/certs/, gitignored) before `docker compose up`.
|
||||
AWG_CONF= # required; AmneziaWG sidecar config (the bot's Telegram egress)
|
||||
TELEGRAM_BOT_TOKEN= # required
|
||||
TELEGRAM_GAME_CHANNEL_ID=
|
||||
TELEGRAM_CHAT_ID= # moderated discussion chat (channel's linked group); empty disables gating
|
||||
TELEGRAM_PROMO_BOT_TOKEN= # optional standalone promo bot token; empty disables it
|
||||
TELEGRAM_BOT_USERNAME= # main bot @username without the @ (promo message); required when the promo token is set
|
||||
TELEGRAM_BOT_LINK= # main bot Mini App link for the promo button (reuse VITE_TELEGRAM_LINK); required when the promo token is set
|
||||
TELEGRAM_MINIAPP_URL= # required
|
||||
TELEGRAM_TEST_ENV=false
|
||||
TELEGRAM_API_BASE_URL=
|
||||
|
||||
+93
-27
@@ -1,8 +1,8 @@
|
||||
# deploy
|
||||
|
||||
The full Scrabble contour: `backend` + `gateway` + the static `landing` + Postgres +
|
||||
the Telegram connector (with a VPN sidecar) + the observability stack (OTel
|
||||
Collector → Prometheus + Tempo → Grafana), fronted by a **caddy** that owns a single
|
||||
the Telegram `validator` + `bot` (the bot with a VPN sidecar) + the observability stack
|
||||
(OTel Collector → Prometheus + Tempo → Grafana), fronted by a **caddy** that owns a single
|
||||
`/_gm` Basic-Auth (the admin console + Grafana). Topology and the decision record are in
|
||||
[`../docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md) §13; this file is the
|
||||
operational reference for **every environment variable**.
|
||||
@@ -16,11 +16,13 @@ operational reference for **every environment variable**.
|
||||
| `landing` | built (`gateway/Dockerfile`, target `landing`) | Static landing page at `/` (caddy:2-alpine + the shared Vite build, `deploy/landing/Caddyfile`); absorbs stray public paths. |
|
||||
| `backend` | built (`backend/Dockerfile`) | Domain service; bakes in the DAWG dictionaries; runs migrations at boot. |
|
||||
| `postgres` | `postgres:17-alpine` | Database (named volume, `pg_isready` healthcheck). |
|
||||
| `vpn` + `telegram` | sidecar + built (`platform/telegram/Dockerfile`) | Telegram connector; egresses through the AmneziaWG sidecar; internal gRPC at `telegram:9091`. |
|
||||
| `validator` | built (`platform/telegram/Dockerfile`, target `validator`) | Telegram HMAC validator (no VPN, no Bot API); internal gRPC at `validator:9091`. Game login depends only on this. |
|
||||
| `vpn` + `bot` | sidecar + built (`platform/telegram/Dockerfile`, target `bot`) | Telegram bot, gated to the **`telegram-local`** profile; egresses through the AmneziaWG sidecar and dials the gateway bot-link (mTLS) at `gateway:9443`. The test contour activates the profile; the prod **main** host omits it and runs the bot standalone on its **own host** (`docker-compose.bot.yml`, no VPN — native Bot API egress). |
|
||||
| `otelcol` | `otel/opentelemetry-collector-contrib` | OTLP/gRPC `:4317` → Prometheus scrape (`:9464`) + Tempo. |
|
||||
| `prometheus` | `prom/prometheus` | Metrics, 15d retention. |
|
||||
| `prometheus` | `prom/prometheus` | Metrics, 15d retention (7d in prod). |
|
||||
| `tempo` | `grafana/tempo` | Traces, 72h retention. |
|
||||
| `grafana` | `grafana/grafana` | Dashboards (provisioned), anonymous-admin behind caddy's `/_gm/grafana`. |
|
||||
| `node_exporter` | `quay.io/prometheus/node-exporter` | Host CPU/memory/disk metrics (Prometheus job `node`); the OOM signal on the tight prod main host (2 vCPU / 1.9 GiB). |
|
||||
|
||||
Networking: inter-service traffic is on the private `internal` network
|
||||
(project-scoped DNS); only `caddy` joins the shared external `edge` network so the
|
||||
@@ -58,13 +60,19 @@ compose binds from this directory.
|
||||
| Variable | Gitea kind | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `POSTGRES_PASSWORD` | secret | Postgres password (also embedded in `BACKEND_POSTGRES_DSN`). |
|
||||
| `AWG_CONF` | secret | AmneziaWG config for the VPN sidecar (the connector's only egress). **Must not contain a `DNS=` line** — it hijacks the shared netns's resolv.conf and breaks the connector resolving `otelcol` (telemetry export). Without it, Docker's resolver handles both `otelcol` and `api.telegram.org`. |
|
||||
| `GM_BASICAUTH_HASH` | secret | bcrypt hash gating `/_gm` (admin console + Grafana). Generate with `docker run --rm caddy:2-alpine caddy hash-password --plaintext '<pw>'`. |
|
||||
| `TELEGRAM_MINIAPP_URL` | variable | The Mini App URL the connector hands out in deep links / buttons. |
|
||||
| `TELEGRAM_MINIAPP_URL` | variable | The Mini App URL the bot hands out in deep links / buttons. |
|
||||
|
||||
**Plus at least one bot token** — `TELEGRAM_BOT_TOKEN_EN` or `TELEGRAM_BOT_TOKEN_RU`
|
||||
(secrets). Compose cannot express "one of", so they default to empty, but the
|
||||
connector **fails at boot** if both are empty.
|
||||
**Plus the bot token** — `TELEGRAM_BOT_TOKEN` (secret), shared by the validator (HMAC
|
||||
secret) and the bot (Bot API). It defaults to empty in compose, but both **fail at
|
||||
boot** when it is empty.
|
||||
|
||||
**Conditionally — `AWG_CONF`** (secret): the AmneziaWG config for the VPN sidecar, needed
|
||||
only when the `telegram-local` profile runs (the test contour and local runs with the
|
||||
bot). It is **not** `:?`-guarded — compose interpolates profiled-out services too, so the
|
||||
prod main host (no VPN) must not require it. It **must not contain a `DNS=` line** — that
|
||||
hijacks the shared netns's resolv.conf and breaks the bot resolving `otelcol` / `gateway`;
|
||||
without it Docker's resolver handles `otelcol`, `gateway` and `api.telegram.org`.
|
||||
|
||||
## Optional variables (with defaults)
|
||||
|
||||
@@ -72,23 +80,18 @@ connector **fails at boot** if both are empty.
|
||||
| --- | --- | --- | --- |
|
||||
| `POSTGRES_DB` | variable | `scrabble` | Database name. |
|
||||
| `POSTGRES_USER` | variable | `scrabble` | Database user. |
|
||||
| `DICT_VERSION` | variable | `v1.0.0` | `scrabble-dictionary` release tag baked into the backend image (build-arg). |
|
||||
| `LOG_LEVEL` | variable | `info` | Shared log level for backend / gateway / connector (`debug\|info\|warn\|error`). |
|
||||
| `DICT_VERSION` | variable | `v1.2.1` | `scrabble-dictionary` release tag baked into the backend image as the **seed for a fresh volume** (build-arg). A live contour changes dictionary through the admin console, not this; on a seeded volume a changed value is ignored (the recorded `.seed_version` marker wins — the seed-drift guard, ARCHITECTURE.md §5). Set per contour as `TEST_`/`PROD_DICT_VERSION`. |
|
||||
| `LOG_LEVEL` | variable | `info` | Shared log level for backend / gateway / validator / bot (`debug\|info\|warn\|error`). |
|
||||
| `CADDY_SITE_ADDRESS` | variable | `:80` | Caddy site address. Test: `:80` (host caddy terminates TLS). Prod: a domain, so caddy does its own ACME. |
|
||||
| `GM_BASICAUTH_USER` | variable | `gm` | Username for the `/_gm` Basic-Auth. |
|
||||
| `GRAFANA_ROOT_URL` | variable | `/_gm/grafana/` | Grafana root URL (sub-path serving). Set the full `https://<domain>/_gm/grafana/` behind a real domain. |
|
||||
| `GRAFANA_ADMIN_PASSWORD` | secret | `admin` | Grafana admin password. Low impact (the login form is disabled, access is anonymous-admin behind caddy) but set it anyway. |
|
||||
| `TELEGRAM_GAME_CHANNEL_ID_EN` | variable | _(empty)_ | English game-channel id; empty/`0` disables channel posts. |
|
||||
| `TELEGRAM_GAME_CHANNEL_ID_RU` | variable | _(empty)_ | Russian game-channel id; empty/`0` disables channel posts. |
|
||||
| `TELEGRAM_GAME_CHANNEL_ID` | variable | _(empty)_ | The bot's game-channel id; empty/`0` disables channel posts. |
|
||||
| `TELEGRAM_TEST_ENV` | _pinned_ | `false` | `true` routes the bot through Telegram's test environment (`.../bot<token>/test/METHOD`). **The CI test contour pins this to `true` in `ci.yaml`** (the contour is the test environment) — it is not a Gitea variable. Set it in `.env` for a local run; prod leaves it `false`. |
|
||||
| `TELEGRAM_API_BASE_URL` | variable | _(empty)_ | Override the Bot API host (a mock/self-hosted server); empty = `https://api.telegram.org`. |
|
||||
| `GATEWAY_DEFAULT_SUPPORTED_LANGUAGES` | variable | `en,ru` | Variant-gating set for non-Telegram logins (web/email/guest). |
|
||||
| `VITE_TELEGRAM_BOT_ID` | variable | _(empty)_ | UI build-arg: numeric bot id for the web Login Widget. |
|
||||
| `VITE_TELEGRAM_LINK` | variable | _(empty)_ | UI build-arg: **fallback** friend-invite Mini App link (e.g. `https://t.me/<bot>/<app>`), used when the per-bot link below is unset. |
|
||||
| `VITE_TELEGRAM_LINK_EN` | variable | _(empty)_ | UI build-arg: friend-invite Mini App link for the **English** bot (full URL, `https://t.me/<bot>/<app>` — `<app>` is the Mini App short name from BotFather). The friend-code share uses the link matching the bot the player signed in through. |
|
||||
| `VITE_TELEGRAM_LINK_RU` | variable | _(empty)_ | UI build-arg: same for the **Russian** bot. |
|
||||
| `VITE_TELEGRAM_GAME_CHANNEL_NAME_EN` | variable | _(empty)_ | UI build-arg: the landing "Play in Telegram" link for the **English** bot (e.g. `https://t.me/Scrabble_Game`). |
|
||||
| `VITE_TELEGRAM_GAME_CHANNEL_NAME_RU` | variable | _(empty)_ | UI build-arg: the landing "Play in Telegram" link for the **Russian** bot (e.g. `https://t.me/Erudit_Game`). |
|
||||
| `VITE_TELEGRAM_LINK` | variable | _(empty)_ | UI build-arg: friend-invite Mini App link (full URL, `https://t.me/<bot>/<app>` — `<app>` is the Mini App short name from BotFather). |
|
||||
| `VITE_TELEGRAM_GAME_CHANNEL_NAME` | variable | _(empty)_ | UI build-arg: the landing "Play in Telegram" link, the bot's game channel (e.g. `https://t.me/Erudit_Game`). |
|
||||
| `VITE_GATEWAY_URL` | variable | _(empty)_ | UI build-arg: gateway origin; empty = same-origin (the usual single-origin deploy). |
|
||||
|
||||
The five `VITE_*` are **build-args** baked into the gateway and landing images at
|
||||
@@ -101,14 +104,77 @@ These are hard-wired in `docker-compose.yml` (no `${...}`), pointing the service
|
||||
at each other on the `internal` network — listed here so they are not mistaken for
|
||||
missing config: `BACKEND_POSTGRES_DSN` (→ `postgres`, `search_path=backend`),
|
||||
`GATEWAY_BACKEND_HTTP_URL`/`_GRPC_ADDR` (→ `backend`),
|
||||
`GATEWAY_CONNECTOR_ADDR`/`BACKEND_CONNECTOR_ADDR` (→ `telegram:9091`), and all three
|
||||
services' `*_OTEL_*_EXPORTER=otlp` → `OTEL_EXPORTER_OTLP_ENDPOINT=http://otelcol:4317`
|
||||
(`_INSECURE=true`). The connector shares the VPN sidecar's netns: routing to the
|
||||
collector's internal IP is fine (connected route), but its `AWG_CONF` must **not**
|
||||
set a `DNS=` directive — that hijacks resolv.conf and breaks resolving `otelcol`
|
||||
("produced zero addresses"); without it the netns uses Docker's resolver, which
|
||||
resolves both `otelcol` and `api.telegram.org`. `GATEWAY_ADMIN_*` is intentionally
|
||||
**unset** — caddy owns `/_gm` in the contour.
|
||||
`GATEWAY_VALIDATOR_ADDR` (→ `validator:9091`), `BACKEND_CONNECTOR_ADDR` (→ the gateway
|
||||
bot-link relay `gateway:9092`), the bot's `TELEGRAM_GATEWAY_ADDR` (→ `gateway:9443`,
|
||||
mTLS) with the `GATEWAY_BOTLINK_*` / `TELEGRAM_BOTLINK_*` cert paths under `/certs` (the
|
||||
mTLS material is generated by `deploy/gen-certs.sh`, gitignored, regenerated each
|
||||
deploy), and all services' `*_OTEL_*_EXPORTER=otlp` →
|
||||
`OTEL_EXPORTER_OTLP_ENDPOINT=http://otelcol:4317`
|
||||
(`_INSECURE=true`). The bot shares the VPN sidecar's netns: routing to the
|
||||
collector's / gateway's internal IP is fine (connected route), but its `AWG_CONF` must
|
||||
**not** set a `DNS=` directive — that hijacks resolv.conf and breaks resolving `otelcol`
|
||||
/ `gateway` ("produced zero addresses"); without it the netns uses Docker's resolver,
|
||||
which resolves `otelcol`, `gateway` and `api.telegram.org`. `GATEWAY_ADMIN_*` is
|
||||
intentionally **unset** — caddy owns `/_gm` in the contour.
|
||||
|
||||
## Production rollout
|
||||
|
||||
Prod runs on **two hosts** (main = full stack + ACME on the domain; tg = the bot only,
|
||||
native Bot API, no VPN), one-time provisioned by **[`ansible/`](ansible/)** (docker, a
|
||||
non-sudo `deploy` user holding the CI key, key-only sshd, default-deny ufw, fail2ban).
|
||||
Re-run `ansible/` after a host resize — it is idempotent.
|
||||
|
||||
**To roll out:** merge `development → master` (CI green), then run the **`prod-deploy`**
|
||||
workflow manually (Gitea → Actions → prod-deploy → run from `master`, input
|
||||
`confirm=deploy`). It builds + pushes the images to the registry, ships the
|
||||
compose/config/certs/env over SSH, deploys the main host with `prod-deploy.sh` (rolling,
|
||||
health-gated, **auto-rollback to the previous tag**), then the bot host, then probes the
|
||||
public site. After `master` is green this workflow is the **only** thing that touches
|
||||
prod — nothing auto-deploys there. It runs four visible jobs: **build → deploy-main →
|
||||
deploy-bot → verify** (the per-service rolling shows in the deploy-main log).
|
||||
|
||||
**Versioning.** Each release is a git tag `vX.Y.Z` on `master`; the deploy stamps
|
||||
`git describe --tags` into every image tag, every binary (`-ldflags` → `pkg/version` →
|
||||
the `service.version` telemetry attribute) and the SPA About screen. Tag the release
|
||||
before running the deploy:
|
||||
|
||||
```sh
|
||||
git tag -a v1.0.0 -m v1.0.0 && git push origin v1.0.0
|
||||
```
|
||||
|
||||
**Manual rollback** (any time after a successful deploy). Run the **`prod-rollback`**
|
||||
workflow (Gitea → Actions → prod-rollback, `confirm=rollback`). Leave `target_version`
|
||||
blank to roll back to the previously deployed version (read from the host's
|
||||
`PREVIOUS_TAG`), or set it to a release tag from the **Releases** page. It re-deploys
|
||||
that already-published image rolling + health-gated — no rebuild, no DB migration
|
||||
(image rollback is DB-safe under the expand-contract rule). The registry keeps every
|
||||
release tag, so any prior release is reachable.
|
||||
|
||||
**Migrations** must be **expand-contract** (backward-compatible; goose is forward-only):
|
||||
the automatic rollback is image-only and never restores the DB. A deploy that changes
|
||||
`backend/internal/postgres/migrations/` opens a maintenance window — the backend (sole
|
||||
writer) is stopped for a consistent `pg_dump` into `/opt/scrabble/dumps` before the new
|
||||
backend migrates. **Manual DB restore** (only if a migration was destructive):
|
||||
`docker exec -i scrabble-postgres psql -U scrabble -d scrabble -c 'DROP SCHEMA backend CASCADE'`,
|
||||
then pipe the dump into the same `psql`, and redeploy the matching old tag.
|
||||
|
||||
**bot-link cert rotation:** regenerate (`deploy/gen-certs.sh /tmp/c --force`), reset the
|
||||
five `PROD_BOTLINK_*` secrets from `/tmp/c`, and re-run the workflow — both hosts redeploy
|
||||
together with the fresh CA.
|
||||
|
||||
**Sizing / monitoring:** the main host launches undersized (2 vCPU / 1.9 GiB); the prod
|
||||
overlay trims limits + `GOMAXPROCS=2` + 7d Prometheus retention, and `node_exporter` feeds
|
||||
host memory to Grafana (`/_gm/grafana/`). Watch host memory and resize at Selectel when
|
||||
players arrive.
|
||||
|
||||
**`PROD_` Gitea set** (mirrors `TEST_`, mapped onto the unprefixed names above) — secrets:
|
||||
`PROD_{POSTGRES_PASSWORD, GM_BASICAUTH_HASH, GRAFANA_ADMIN_PASSWORD, TELEGRAM_BOT_TOKEN,
|
||||
TELEGRAM_PROMO_BOT_TOKEN, REGISTRY_PASSWORD, SSH_KEY, SSH_KNOWN_HOSTS, BOTLINK_CA,
|
||||
BOTLINK_GATEWAY_CERT, BOTLINK_GATEWAY_KEY, BOTLINK_BOT_CERT, BOTLINK_BOT_KEY}`; variables:
|
||||
`PROD_{REGISTRY_USER, MAIN_HOST, TG_HOST, CADDY_SITE_ADDRESS, GM_BASICAUTH_USER,
|
||||
GRAFANA_ROOT_URL, LOG_LEVEL, DICT_VERSION, TELEGRAM_MINIAPP_URL, TELEGRAM_GAME_CHANNEL_ID,
|
||||
TELEGRAM_CHAT_ID, TELEGRAM_BOT_USERNAME, VITE_TELEGRAM_BOT_ID, VITE_TELEGRAM_LINK,
|
||||
VITE_TELEGRAM_GAME_CHANNEL_NAME}`.
|
||||
|
||||
## Host-side setup (outside this repo)
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Prod host provisioning (Stage 18)
|
||||
|
||||
Idempotent Ansible that prepares the two production hosts. It installs Docker, a
|
||||
non-sudo `deploy` service account, SSH hardening, a default-deny firewall,
|
||||
fail2ban, unattended security upgrades and time sync. It does **not** deploy the
|
||||
application — that is `.gitea/workflows/prod-deploy.yaml`'s job, running as the
|
||||
`deploy` account this playbook creates.
|
||||
|
||||
Hosts are referenced by `~/.ssh/config` aliases (`scrabble-main-ops`,
|
||||
`scrabble-tg-ops`), so no IPs or key paths live in the repo.
|
||||
|
||||
## Prerequisites (controller)
|
||||
|
||||
- `ansible` with the bundled collections (`community.general`, `community.docker`,
|
||||
`ansible.posix`).
|
||||
- The two hosts reachable as root via the ssh-config aliases, host keys already
|
||||
accepted into `known_hosts` (`host_key_checking = True`).
|
||||
|
||||
## One-time: the CI deploy key
|
||||
|
||||
The CI prod-deploy workflow logs into the hosts as `deploy` using a dedicated
|
||||
key. Generate it once on the controller, authorize its public half via the
|
||||
playbook, and store its private half **only** in the Gitea `PROD_SSH_KEY` secret:
|
||||
|
||||
```sh
|
||||
ssh-keygen -t ed25519 -N '' -C scrabble-ci-deploy \
|
||||
-f ~/.ssh/scrabble_ci_deploy_ed25519
|
||||
# private half -> Gitea secret PROD_SSH_KEY (set via API); never commit it
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
cd deploy/ansible
|
||||
ansible-playbook site.yml
|
||||
```
|
||||
|
||||
The playbook reads the public key from `~/.ssh/scrabble_ci_deploy_ed25519.pub` by
|
||||
default; override with `-e deploy_ci_pubkey_path=/path/to/key.pub`. Re-running is
|
||||
safe (idempotent) and survives a host resize.
|
||||
|
||||
## What each host gets
|
||||
|
||||
- **both** (`common`): docker-ce + compose plugin, `daemon.json` (live-restore,
|
||||
10m×3 log rotation), `deploy` user (docker group, no sudo), key-only sshd,
|
||||
`ufw` default-deny incoming + allow SSH, fail2ban sshd jail, unattended
|
||||
upgrades, chrony, `/opt/scrabble/{config,certs,dumps,images}`.
|
||||
- **main**: `ufw` opens 80/443/9443; the external `edge` docker network.
|
||||
- **tg**: verifies direct `api.telegram.org` egress (the no-VPN assumption).
|
||||
@@ -0,0 +1,11 @@
|
||||
[defaults]
|
||||
inventory = inventory.ini
|
||||
roles_path = roles
|
||||
interpreter_python = /usr/bin/python3
|
||||
host_key_checking = True
|
||||
stdout_callback = yaml
|
||||
deprecation_warnings = False
|
||||
retry_files_enabled = False
|
||||
|
||||
[ssh_connection]
|
||||
pipelining = True
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
# Service account the CI prod-deploy workflow uses to drive docker on the hosts.
|
||||
# Membership in the docker group is root-equivalent (docker socket access), which
|
||||
# is all the deploy workflow needs; the account is deliberately not given sudo.
|
||||
deploy_user: deploy
|
||||
|
||||
# Public half of the dedicated CI deploy SSH key, read from the controller at run
|
||||
# time. The private half is generated on the controller during provisioning and
|
||||
# stored ONLY in the Gitea PROD_SSH_KEY secret; it is never committed. Override the
|
||||
# path with -e deploy_ci_pubkey_path=/path/to/key.pub if the key lives elsewhere.
|
||||
deploy_ci_pubkey_path: "{{ lookup('env', 'HOME') }}/.ssh/scrabble_ci_deploy_ed25519.pub"
|
||||
deploy_ci_pubkey: "{{ lookup('file', deploy_ci_pubkey_path) }}"
|
||||
|
||||
# Base directory the deploy workflow rsyncs compose files, config, certs and dumps
|
||||
# into. Owned by deploy_user so the workflow needs no elevation.
|
||||
scrabble_base_dir: /opt/scrabble
|
||||
|
||||
# Docker daemon json-file log rotation, mirroring the compose x-logging anchor so
|
||||
# the host's own containers (and any ad-hoc runs) rotate identically.
|
||||
docker_log_max_size: "10m"
|
||||
docker_log_max_file: "3"
|
||||
@@ -0,0 +1,19 @@
|
||||
# Production inventory for Stage 18.
|
||||
#
|
||||
# Hosts resolve through the operator's ~/.ssh/config aliases, so HostName (public
|
||||
# IP), User and IdentityFile live there — no IPs or key paths are committed here.
|
||||
# scrabble-main-ops -> main stack host (public IP, domain erudit-game.ru)
|
||||
# scrabble-tg-ops -> Telegram bot host (direct Bot API egress, no VPN)
|
||||
|
||||
[main]
|
||||
scrabble-main-ops
|
||||
|
||||
[tg]
|
||||
scrabble-tg-ops
|
||||
|
||||
[prod:children]
|
||||
main
|
||||
tg
|
||||
|
||||
[prod:vars]
|
||||
ansible_user=root
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
- name: restart docker
|
||||
ansible.builtin.service:
|
||||
name: docker
|
||||
state: restarted
|
||||
|
||||
- name: reload sshd
|
||||
ansible.builtin.service:
|
||||
name: ssh
|
||||
state: reloaded
|
||||
|
||||
- name: restart fail2ban
|
||||
ansible.builtin.service:
|
||||
name: fail2ban
|
||||
state: restarted
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
# Common baseline applied to both prod hosts: Docker engine, a non-sudo deploy
|
||||
# service account, SSH hardening, a default-deny firewall, fail2ban, unattended
|
||||
# security upgrades and time sync. Every task is idempotent.
|
||||
|
||||
- name: Install base packages
|
||||
ansible.builtin.apt:
|
||||
name:
|
||||
- ca-certificates
|
||||
- curl
|
||||
- gnupg
|
||||
- ufw
|
||||
- fail2ban
|
||||
- unattended-upgrades
|
||||
- chrony
|
||||
state: present
|
||||
update_cache: true
|
||||
cache_valid_time: 3600
|
||||
|
||||
# --- Docker engine (official repo; trixie is published upstream) ---------------
|
||||
|
||||
- name: Create apt keyring directory
|
||||
ansible.builtin.file:
|
||||
path: /etc/apt/keyrings
|
||||
state: directory
|
||||
mode: "0755"
|
||||
|
||||
- name: Install Docker apt GPG key
|
||||
ansible.builtin.get_url:
|
||||
url: https://download.docker.com/linux/debian/gpg
|
||||
dest: /etc/apt/keyrings/docker.asc
|
||||
mode: "0644"
|
||||
|
||||
- name: Add Docker apt repository
|
||||
ansible.builtin.apt_repository:
|
||||
repo: >-
|
||||
deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc]
|
||||
https://download.docker.com/linux/debian {{ ansible_distribution_release }} stable
|
||||
filename: docker
|
||||
state: present
|
||||
|
||||
- name: Install Docker engine and the compose plugin
|
||||
ansible.builtin.apt:
|
||||
name:
|
||||
- docker-ce
|
||||
- docker-ce-cli
|
||||
- containerd.io
|
||||
- docker-buildx-plugin
|
||||
- docker-compose-plugin
|
||||
state: present
|
||||
update_cache: true
|
||||
|
||||
- name: Configure the Docker daemon (live-restore + log rotation)
|
||||
ansible.builtin.template:
|
||||
src: daemon.json.j2
|
||||
dest: /etc/docker/daemon.json
|
||||
mode: "0644"
|
||||
notify: restart docker
|
||||
|
||||
- name: Enable and start Docker
|
||||
ansible.builtin.service:
|
||||
name: docker
|
||||
enabled: true
|
||||
state: started
|
||||
|
||||
# --- Deploy service account ----------------------------------------------------
|
||||
|
||||
- name: Create the deploy service account
|
||||
ansible.builtin.user:
|
||||
name: "{{ deploy_user }}"
|
||||
groups: docker
|
||||
append: true
|
||||
shell: /bin/bash
|
||||
create_home: true
|
||||
|
||||
- name: Ensure the deploy .ssh directory
|
||||
ansible.builtin.file:
|
||||
path: "/home/{{ deploy_user }}/.ssh"
|
||||
state: directory
|
||||
owner: "{{ deploy_user }}"
|
||||
group: "{{ deploy_user }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Authorize the CI deploy SSH key (exclusive)
|
||||
ansible.builtin.copy:
|
||||
dest: "/home/{{ deploy_user }}/.ssh/authorized_keys"
|
||||
content: "{{ deploy_ci_pubkey }}\n"
|
||||
owner: "{{ deploy_user }}"
|
||||
group: "{{ deploy_user }}"
|
||||
mode: "0600"
|
||||
|
||||
# --- SSH hardening -------------------------------------------------------------
|
||||
|
||||
- name: Harden sshd (key-only auth)
|
||||
ansible.builtin.template:
|
||||
src: sshd-hardening.conf.j2
|
||||
dest: /etc/ssh/sshd_config.d/10-scrabble-hardening.conf
|
||||
mode: "0644"
|
||||
validate: sshd -t -f %s
|
||||
notify: reload sshd
|
||||
|
||||
# --- Firewall (default deny incoming) ------------------------------------------
|
||||
# SSH is allowed before the policy flips so enabling ufw never locks us out.
|
||||
|
||||
- name: Allow SSH through the firewall
|
||||
community.general.ufw:
|
||||
rule: allow
|
||||
name: OpenSSH
|
||||
|
||||
- name: Default-deny incoming, allow outgoing
|
||||
community.general.ufw:
|
||||
direction: "{{ item.direction }}"
|
||||
policy: "{{ item.policy }}"
|
||||
loop:
|
||||
- { direction: incoming, policy: deny }
|
||||
- { direction: outgoing, policy: allow }
|
||||
|
||||
- name: Enable the firewall
|
||||
community.general.ufw:
|
||||
state: enabled
|
||||
|
||||
# --- fail2ban ------------------------------------------------------------------
|
||||
|
||||
- name: Configure the fail2ban sshd jail
|
||||
ansible.builtin.template:
|
||||
src: jail.local.j2
|
||||
dest: /etc/fail2ban/jail.local
|
||||
mode: "0644"
|
||||
notify: restart fail2ban
|
||||
|
||||
- name: Enable and start fail2ban
|
||||
ansible.builtin.service:
|
||||
name: fail2ban
|
||||
enabled: true
|
||||
state: started
|
||||
|
||||
# --- Unattended security upgrades + time sync ----------------------------------
|
||||
|
||||
- name: Enable unattended upgrades
|
||||
ansible.builtin.copy:
|
||||
dest: /etc/apt/apt.conf.d/20auto-upgrades
|
||||
mode: "0644"
|
||||
content: |
|
||||
APT::Periodic::Update-Package-Lists "1";
|
||||
APT::Periodic::Unattended-Upgrade "1";
|
||||
|
||||
- name: Enable and start chrony
|
||||
ansible.builtin.service:
|
||||
name: chrony
|
||||
enabled: true
|
||||
state: started
|
||||
|
||||
# --- Deploy directories --------------------------------------------------------
|
||||
|
||||
- name: Create the scrabble base directories
|
||||
ansible.builtin.file:
|
||||
path: "{{ scrabble_base_dir }}/{{ item }}"
|
||||
state: directory
|
||||
owner: "{{ deploy_user }}"
|
||||
group: "{{ deploy_user }}"
|
||||
mode: "0750"
|
||||
loop:
|
||||
- ""
|
||||
- config
|
||||
- certs
|
||||
- dumps
|
||||
- images
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"live-restore": true,
|
||||
"log-driver": "json-file",
|
||||
"log-opts": {
|
||||
"max-size": "{{ docker_log_max_size }}",
|
||||
"max-file": "{{ docker_log_max_file }}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Managed by Ansible (deploy/ansible).
|
||||
[DEFAULT]
|
||||
bantime = 1h
|
||||
findtime = 10m
|
||||
maxretry = 5
|
||||
backend = systemd
|
||||
|
||||
[sshd]
|
||||
enabled = true
|
||||
@@ -0,0 +1,6 @@
|
||||
# Managed by Ansible (deploy/ansible). Key-only authentication.
|
||||
# root stays reachable by key (prohibit-password) for provisioning re-runs.
|
||||
PasswordAuthentication no
|
||||
PermitRootLogin prohibit-password
|
||||
PubkeyAuthentication yes
|
||||
KbdInteractiveAuthentication no
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
# Main stack host: public web + bot-link ports and the external 'edge' network
|
||||
# the compose stack attaches caddy to.
|
||||
|
||||
- name: Open public web and bot-link ports
|
||||
community.general.ufw:
|
||||
rule: allow
|
||||
port: "{{ item }}"
|
||||
proto: tcp
|
||||
loop:
|
||||
- "80" # HTTP (ACME challenge + redirect to HTTPS)
|
||||
- "443" # HTTPS (caddy edge)
|
||||
- "9443" # bot-link mTLS (remote bot dials in; mutual TLS gates access)
|
||||
|
||||
- name: Ensure the external 'edge' docker network exists
|
||||
community.docker.docker_network:
|
||||
name: edge
|
||||
state: present
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
# Telegram bot host: holds no inbound port beyond SSH (the bot dials out to the
|
||||
# Bot API and into the main host's bot-link). We only verify direct Bot API
|
||||
# egress here, since the "no VPN" decision depends on it.
|
||||
|
||||
- name: Verify direct Telegram Bot API egress (no VPN on this host)
|
||||
ansible.builtin.uri:
|
||||
url: https://api.telegram.org/
|
||||
method: GET
|
||||
status_code: [200, 301, 302, 401, 404] # any HTTP reply proves reachability
|
||||
timeout: 10
|
||||
register: tg_egress
|
||||
failed_when: false
|
||||
|
||||
- name: Report Telegram reachability
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
api.telegram.org reachable:
|
||||
{{ (tg_egress.status | default(0) | int) > 0 }} (status {{ tg_egress.status | default('none') }})
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
# Stage 18 host provisioning. Idempotent: safe to re-run after a host resize.
|
||||
# Prepares hosts only (docker, hardening, service account, firewall); the
|
||||
# application is deployed separately by .gitea/workflows/prod-deploy.yaml.
|
||||
|
||||
- name: Common baseline (both hosts)
|
||||
hosts: prod
|
||||
become: true
|
||||
pre_tasks:
|
||||
- name: Require a well-formed CI deploy public key
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- deploy_ci_pubkey | length > 0
|
||||
- deploy_ci_pubkey is search('^(ssh|ecdsa)-')
|
||||
fail_msg: >-
|
||||
deploy_ci_pubkey is empty or malformed. Generate the key first
|
||||
(see deploy/ansible/README.md) or override deploy_ci_pubkey_path.
|
||||
roles:
|
||||
- common
|
||||
|
||||
- name: Main stack host
|
||||
hosts: main
|
||||
become: true
|
||||
roles:
|
||||
- main
|
||||
|
||||
- name: Telegram bot host
|
||||
hosts: tg
|
||||
become: true
|
||||
roles:
|
||||
- tg
|
||||
+20
-2
@@ -38,10 +38,28 @@
|
||||
}
|
||||
}
|
||||
|
||||
# The game SPA and the Connect edge are served by the gateway.
|
||||
# The game SPA and the Connect edge are served by the gateway. Strip any
|
||||
# client-supplied X-Scrabble-Honeypot here so the gateway only ever honours the
|
||||
# tag the honeypot block sets below (a client cannot self-tag a real request).
|
||||
@gateway path /app /app/* /telegram /telegram/* /scrabble.edge.v1.Gateway/*
|
||||
handle @gateway {
|
||||
reverse_proxy gateway:8081
|
||||
reverse_proxy gateway:8081 {
|
||||
header_up -X-Scrabble-Honeypot
|
||||
}
|
||||
}
|
||||
|
||||
# Honeypot decoy paths: classic vulnerability-scanner bait no real client ever
|
||||
# requests. Route them to the gateway tagged with X-Scrabble-Honeypot — the set
|
||||
# replaces any client-supplied value — so it logs the scanner hit and (in prod)
|
||||
# bans the source IP. (A delete + set in one block would not work: Caddy applies
|
||||
# header_up deletions after sets, which would strip the tag we just set; the real
|
||||
# endpoints instead strip the header in the @gateway block above.) Keep this list
|
||||
# disjoint from every legitimate landing/app path.
|
||||
@honeypot path /.env /.git /.git/* /.aws/* /wp-login.php /wp-admin /wp-admin/* /phpmyadmin /phpmyadmin/*
|
||||
handle @honeypot {
|
||||
reverse_proxy gateway:8081 {
|
||||
header_up X-Scrabble-Honeypot 1
|
||||
}
|
||||
}
|
||||
|
||||
# Everything else — the public landing at / and any stray path — is static.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user