Compare commits
14 Commits
d5369a0188
..
v1.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
| dc946a1faf | |||
| ba57687430 | |||
| 6cb88b28c4 | |||
| 46d569720c | |||
| 9253b1bdca | |||
| 384bd143d0 | |||
| 9d1ca213d6 | |||
| 1f78bb274b | |||
| 81b716569f | |||
| aa330b726e | |||
| c5d22fceca | |||
| deaa7a29c5 | |||
| 24017bcb7f | |||
| 2c4f4b10dc |
@@ -21,6 +21,18 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
{$CADDY_SITE_ADDRESS::80} {
|
{$CADDY_SITE_ADDRESS::80} {
|
||||||
|
# HTTP/3 is advertised by default whenever this caddy terminates TLS (prod:
|
||||||
|
# CADDY_SITE_ADDRESS is the domain). But UDP/443 is never reachable — the prod
|
||||||
|
# compose maps only "443:443" (TCP) and ufw opens 443/tcp — so a client that cached
|
||||||
|
# the `Alt-Svc: h3` advert (sticky for ma=2592000s) stalls on the dead QUIC path
|
||||||
|
# before falling back to h2, which surfaced as the Telegram Mini App intermittently
|
||||||
|
# hanging on load. `Alt-Svc: clear` actively drops any cached alternative and pins
|
||||||
|
# clients to h2/h1; it is applied site-wide so every route is covered. In the test
|
||||||
|
# contour this caddy serves plain :80 (no h3 to advertise) and the host caddy
|
||||||
|
# re-stamps its own Alt-Svc, so the live test fix lives in the host caddy — here it
|
||||||
|
# is the prod fix. Background + alternatives (incl. serving h3 for real): docs/EDGE_HTTP3.md.
|
||||||
|
header Alt-Svc clear
|
||||||
|
|
||||||
# Operator surfaces under /_gm: a single shared Basic-Auth, then route.
|
# Operator surfaces under /_gm: a single shared Basic-Auth, then route.
|
||||||
@gm path /_gm /_gm/*
|
@gm path /_gm /_gm/*
|
||||||
handle @gm {
|
handle @gm {
|
||||||
|
|||||||
@@ -36,7 +36,21 @@
|
|||||||
"type": "stat",
|
"type": "stat",
|
||||||
"title": "Database size",
|
"title": "Database size",
|
||||||
"gridPos": { "h": 5, "w": 6, "x": 18, "y": 0 },
|
"gridPos": { "h": 5, "w": 6, "x": 18, "y": 0 },
|
||||||
"fieldConfig": { "defaults": { "unit": "bytes" }, "overrides": [] },
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes",
|
||||||
|
"color": { "mode": "thresholds" },
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{ "color": "green", "value": null },
|
||||||
|
{ "color": "yellow", "value": 8589934592 },
|
||||||
|
{ "color": "red", "value": 17179869184 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
"datasource": { "type": "prometheus", "uid": "prometheus" },
|
"datasource": { "type": "prometheus", "uid": "prometheus" },
|
||||||
"targets": [{ "refId": "A", "expr": "max(pg_database_size_bytes{datname=\"scrabble\"})" }]
|
"targets": [{ "refId": "A", "expr": "max(pg_database_size_bytes{datname=\"scrabble\"})" }]
|
||||||
},
|
},
|
||||||
|
|||||||
+11
-3
@@ -158,7 +158,12 @@ arrive from a platform rather than completing a mandatory registration).
|
|||||||
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
|
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
|
||||||
any bot-scoped language, and the friend-invite **share link** (and its caption) point at
|
any bot-scoped language, and the friend-invite **share link** (and its caption) point at
|
||||||
that one bot. First Telegram contact seeds the new account's `preferred_language` from the
|
that one bot. First Telegram contact seeds the new account's `preferred_language` from the
|
||||||
launch `language_code` (§4); the interface language is otherwise edited in Settings.
|
launch `language_code` (§4), but the **interface language follows the device** — the system
|
||||||
|
guess, or an explicit Settings choice saved locally — and the bot never dictates the UI.
|
||||||
|
`preferred_language` is then **reconciled to the active interface locale on every session
|
||||||
|
adopt** (not only on a Settings change; a no-op for guests and when already equal), so the
|
||||||
|
server-rendered language surfaces — this push and the ad banner — always match the UI rather
|
||||||
|
than stranding a user who never opened Settings on the creation-time seed.
|
||||||
- **Variant preferences (New Game gating).** Which variants a player may be matched into is a
|
- **Variant preferences (New Game gating).** Which variants a player may be matched into is a
|
||||||
per-user **profile** setting — `variant_preferences`, a set of `engine.Variant` labels
|
per-user **profile** setting — `variant_preferences`, a set of `engine.Variant` labels
|
||||||
(`scrabble_en`, `scrabble_ru`, `erudit_ru`) edited on the Settings/Profile screen. New
|
(`scrabble_en`, `scrabble_ru`, `erudit_ru`) edited on the Settings/Profile screen. New
|
||||||
@@ -640,7 +645,7 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
|
|||||||
**floats games with any unread entry to the top** of the your-turn and opponent-turn
|
**floats games with any unread entry to the top** of the your-turn and opponent-turn
|
||||||
sections (the finished section keeps its activity order). On each clear the publish-to-read
|
sections (the finished section keeps its activity order). On each clear the publish-to-read
|
||||||
latency is recorded; the read time itself is not retained.
|
latency is recorded; the read time itself is not retained.
|
||||||
- **Profile**: `preferred_language` (en/ru, edited in Settings), display name, email
|
- **Profile**: `preferred_language` (en/ru; tracks the interface language — §4), display name, email
|
||||||
(confirm-code binding, see §4), **timezone**, the daily **away window**, the
|
(confirm-code binding, see §4), **timezone**, the daily **away window**, the
|
||||||
**variant preferences** (`variant_preferences`, the matchable-variant set that gates New
|
**variant preferences** (`variant_preferences`, the matchable-variant set that gates New
|
||||||
Game — §3, defaulting to Erudit only, at least one enforced) and the
|
Game — §3, defaulting to Erudit only, at least one enforced) and the
|
||||||
@@ -1093,7 +1098,10 @@ Two contours, two secret/variable prefixes (`TEST_` / `PROD_`):
|
|||||||
the **main host** runs the full stack (`docker-compose.yml` + `docker-compose.prod.yml`),
|
the **main host** runs the full stack (`docker-compose.yml` + `docker-compose.prod.yml`),
|
||||||
the **bot host** runs only the bot (`docker-compose.bot.yml`, no VPN — native Bot API
|
the **bot host** runs only the bot (`docker-compose.bot.yml`, no VPN — native Bot API
|
||||||
egress, telemetry off). There is no host caddy, so the contour caddy terminates TLS —
|
egress, telemetry off). There is no host caddy, so the contour caddy terminates TLS —
|
||||||
`CADDY_SITE_ADDRESS` is the domain and caddy does its own ACME. The gateway **publishes**
|
`CADDY_SITE_ADDRESS` is the domain and caddy does its own ACME. Caddy advertises HTTP/3 by default, but UDP/443 is not exposed (the
|
||||||
|
compose maps only TCP and ufw opens 443/tcp), so the edge emits `Alt-Svc: clear` to keep
|
||||||
|
clients on h2/h1 rather than stall on a dead QUIC path — see [`EDGE_HTTP3.md`](EDGE_HTTP3.md).
|
||||||
|
The gateway **publishes**
|
||||||
the bot-link `:9443`; the remote bot dials it over mTLS (certs from `PROD_BOTLINK_*`,
|
the bot-link `:9443`; the remote bot dials it over mTLS (certs from `PROD_BOTLINK_*`,
|
||||||
ServerName `gateway`, so TLS validation is independent of the public dial address), holds
|
ServerName `gateway`, so TLS validation is independent of the public dial address), holds
|
||||||
no inbound port, and login is unaffected if that host or the link is down.
|
no inbound port, and login is unaffected if that host or the link is down.
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Edge HTTP/3 (`Alt-Svc`) policy
|
||||||
|
|
||||||
|
## TL;DR
|
||||||
|
|
||||||
|
The edge **advertises HTTP/3 but does not actually serve it** (UDP/443 is not exposed),
|
||||||
|
so we suppress the advert with `Alt-Svc: clear`. Advertising QUIC on `:443/udp` while
|
||||||
|
that port is unreachable makes clients — notably the Telegram Mini App webview — stall
|
||||||
|
on a dead QUIC connection before falling back to h2, which shows up as the app "hanging
|
||||||
|
on load".
|
||||||
|
|
||||||
|
## Symptom
|
||||||
|
|
||||||
|
Opening the Mini App intermittently hangs on load: from a barely-noticeable pause to
|
||||||
|
several seconds, sometimes a blank window that never finishes downloading `index.html`.
|
||||||
|
Intermittent, worse after the first successful visit, reproduced on both the test
|
||||||
|
contour and prod.
|
||||||
|
|
||||||
|
## Root cause
|
||||||
|
|
||||||
|
Caddy enables HTTP/3 by default on any TLS listener and emits
|
||||||
|
`Alt-Svc: h3=":443"; ma=2592000` — telling every client "reach me over QUIC/UDP 443"
|
||||||
|
and to cache that for 30 days. But UDP/443 is **never reachable end to end**:
|
||||||
|
|
||||||
|
- **Test contour**: the host caddy publishes only `:443/tcp` (`docker port caddy` shows
|
||||||
|
no `udp`); QUIC packets from the internet are dropped.
|
||||||
|
- **Prod**: `deploy/docker-compose.prod.yml` maps `"443:443"` (Docker = **TCP only**)
|
||||||
|
and `deploy/ansible/roles/main/tasks/main.yml` opens 443 `proto: tcp`. UDP/443 is
|
||||||
|
dropped at both the publish and the firewall.
|
||||||
|
|
||||||
|
Caddy *does* bind `udp/443` inside the container and h3 works container-to-container
|
||||||
|
(verified `http=3 code=200`), so the listener is healthy — it is simply not exposed.
|
||||||
|
|
||||||
|
A client that cached the advert tries QUIC first on later opens, gets no response, and
|
||||||
|
waits for the QUIC attempt to time out before falling back to TCP/h2. That wait is the
|
||||||
|
stall. The very first visit (no cached `Alt-Svc`) uses h2 and is fast.
|
||||||
|
|
||||||
|
The h2/TCP serving path itself is healthy: 30 fresh-TLS requests through the full path
|
||||||
|
(host caddy -> contour caddy -> gateway) measured TTFB ~9.5 ms, total ~9.8 ms, no tail;
|
||||||
|
`index.html` is ~1 KB.
|
||||||
|
|
||||||
|
## Fix in place (option A — suppress the advert)
|
||||||
|
|
||||||
|
Emit `Alt-Svc: clear`, which actively drops any cached alternative (better than merely
|
||||||
|
deleting the header, which leaves the sticky 30-day cache in place):
|
||||||
|
|
||||||
|
- **Prod / repo**: `deploy/caddy/Caddyfile` — a site-level `header Alt-Svc clear` (this
|
||||||
|
caddy terminates TLS in prod).
|
||||||
|
- **Test contour**: the host caddy terminates TLS, so the fix lives there (homelab
|
||||||
|
config, outside this repo): `header Alt-Svc clear` on the `scrabble.*` site. The
|
||||||
|
in-compose caddy serves plain `:80` in test and never advertises h3, so the repo
|
||||||
|
directive is a harmless no-op there (the host caddy re-stamps the header).
|
||||||
|
|
||||||
|
`header Alt-Svc clear` overrides Caddy's auto-advert (verified) and is site-scoped.
|
||||||
|
|
||||||
|
### Verify
|
||||||
|
|
||||||
|
The runner/prod host shell cannot reach the Docker bridge IPs directly, so probe from a
|
||||||
|
container on the relevant network, using `--resolve` to hit the TLS-terminating caddy by
|
||||||
|
its bridge IP (this also bypasses the public-IP NAT hairpin):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# <edge-ip> = the TLS-terminating caddy's IP on its network (docker inspect ... )
|
||||||
|
docker run --rm --network edge curlimages/curl:latest -sS -D - -o /dev/null \
|
||||||
|
--resolve <host>:443:<edge-ip> https://<host>/telegram/ | grep -iE '^HTTP|^alt-svc'
|
||||||
|
# expect: HTTP/2 200, and NO `alt-svc: h3=...` (the header is absent or `alt-svc: clear`)
|
||||||
|
```
|
||||||
|
|
||||||
|
## If it recurs — alternatives to try
|
||||||
|
|
||||||
|
So we do not re-derive the diagnosis from scratch:
|
||||||
|
|
||||||
|
1. **Re-confirm the advert is actually suppressed** with the verify command above. A
|
||||||
|
redeploy or a Caddy upgrade could regress it, or a client may still hold a cached
|
||||||
|
`h3` entry that has not yet been replaced by a `clear` (it needs one successful h2
|
||||||
|
response to receive the `clear`).
|
||||||
|
2. **Option B — serve HTTP/3 for real** instead of suppressing it. Worth it only if we
|
||||||
|
actually want QUIC (the benefit is marginal for a ~1 KB shell plus hash-immutable
|
||||||
|
cached assets, and it adds UDP/QUIC attack surface):
|
||||||
|
- Publish UDP: add `"443:443/udp"` next to the TCP map in
|
||||||
|
`deploy/docker-compose.prod.yml` (and publish udp/443 on the test host caddy too).
|
||||||
|
- Open the firewall: add a `443 proto: udp` rule in
|
||||||
|
`deploy/ansible/roles/main/tasks/main.yml`.
|
||||||
|
- Drop the `header Alt-Svc clear` so Caddy advertises h3 again.
|
||||||
|
- Verify with an h3 client from inside the network:
|
||||||
|
`docker run --rm --network edge ymuski/curl-http3 curl --http3-only ...` should
|
||||||
|
return `http=3 code=200`.
|
||||||
|
3. **Look past the edge** if the advert is suppressed and stalls persist. The h2 path is
|
||||||
|
fast server-side, so a remaining stall is most likely the client network / RTT / the
|
||||||
|
provider, not our stack. Re-run the timing loop (below) to confirm the server is
|
||||||
|
still <~10 ms TTFB before chasing the client side.
|
||||||
|
|
||||||
|
## How this was diagnosed (method, to repeat)
|
||||||
|
|
||||||
|
- The runner/prod host shell cannot reach the Docker bridge subnets, so all probing runs
|
||||||
|
from a throwaway container on the target network (`docker run --network <net>
|
||||||
|
curlimages/curl`), using `--resolve <host>:443:<edge-ip>` to bypass the public-IP NAT
|
||||||
|
hairpin and exercise the real TLS path.
|
||||||
|
- Compare a fresh-connection timing loop (worst case, full TLS each time) against a
|
||||||
|
keepalive batch to separate handshake cost from serving cost:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run --rm --network edge curlimages/curl:latest sh -c '
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
curl -sS -o /dev/null --resolve <host>:443:<edge-ip> \
|
||||||
|
-w "http=%{http_version} code=%{http_code} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
|
||||||
|
https://<host>/telegram/
|
||||||
|
done'
|
||||||
|
```
|
||||||
|
|
||||||
|
- `docker port <caddy>` shows whether `udp/443` is actually published; the response
|
||||||
|
`Alt-Svc` header shows what the edge advertises. The two disagreeing is the bug.
|
||||||
@@ -38,10 +38,17 @@ Telegram identity to an account from a browser. Both map a rejection to gRPC
|
|||||||
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
||||||
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
||||||
false when the kind is not rendered out-of-app or the user never started the bot).
|
false when the kind is not rendered out-of-app or the user never started the bot).
|
||||||
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a Mini App
|
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a localized
|
||||||
launch button; a deep-link payload routes the launch to a game / invitation / friend
|
welcome and a Mini App launch button; a deep-link payload routes the launch to a game /
|
||||||
code. This is **self-contained** — the bot never calls back into the game, so `/start`
|
invitation / friend code. The welcome is **Russian or English** by the sender's reported
|
||||||
onboarding works even when the game is down.
|
Telegram language (`Message.from.language_code`, which the Bot API carries on the message
|
||||||
|
itself — no separate user-update event — English fallback) and links the game channel and
|
||||||
|
discussion chat by their public `@username`, **resolved once at startup** from
|
||||||
|
`TELEGRAM_GAME_CHANNEL_ID` / `TELEGRAM_CHAT_ID` via `getChat` (a chat that is unset,
|
||||||
|
private, or unreadable degrades that link to a generic noun — "the channel" / "our
|
||||||
|
chat" — rather than a dangling "@"). This is otherwise **self-contained**
|
||||||
|
— the bot never calls back into the game, so `/start` onboarding works even when the game
|
||||||
|
is down.
|
||||||
- **Moderated-chat gating.** When `TELEGRAM_CHAT_ID` names a channel's linked discussion
|
- **Moderated-chat gating.** When `TELEGRAM_CHAT_ID` names a channel's linked discussion
|
||||||
group, the bot gates who may write there. The group **allows sending by default** (a
|
group, the bot gates who may write there. The group **allows sending by default** (a
|
||||||
human setting) and the bot only **restricts** — Telegram intersects the chat default with
|
human setting) and the bot only **restricts** — Telegram intersects the chat default with
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ func run(ctx context.Context, cfg config.BotConfig, logger *zap.Logger) error {
|
|||||||
MiniAppURL: cfg.MiniAppURL,
|
MiniAppURL: cfg.MiniAppURL,
|
||||||
SendRatePerSecond: cfg.SendRatePerSecond,
|
SendRatePerSecond: cfg.SendRatePerSecond,
|
||||||
ChatID: cfg.ChatID,
|
ChatID: cfg.ChatID,
|
||||||
|
GameChannelID: cfg.GameChannelID,
|
||||||
}, logger)
|
}, logger)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -33,8 +33,12 @@ type Config struct {
|
|||||||
SendRatePerSecond int
|
SendRatePerSecond int
|
||||||
// ChatID is the moderated discussion chat the bot gates write access in; 0
|
// ChatID is the moderated discussion chat the bot gates write access in; 0
|
||||||
// disables chat gating (and the chat_member long-poll subscription). Gating needs
|
// disables chat gating (and the chat_member long-poll subscription). Gating needs
|
||||||
// the bot to be an administrator there with the restrict-members right.
|
// the bot to be an administrator there with the restrict-members right. Its public
|
||||||
|
// @username is also resolved at startup for the /start welcome's discussion link.
|
||||||
ChatID int64
|
ChatID int64
|
||||||
|
// GameChannelID is the game channel whose public @username the /start welcome links
|
||||||
|
// to (resolved from this id via getChat at startup); 0 omits that follow link.
|
||||||
|
GameChannelID int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// EligibilityResolver answers whether the Telegram user identified by externalID
|
// EligibilityResolver answers whether the Telegram user identified by externalID
|
||||||
@@ -54,6 +58,13 @@ type Bot struct {
|
|||||||
limiter *rate.Limiter
|
limiter *rate.Limiter
|
||||||
// chatID is the moderated discussion chat (0 disables gating).
|
// chatID is the moderated discussion chat (0 disables gating).
|
||||||
chatID int64
|
chatID int64
|
||||||
|
// channelID is the game channel (0 omits its welcome follow link).
|
||||||
|
channelID int64
|
||||||
|
// channelUsername and chatUsername are the public @usernames (without the leading
|
||||||
|
// @) of the game channel and the discussion chat, resolved once at startup
|
||||||
|
// (resolveWelcomeHandles) for the /start welcome's follow links; "" when unresolved.
|
||||||
|
channelUsername string
|
||||||
|
chatUsername string
|
||||||
// botID is the bot's own Telegram user id (resolved at startup); it skips the
|
// botID is the bot's own Telegram user id (resolved at startup); it skips the
|
||||||
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
|
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
|
||||||
botID int64
|
botID int64
|
||||||
@@ -69,7 +80,7 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
|
|||||||
if log == nil {
|
if log == nil {
|
||||||
log = zap.NewNop()
|
log = zap.NewNop()
|
||||||
}
|
}
|
||||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID}
|
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID, channelID: cfg.GameChannelID}
|
||||||
if cfg.SendRatePerSecond > 0 {
|
if cfg.SendRatePerSecond > 0 {
|
||||||
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
||||||
}
|
}
|
||||||
@@ -123,9 +134,43 @@ func (t *Bot) Run(ctx context.Context) {
|
|||||||
if t.chatID != 0 {
|
if t.chatID != 0 {
|
||||||
t.logChatAdminStatus(ctx)
|
t.logChatAdminStatus(ctx)
|
||||||
}
|
}
|
||||||
|
t.resolveWelcomeHandles(ctx)
|
||||||
t.api.Start(ctx)
|
t.api.Start(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveWelcomeHandles resolves, once at startup, the public @usernames of the game
|
||||||
|
// channel and the discussion chat from their configured ids (getChat), caching them for
|
||||||
|
// the /start welcome's follow links. It runs before the update loop, so the handles are
|
||||||
|
// set before any /start is handled; a chat that is unset, private (no public username)
|
||||||
|
// or unreadable simply leaves its handle empty and the welcome omits that follow link.
|
||||||
|
func (t *Bot) resolveWelcomeHandles(ctx context.Context) {
|
||||||
|
t.channelUsername = t.resolveUsername(ctx, t.channelID, "game channel")
|
||||||
|
t.chatUsername = t.resolveUsername(ctx, t.chatID, "discussion chat")
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveUsername returns the public @username (without the leading @) of the chat with
|
||||||
|
// the given id, or "" when id is 0, the chat has no public username, or getChat fails —
|
||||||
|
// logging the reason, since a missing handle silently drops a welcome follow link.
|
||||||
|
func (t *Bot) resolveUsername(ctx context.Context, id int64, label string) string {
|
||||||
|
if id == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
chat, err := t.api.GetChat(ctx, &tgbot.GetChatParams{ChatID: id})
|
||||||
|
if err != nil {
|
||||||
|
t.log.Warn("welcome: getChat failed; follow link omitted",
|
||||||
|
zap.String("chat", label), zap.Int64("id", id), zap.Error(err))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if chat.Username == "" {
|
||||||
|
t.log.Warn("welcome: chat has no public @username; follow link omitted",
|
||||||
|
zap.String("chat", label), zap.Int64("id", id))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
t.log.Info("welcome: resolved follow link",
|
||||||
|
zap.String("chat", label), zap.String("username", chat.Username))
|
||||||
|
return chat.Username
|
||||||
|
}
|
||||||
|
|
||||||
// logChatAdminStatus checks, at startup, whether the bot can actually gate the
|
// logChatAdminStatus checks, at startup, whether the bot can actually gate the
|
||||||
// moderated chat — it must be an administrator there with the restrict-members
|
// moderated chat — it must be an administrator there with the restrict-members
|
||||||
// ("Ban users") right, or Telegram delivers no chat_member updates and restricts
|
// ("Ban users") right, or Telegram delivers no chat_member updates and restricts
|
||||||
@@ -198,11 +243,19 @@ func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Up
|
|||||||
if update.Message.Chat.Type != models.ChatTypePrivate {
|
if update.Message.Chat.Type != models.ChatTypePrivate {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// The sender's Telegram language rides on the message itself (Message.from.language_code
|
||||||
|
// in the Bot API — there is no separate user-update event); fall back to English when it
|
||||||
|
// is absent.
|
||||||
|
lang := ""
|
||||||
|
if update.Message.From != nil {
|
||||||
|
lang = update.Message.From.LanguageCode
|
||||||
|
}
|
||||||
|
text, button := startText(lang, t.channelUsername, t.chatUsername)
|
||||||
startParam := startPayload(update.Message.Text)
|
startParam := startPayload(update.Message.Text)
|
||||||
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
|
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
|
||||||
ChatID: update.Message.Chat.ID,
|
ChatID: update.Message.Chat.ID,
|
||||||
Text: "Tap to open Scrabble.",
|
Text: text,
|
||||||
ReplyMarkup: t.launchMarkup("Open Scrabble", startParam),
|
ReplyMarkup: t.launchMarkup(button, startParam),
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
t.log.Warn("reply to start failed", zap.Error(err))
|
t.log.Warn("reply to start failed", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ func (f *fakeBotAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
f.text = r.FormValue("text")
|
f.text = r.FormValue("text")
|
||||||
f.replyMarkup = r.FormValue("reply_markup")
|
f.replyMarkup = r.FormValue("reply_markup")
|
||||||
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
|
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/getChat"):
|
||||||
|
// Echo the requested id into the username so a resolver test can tell the
|
||||||
|
// channel lookup from the chat lookup.
|
||||||
|
io.WriteString(w, `{"ok":true,"result":{"id":-100,"type":"channel","username":"u`+r.FormValue("chat_id")+`"}}`)
|
||||||
default:
|
default:
|
||||||
io.WriteString(w, `{"ok":true,"result":true}`)
|
io.WriteString(w, `{"ok":true,"result":true}`)
|
||||||
}
|
}
|
||||||
@@ -105,7 +109,7 @@ func TestTestEnvironmentRoutesGetMe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
||||||
t.Run("private replies", func(t *testing.T) {
|
t.Run("private replies in english by default", func(t *testing.T) {
|
||||||
api := &fakeBotAPI{}
|
api := &fakeBotAPI{}
|
||||||
b := newTestBot(t, api)
|
b := newTestBot(t, api)
|
||||||
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
@@ -114,6 +118,35 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
|||||||
if api.chatID != "42" || !strings.Contains(api.replyMarkup, "web_app") {
|
if api.chatID != "42" || !strings.Contains(api.replyMarkup, "web_app") {
|
||||||
t.Errorf("private /start: chat=%q markup=%q, want a web_app reply", api.chatID, api.replyMarkup)
|
t.Errorf("private /start: chat=%q markup=%q, want a web_app reply", api.chatID, api.replyMarkup)
|
||||||
}
|
}
|
||||||
|
// No reported language -> English welcome + English button.
|
||||||
|
if !strings.Contains(api.text, "Hi!") {
|
||||||
|
t.Errorf("text = %q, want the English welcome", api.text)
|
||||||
|
}
|
||||||
|
if !strings.Contains(api.replyMarkup, "Open") {
|
||||||
|
t.Errorf("reply_markup = %q, want the English button", api.replyMarkup)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("uses the sender's reported language", func(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
|
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||||
|
From: &models.User{ID: 7, LanguageCode: "ru"},
|
||||||
|
}})
|
||||||
|
if !strings.Contains(api.text, "Привет!") {
|
||||||
|
t.Errorf("text = %q, want the Russian welcome for a ru sender", api.text)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("embeds resolved follow handles", func(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.channelUsername, b.chatUsername = "erudit", "erudite_chat"
|
||||||
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
|
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||||
|
}})
|
||||||
|
if !strings.Contains(api.text, "@erudit") || !strings.Contains(api.text, "@erudite_chat") {
|
||||||
|
t.Errorf("text = %q, want the follow handles", api.text)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
t.Run("group ignored", func(t *testing.T) {
|
t.Run("group ignored", func(t *testing.T) {
|
||||||
api := &fakeBotAPI{}
|
api := &fakeBotAPI{}
|
||||||
@@ -127,6 +160,26 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResolveWelcomeHandles(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.channelID, b.chatID = 111, 222
|
||||||
|
b.resolveWelcomeHandles(context.Background())
|
||||||
|
// The fake echoes the requested id into the username, so each lookup is independent.
|
||||||
|
if b.channelUsername != "u111" {
|
||||||
|
t.Errorf("channelUsername = %q, want u111", b.channelUsername)
|
||||||
|
}
|
||||||
|
if b.chatUsername != "u222" {
|
||||||
|
t.Errorf("chatUsername = %q, want u222", b.chatUsername)
|
||||||
|
}
|
||||||
|
// An unset id resolves to no handle (and makes no getChat call).
|
||||||
|
b.channelID = 0
|
||||||
|
b.resolveWelcomeHandles(context.Background())
|
||||||
|
if b.channelUsername != "" {
|
||||||
|
t.Errorf("channelUsername = %q, want empty for id 0", b.channelUsername)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestStartPayload(t *testing.T) {
|
func TestStartPayload(t *testing.T) {
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
"/start g123": "g123",
|
"/start g123": "g123",
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package bot
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// startText returns the localized /start welcome body and the launch-button label.
|
||||||
|
// Russian is used when lang (the IETF language tag the Telegram client reports on the
|
||||||
|
// message's sender) starts with "ru", English otherwise and when it is absent — so a
|
||||||
|
// user with no reported language still gets a sensible message. channel and chat are
|
||||||
|
// the resolved public @usernames (without the leading @) of the game channel and the
|
||||||
|
// discussion chat; when either is empty its follow link degrades to a generic noun
|
||||||
|
// (e.g. "the channel" / "our chat") rather than rendering a dangling "@", since the
|
||||||
|
// bot's own info screen still lists the real links.
|
||||||
|
func startText(lang, channel, chat string) (text, button string) {
|
||||||
|
if strings.HasPrefix(strings.ToLower(lang), "ru") {
|
||||||
|
return ruWelcome(channel, chat), "Открыть «Эрудит»"
|
||||||
|
}
|
||||||
|
return enWelcome(channel, chat), "Open “Erudite”"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ruWelcome builds the Russian welcome. A known handle is named as "@<username>"; an
|
||||||
|
// unresolved one degrades to a plain noun.
|
||||||
|
func ruWelcome(channel, chat string) string {
|
||||||
|
ch := "канал"
|
||||||
|
if channel != "" {
|
||||||
|
ch = "@" + channel
|
||||||
|
}
|
||||||
|
ct := "чате"
|
||||||
|
if chat != "" {
|
||||||
|
ct = "@" + chat
|
||||||
|
}
|
||||||
|
return strings.Join([]string{
|
||||||
|
"Привет! 👋",
|
||||||
|
"Здесь можно сражаться в «Эрудит» со случайными игроками или в компании друзей.",
|
||||||
|
"Подписывайтесь на " + ch + ", чтобы быть в курсе последних игровых событий и вовремя " +
|
||||||
|
"получать важные уведомления. Игроки могут обсуждать игру и просто общаться в нашем " +
|
||||||
|
ct + "! 💬",
|
||||||
|
"Ни слова больше.\nПервая партия сама себя не сыграет 😊",
|
||||||
|
}, "\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// enWelcome builds the English welcome (the fallback for any non-Russian or missing
|
||||||
|
// language). A known handle is named as "@<username>"; an unresolved one degrades to a
|
||||||
|
// plain noun.
|
||||||
|
func enWelcome(channel, chat string) string {
|
||||||
|
ch := "the channel"
|
||||||
|
if channel != "" {
|
||||||
|
ch = "@" + channel
|
||||||
|
}
|
||||||
|
ct := "group chat"
|
||||||
|
if chat != "" {
|
||||||
|
ct = "@" + chat
|
||||||
|
}
|
||||||
|
return strings.Join([]string{
|
||||||
|
"Hi! 👋",
|
||||||
|
"Play Scrabble against random players — or with a group of friends.",
|
||||||
|
"Follow " + ch + " to stay up to date with the latest game events and receive important " +
|
||||||
|
"notifications in time. Players can discuss the game and simply chat in our " + ct + "! 💬",
|
||||||
|
"Okay, no more talking.\nFirst game won't play itself 😊",
|
||||||
|
}, "\n\n")
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package bot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStartTextLocalizesByLanguage(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
lang string
|
||||||
|
wantButton string
|
||||||
|
wantSubstr string // a phrase unique to the chosen language body
|
||||||
|
}{
|
||||||
|
{"russian", "ru", "Открыть «Эрудит»", "Привет!"},
|
||||||
|
{"russian region tag", "ru-RU", "Открыть «Эрудит»", "Первая партия"},
|
||||||
|
{"english", "en", "Open “Erudite”", "Hi!"},
|
||||||
|
{"other language falls back to english", "de", "Open “Erudite”", "Hi!"},
|
||||||
|
{"absent language falls back to english", "", "Open “Erudite”", "no more talking"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
text, button := startText(tc.lang, "erudit", "erudite_chat")
|
||||||
|
if button != tc.wantButton {
|
||||||
|
t.Errorf("button = %q, want %q", button, tc.wantButton)
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, tc.wantSubstr) {
|
||||||
|
t.Errorf("text %q does not contain %q", text, tc.wantSubstr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartTextEmbedsFollowHandles(t *testing.T) {
|
||||||
|
for _, lang := range []string{"ru", "en"} {
|
||||||
|
text, _ := startText(lang, "erudit", "erudite_chat")
|
||||||
|
if !strings.Contains(text, "@erudit") || !strings.Contains(text, "@erudite_chat") {
|
||||||
|
t.Errorf("lang %q: follow paragraph missing the handles: %q", lang, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartTextFallsBackToGenericWhenHandleMissing(t *testing.T) {
|
||||||
|
// An unresolved handle degrades to a generic noun rather than a dangling "@" — and
|
||||||
|
// only that slot degrades; a resolved sibling still shows its "@username".
|
||||||
|
t.Run("both missing leaves no @", func(t *testing.T) {
|
||||||
|
for _, lang := range []string{"ru", "en"} {
|
||||||
|
text, _ := startText(lang, "", "")
|
||||||
|
if strings.Contains(text, "@") {
|
||||||
|
t.Errorf("lang %q: text shows a dangling @: %q", lang, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The generic nouns are present in each language.
|
||||||
|
ru, _ := startText("ru", "", "")
|
||||||
|
if !strings.Contains(ru, "на канал") || !strings.Contains(ru, "в нашем чате") {
|
||||||
|
t.Errorf("russian generic fallback missing: %q", ru)
|
||||||
|
}
|
||||||
|
en, _ := startText("en", "", "")
|
||||||
|
if !strings.Contains(en, "Follow the channel") || !strings.Contains(en, "in our group chat") {
|
||||||
|
t.Errorf("english generic fallback missing: %q", en)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("only the missing slot degrades", func(t *testing.T) {
|
||||||
|
// Channel resolved, chat missing: the channel keeps its @handle, the chat is generic.
|
||||||
|
en, _ := startText("en", "erudit", "")
|
||||||
|
if !strings.Contains(en, "@erudit") || strings.Contains(en, "@erudite") {
|
||||||
|
t.Errorf("channel handle not shown / chat handle leaked: %q", en)
|
||||||
|
}
|
||||||
|
if !strings.Contains(en, "in our group chat") {
|
||||||
|
t.Errorf("chat slot did not degrade to a generic noun: %q", en)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
+17
-18
@@ -68,7 +68,6 @@ export const app = $state<{
|
|||||||
locale: Locale;
|
locale: Locale;
|
||||||
reduceMotion: boolean;
|
reduceMotion: boolean;
|
||||||
boardLabels: BoardLabelMode;
|
boardLabels: BoardLabelMode;
|
||||||
localeLocked: boolean;
|
|
||||||
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
|
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
|
||||||
notifications: number;
|
notifications: number;
|
||||||
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
|
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
|
||||||
@@ -109,7 +108,6 @@ export const app = $state<{
|
|||||||
locale: 'en',
|
locale: 'en',
|
||||||
reduceMotion: false,
|
reduceMotion: false,
|
||||||
boardLabels: 'beginner',
|
boardLabels: 'beginner',
|
||||||
localeLocked: false,
|
|
||||||
notifications: 0,
|
notifications: 0,
|
||||||
chatUnread: {},
|
chatUnread: {},
|
||||||
messageUnread: {},
|
messageUnread: {},
|
||||||
@@ -451,18 +449,20 @@ async function adoptSession(s: Session): Promise<void> {
|
|||||||
await saveSession(s);
|
await saveSession(s);
|
||||||
try {
|
try {
|
||||||
app.profile = await gateway.profileGet();
|
app.profile = await gateway.profileGet();
|
||||||
// The live interface language follows the device — the explicit local choice (locked, saved
|
// The live interface language follows the device — the explicit local choice (saved in
|
||||||
// in prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
// prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
||||||
// account here. preferred_language stays the user's saved choice (written from Settings,
|
// account here: the Telegram bot a user signs in through must not dictate the UI, so a
|
||||||
// and used for out-of-app push routing), but the Telegram bot a user signs in through must
|
// ru-bot launch on an English system stays English.
|
||||||
// not dictate the UI: a ru-bot launch on an English system stays English.
|
|
||||||
//
|
//
|
||||||
// But the banner and out-of-app push routing ARE resolved from preferred_language, so an
|
// The banner and out-of-app push are resolved server-side from preferred_language, so it
|
||||||
// explicit device choice the account has not recorded yet (picked while a guest, or
|
// must track whatever language the UI actually shows — the explicit choice AND the system
|
||||||
// differing from the Telegram system-language seed) would otherwise leave them in the wrong
|
// guess. Reconcile it to the active locale on every adopt, not only after an explicit
|
||||||
// language until the next Settings change. Reconcile the account to the saved local choice
|
// Settings choice: a user who never opened Settings would otherwise be stuck on the
|
||||||
// here; persistLanguageToServer no-ops for guests and when already equal.
|
// creation-time seed — e.g. an English banner under a Russian UI. This keeps every
|
||||||
if (app.localeLocked) void persistLanguageToServer(app.locale);
|
// server-rendered, language-dependent surface (banner, out-of-app push) aligned with the
|
||||||
|
// interface, not just one. persistLanguageToServer self-gates (a no-op for guests and when
|
||||||
|
// already equal), so there is no write in the steady state.
|
||||||
|
void persistLanguageToServer(app.locale);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
handleError(err);
|
handleError(err);
|
||||||
}
|
}
|
||||||
@@ -483,9 +483,10 @@ export async function applyLinkResult(r: LinkResult): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
app.profile = await gateway.profileGet();
|
app.profile = await gateway.profileGet();
|
||||||
// A guest who chose a language and then linked in place now has a durable account: push the
|
// A guest who linked in place now has a durable account: push the active interface language
|
||||||
// saved choice so the banner + push routing follow it (see adoptSession).
|
// so the banner + push routing follow it (see adoptSession — reconciled regardless of an
|
||||||
if (app.localeLocked) void persistLanguageToServer(app.locale);
|
// explicit Settings choice).
|
||||||
|
void persistLanguageToServer(app.locale);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -538,7 +539,6 @@ export async function bootstrap(): Promise<void> {
|
|||||||
applyReduceMotion(app.reduceMotion);
|
applyReduceMotion(app.reduceMotion);
|
||||||
if (prefs.locale) {
|
if (prefs.locale) {
|
||||||
app.locale = prefs.locale;
|
app.locale = prefs.locale;
|
||||||
app.localeLocked = true;
|
|
||||||
setLocale(prefs.locale);
|
setLocale(prefs.locale);
|
||||||
} else {
|
} else {
|
||||||
const guess = localeFrom(typeof navigator !== 'undefined' ? navigator.language : 'en');
|
const guess = localeFrom(typeof navigator !== 'undefined' ? navigator.language : 'en');
|
||||||
@@ -754,7 +754,6 @@ export function setTheme(theme: ThemePref): void {
|
|||||||
|
|
||||||
export function setLocalePref(locale: Locale): void {
|
export function setLocalePref(locale: Locale): void {
|
||||||
app.locale = locale;
|
app.locale = locale;
|
||||||
app.localeLocked = true;
|
|
||||||
setLocale(locale);
|
setLocale(locale);
|
||||||
persistPrefs();
|
persistPrefs();
|
||||||
void persistLanguageToServer(locale);
|
void persistLanguageToServer(locale);
|
||||||
|
|||||||
Reference in New Issue
Block a user