thermograph/backend/daemon/internal/gateway/gateway_test.go
emi 2d3f37c474
All checks were successful
Sync infra to hosts / sync-beta (push) Successful in 8s
Sync infra to hosts / sync-prod (push) Successful in 7s
secrets-guard / encrypted (push) Successful in 8s
shell-lint / shellcheck (push) Successful in 10s
Build + push backend image (Forgejo registry) / build-push (push) Successful in 1m14s
Deploy backend to beta VPS / deploy (push) Successful in 2m4s
daemon: move the Discord gateway and scheduler out of the web process into Go (#21)
The gateway bot and APScheduler were long-lived stateful I/O loops running
inside the async web app under a leader election. They move into a single Go
binary that owns ONLY that I/O -- websocket, RESUME, heartbeat, backoff, timers.

It owns no grading logic. Anything needing data calls back over a new
internal-only surface (/internal/discord/grade, /internal/jobs/*). Grading
depends on polars and the parquet cache; reimplementing it in Go would let the
bot's grades drift from the API's. The grade route returns gateway-ready JSON
and Go relays the bytes verbatim.

The binary ships in the backend image and runs as a second compose service off
the same tag, so the two ends of the /internal/* contract can never skew.
deploy.sh rolls daemon alongside backend -- without that the service would never
be created, since a single-service deploy uses --no-deps. It also probes the
image first and skips the daemon when rolling a tag that predates the binary:
infra tracks main while image tags are env-staged, so a host can legitimately be
asked to roll an older backend image, and creating the service anyway would
leave a container crash-looping on a missing binary.

replicas: 1 with order: stop-first replaces the leader election -- Discord
permits one gateway connection per bot token.

THERMOGRAPH_INTERNAL_TOKEN is optional: both ends derive it from
THERMOGRAPH_AUTH_SECRET via HMAC under a domain-separation label, so this needs
no new vault entry. The derivation is pinned to a shared cross-language test
vector asserted on both sides, so drift fails CI instead of 401ing every call.
Fail closed when neither secret is set.

Improvements over the Python: a close intended for RESUME uses 4000 rather than
1000 (Discord invalidates a session closed 1000, so the old default defeated its
own resume); MESSAGE_CREATE runs on a bounded worker pool; and a malformed HELLO
returns an error rather than a clean reconnect, which would otherwise reset
backoff and hot-loop against the gateway.

365 Python tests pass; Go build/vet/test -race clean; shellcheck 0 findings.
2026-07-23 22:49:54 +00:00

182 lines
5.8 KiB
Go

// Connection-machinery tests, restricted to the pure parts (backoff, fatal
// close codes, READY/session bookkeeping, sequence tracking). Deliberately no
// live-gateway test — that path is exercised in staging, not CI.
package gateway
import (
"context"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/coder/websocket"
)
func TestBackoffDoublesAndCaps(t *testing.T) {
want := []time.Duration{
2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second,
32 * time.Second, 60 * time.Second, 60 * time.Second, 60 * time.Second,
}
d := backoffStart
for i, w := range want {
d = nextBackoff(d)
if d != w {
t.Fatalf("step %d: want %s, got %s", i, w, d)
}
}
}
func TestFatalCloseCodes(t *testing.T) {
for _, c := range []websocket.StatusCode{4004, 4010, 4011, 4012, 4013, 4014} {
if !isFatalClose(c) {
t.Errorf("close code %d must be fatal (reconnecting loops forever)", c)
}
}
// 4008 (rate limited) and 4009 (session timed out) are resumable; 4000 is
// our own zombie close; -1 is CloseStatus's not-a-close-error sentinel.
for _, c := range []websocket.StatusCode{-1, 1000, 1001, 4000, 4001, 4008, 4009} {
if isFatalClose(c) {
t.Errorf("close code %d must not be fatal", c)
}
}
}
func TestReadyCapturesResumeState(t *testing.T) {
b := New("tok", &fakeGrader{})
sess := &session{}
d := []byte(`{"session_id":"abc","resume_gateway_url":"wss://resume.example/","user":{"id":"999"}}`)
b.dispatch(context.Background(), payload{Op: opDispatch, T: "READY", D: d}, sess)
if sess.sessionID != "abc" {
t.Fatalf("want session id abc, got %q", sess.sessionID)
}
// Trailing slash trimmed, gateway query string appended — RESUME must go
// to the session's own URL with the same v10/json parameters.
if sess.resumeURL != "wss://resume.example/?v=10&encoding=json" {
t.Fatalf("bad resume url: %q", sess.resumeURL)
}
if sess.userID != botID {
t.Fatalf("want user id %s, got %q", botID, sess.userID)
}
}
func TestReadyWithoutResumeURLLeavesItEmpty(t *testing.T) {
b := New("tok", &fakeGrader{})
sess := &session{resumeURL: "wss://stale.example/?v=10&encoding=json"}
d := []byte(`{"session_id":"abc","user":{"id":"999"}}`)
b.dispatch(context.Background(), payload{Op: opDispatch, T: "READY", D: d}, sess)
if sess.resumeURL != "" {
t.Fatalf("a READY without resume_gateway_url must clear the stale url, got %q", sess.resumeURL)
}
}
func TestMessageCreateBeforeReadyIsIgnored(t *testing.T) {
// Until READY supplies our user id we cannot detect mentions (or guard
// against answering ourselves), so nothing may be handled.
g := &fakeGrader{resp: json.RawMessage(`{}`)}
b := New("tok", g)
sess := &session{} // no userID yet
d, err := json.Marshal(testMsg("<@999> Phoenix", mentioning(botID)))
if err != nil {
t.Fatalf("marshal: %v", err)
}
b.dispatch(context.Background(), payload{Op: opDispatch, T: "MESSAGE_CREATE", D: d}, sess)
time.Sleep(20 * time.Millisecond)
if g.callCount() != 0 {
t.Fatal("pre-READY message must be ignored")
}
}
func TestPayloadSequenceIsNullable(t *testing.T) {
var withSeq, withoutSeq payload
if err := json.Unmarshal([]byte(`{"op":0,"t":"X","s":7,"d":{}}`), &withSeq); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if withSeq.S == nil || *withSeq.S != 7 {
t.Fatalf("want seq 7, got %v", withSeq.S)
}
if err := json.Unmarshal([]byte(`{"op":11,"s":null,"d":null}`), &withoutSeq); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if withoutSeq.S != nil {
t.Fatalf("null seq must stay nil, got %v", *withoutSeq.S)
}
}
func TestSessionSeqTracking(t *testing.T) {
sess := &session{}
if _, ok := sess.lastSeq(); ok {
t.Fatal("fresh session must have no sequence number")
}
sess.setSeq(41)
sess.setSeq(42)
if seq, ok := sess.lastSeq(); !ok || seq != 42 {
t.Fatalf("want seq 42, got %d (ok=%v)", seq, ok)
}
}
// A malformed HELLO must be an ERROR, not a clean "reidentify". Run treats a
// clean return as a PLANNED reconnect: backoff resets to 1s and it redials with
// no sleep at all. So if these ever regress to returning nil, a gateway stuck
// sending a bad HELLO becomes a tight reconnect loop against Discord.
func TestParseHelloRejectsMalformedSoBackoffApplies(t *testing.T) {
for _, tc := range []struct {
name string
raw string
}{
{"not json", `{`},
{"wrong op", `{"op":0,"d":{"heartbeat_interval":41250}}`},
{"missing interval", `{"op":10,"d":{}}`},
{"zero interval", `{"op":10,"d":{"heartbeat_interval":0}}`},
{"negative interval", `{"op":10,"d":{"heartbeat_interval":-1}}`},
{"interval wrong type", `{"op":10,"d":{"heartbeat_interval":"soon"}}`},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := parseHello([]byte(tc.raw))
if err == nil {
t.Fatalf("parseHello(%s) = %v, nil; want an error so Run applies backoff", tc.raw, got)
}
if got != 0 {
t.Fatalf("parseHello(%s) interval = %v; want 0 on error", tc.raw, got)
}
})
}
}
func TestParseHelloAcceptsValid(t *testing.T) {
got, err := parseHello([]byte(`{"op":10,"d":{"heartbeat_interval":41250}}`))
if err != nil {
t.Fatalf("parseHello: unexpected error %v", err)
}
if want := 41250 * time.Millisecond; got != want {
t.Fatalf("interval = %v; want %v", got, want)
}
}
// Discord's advertised retry_after is clamped to 5s, matching the Python REST
// helper's _MAX_BACKOFF_S. Replies run on a small fixed worker pool, so a bogus
// server value must not park a slot for minutes.
func TestRetryAfterClamp(t *testing.T) {
for _, tc := range []struct {
name string
body string
want time.Duration
}{
{"honours a sane value", `{"retry_after":2}`, 2 * time.Second},
{"clamps a hostile value", `{"retry_after":600}`, 5 * time.Second},
{"defaults when absent", `{}`, 1 * time.Second},
} {
t.Run(tc.name, func(t *testing.T) {
if got := retryAfter(http.Header{}, []byte(tc.body)); got != tc.want {
t.Fatalf("retryAfter(%s) = %v; want %v", tc.body, got, tc.want)
}
})
}
}