thermograph/backend/daemon/internal/gateway/message_test.go

163 lines
5 KiB
Go
Raw Normal View History

daemon: move the Discord gateway and scheduler out of the web process into Go web/app.py started two long-lived background jobs under a leader election: the Discord gateway bot and an APScheduler. Both are stateful I/O loops -- reconnect, RESUME, heartbeat, backoff, interval timers -- living inside an async web app that also has to serve requests. This moves them into a single Go binary. Go owns ONLY the stateful I/O. It owns no climate or grading logic: anything needing data calls back into Python over a new internal-only HTTP surface (/internal/discord/grade, /internal/jobs/warm-cities, /internal/jobs/indexnow). Grading depends on polars and the parquet cache; reimplementing it in Go would make the bot's grades drift from the API's, and the slash-command path deliberately shares one grade builder so the two can never disagree. The grade route returns gateway-ready JSON -- including the ephemeral-flag drop that discord_bot.py used to do -- and Go relays those bytes verbatim without parsing the embed. Packaging: the binary is built by a golang:1.26 stage in the backend Dockerfile and shipped in the SAME image, run as a second compose service off the SAME tag. The daemon and backend share the /internal/* contract, so they must never skew versions; one image makes that structural rather than a convention. Its entrypoint bypasses entrypoint.sh -- the backend owns alembic, and two racing migrators is a real hazard. replicas: 1 in the Swarm stack is load-bearing. Discord permits exactly one gateway connection per bot token; the pin replaces core/singleton.claim_leader for this workload. update_config uses order: stop-first, since start-first would briefly run two gateways. autoscale.sh targets ${STACK_NAME}_web only, so it cannot scale this. Security: the internal routes compare the token with hmac.compare_digest and the whole router 404s when THERMOGRAPH_INTERNAL_TOKEN is unset -- fail closed, never default open. Caddy only routes /api/*, /digest and /discord/interactions to the backend, so /internal/* was never publicly reachable; the token is defence in depth. The router mounts before the catch-all frontend proxy so /internal/* cannot fall through to it. The daemon refuses to start without the token. Behaviour preserved from the Python, with the reasoning carried into the Go comments: non-privileged intents (no MESSAGE_CONTENT, so no portal review); fatal close codes 4004/4010-4014 stop rather than loop; the bot-author and self-author mention-loop guard; allowed_mentions locked to {"parse":[], "replied_user":true} so a crafted query cannot turn a reply into an @everyone ping; the first cron tick deferred one full interval rather than firing at boot, since warm-cities already runs at deploy time; and no overlapping warm-cities run, which would double-spend the archive-fetch quota. Two deliberate improvements over the Python. A close intended for RESUME now uses 4000 rather than 1000 -- Discord invalidates a session closed 1000/1001, so the Python's default close silently defeated its own resume. And MESSAGE_CREATE is handled on a bounded worker pool rather than an unbounded thread hand-off, so a flood of mentions cannot spawn unbounded work against the backend. A .dockerignore is added because a disposable backend/.venv was being swallowed by COPY . /app/ and duplicated again by the chown layer, inflating the image to 1.8 GB; it builds at 578 MB. Tests: 29 Go gateway tests covering every behaviour the deleted test_discord_bot.py asserted, plus cron/config/apiclient suites; 10 new Python tests for the internal routes (fail-closed, auth, flag drop, per-job 409 guard). Full suite 359 passed / 7 skipped; go build, vet and test -race clean.
2026-07-23 22:33:11 +00:00
// Triage tests: every behaviour asserted by the Python suite
// (backend/tests/notifications/test_discord_bot.py) has an equivalent here,
// minus the ephemeral-flag drop — the /internal/discord/grade route now
// returns gateway-ready JSON, so that concern moved to the Python side.
package gateway
import (
"encoding/json"
"strings"
"testing"
)
const botID = "999"
// testMsg mirrors the Python suite's _msg fixture: author "1" (not a bot),
// message id 42 in channel 77, guild 5 unless overridden.
func testMsg(content string, opts ...func(*gwMessage)) *gwMessage {
m := &gwMessage{
ID: "42",
ChannelID: "77",
GuildID: "5",
Content: content,
Author: gwAuthor{ID: "1"},
}
for _, opt := range opts {
opt(m)
}
return m
}
func fromBot() func(*gwMessage) {
return func(m *gwMessage) { m.Author.Bot = true }
}
func fromID(id string) func(*gwMessage) {
return func(m *gwMessage) { m.Author.ID = snowflake(id) }
}
func mentioning(ids ...string) func(*gwMessage) {
return func(m *gwMessage) {
for _, id := range ids {
m.Mentions = append(m.Mentions, gwAuthor{ID: snowflake(id)})
}
}
}
func asDM() func(*gwMessage) {
return func(m *gwMessage) { m.GuildID = "" }
}
// --- when the bot stays silent ----------------------------------------------
func TestIgnoresOtherBots(t *testing.T) {
act, _ := triage(testMsg("<@999> Phoenix", fromID("8"), fromBot(), mentioning(botID)), botID)
if act != actSilent {
t.Fatalf("bot author should be ignored, got action %d", act)
}
}
func TestIgnoresItsOwnMessages(t *testing.T) {
act, _ := triage(testMsg("hello", fromID(botID), mentioning(botID)), botID)
if act != actSilent {
t.Fatalf("own message should be ignored, got action %d", act)
}
}
func TestIgnoresGuildMessageWithoutAMention(t *testing.T) {
act, _ := triage(testMsg("just chatting"), botID)
if act != actSilent {
t.Fatalf("unmentioned guild message should be ignored, got action %d", act)
}
}
// --- when the bot replies ----------------------------------------------------
func TestMentionWithCityGrades(t *testing.T) {
act, query := triage(testMsg("<@999> Phoenix", mentioning(botID)), botID)
if act != actGrade || query != "Phoenix" {
t.Fatalf("want grade %q, got action %d query %q", "Phoenix", act, query)
}
}
func TestLegacyNicknameMentionIsStripped(t *testing.T) {
act, query := triage(testMsg("<@!999> Tokyo", mentioning(botID)), botID)
if act != actGrade || query != "Tokyo" {
t.Fatalf("want grade %q, got action %d query %q", "Tokyo", act, query)
}
}
func TestDMNeedsNoMention(t *testing.T) {
act, query := triage(testMsg("Berlin", asDM()), botID)
if act != actGrade || query != "Berlin" {
t.Fatalf("want grade %q, got action %d query %q", "Berlin", act, query)
}
}
func TestDMTrimsButKeepsInnerWhitespace(t *testing.T) {
// Parity with the Python DM path (.strip(), not a collapse): only the
// edges are trimmed.
act, query := triage(testMsg(" New York ", asDM()), botID)
if act != actGrade || query != "New York" {
t.Fatalf("want grade %q, got action %d query %q", "New York", act, query)
}
}
func TestMentionWithNoQueryGivesHelp(t *testing.T) {
act, query := triage(testMsg("<@999>", mentioning(botID)), botID)
if act != actHelp || query != "" {
t.Fatalf("want help, got action %d query %q", act, query)
}
if !strings.Contains(strings.ToLower(helpText), "mention me") {
t.Fatalf("help text lost its instruction: %q", helpText)
}
}
// --- helpers -----------------------------------------------------------------
func TestStripMentionsHandlesBothForms(t *testing.T) {
if got := stripMentions("<@999> <@!999> Sao Paulo", botID); got != "Sao Paulo" {
t.Fatalf("want %q, got %q", "Sao Paulo", got)
}
}
func TestIsDMIsTrueWithoutGuildID(t *testing.T) {
if !isDM(testMsg("x", asDM())) {
t.Fatal("message without guild_id should be a DM")
}
if isDM(testMsg("x")) {
t.Fatal("message with guild_id should not be a DM")
}
}
func TestSnowflakeAcceptsStringOrNumber(t *testing.T) {
// The Python compared ids through str() coercion; a numeric id in the
// payload must still count as a mention.
var m gwMessage
raw := `{"id":42,"channel_id":"77","guild_id":"5","content":"<@999> Lima",
"author":{"id":1,"bot":false},"mentions":[{"id":999}]}`
if err := json.Unmarshal([]byte(raw), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if m.ID != "42" || string(m.Author.ID) != "1" {
t.Fatalf("numeric ids mis-decoded: id=%q author=%q", m.ID, m.Author.ID)
}
act, query := triage(&m, botID)
if act != actGrade || query != "Lima" {
t.Fatalf("want grade %q, got action %d query %q", "Lima", act, query)
}
}
func TestIntentsExcludeMessageContent(t *testing.T) {
// The no-privileged-intent constraint is load-bearing: adding
// MESSAGE_CONTENT (1<<15) silently would make Discord close the gateway
// with 4014 until the portal review happens.
if intents != intentGuilds|intentGuildMessages|intentDirectMessages {
t.Fatalf("unexpected intents bitfield: %d", intents)
}
if intents&(1<<15) != 0 {
t.Fatal("intents must not request MESSAGE_CONTENT")
}
}