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
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.
204 lines
5.2 KiB
Go
204 lines
5.2 KiB
Go
package cron
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// Intervals here are tens of milliseconds: long enough that scheduler jitter
|
|
// cannot invert an assertion, short enough that the whole file runs in well
|
|
// under a second.
|
|
|
|
func discard() *slog.Logger {
|
|
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
|
}
|
|
|
|
// The first run must be one interval after start, never at startup — the
|
|
// deploy hook already warmed the cache, so a boot-time run is pure waste.
|
|
func TestFirstRunIsDeferredOneInterval(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
var runs atomic.Int32
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
Run(ctx, discard(), Job{
|
|
Name: "test",
|
|
Interval: 60 * time.Millisecond,
|
|
Run: func(context.Context) error {
|
|
runs.Add(1)
|
|
return nil
|
|
},
|
|
})
|
|
}()
|
|
|
|
// Well inside the first interval: nothing may have run yet.
|
|
time.Sleep(20 * time.Millisecond)
|
|
if got := runs.Load(); got != 0 {
|
|
t.Fatalf("job ran %d time(s) before the first interval elapsed; first run must be deferred", got)
|
|
}
|
|
|
|
// Well past the first interval: it must have run by now.
|
|
deadline := time.After(500 * time.Millisecond)
|
|
for runs.Load() == 0 {
|
|
select {
|
|
case <-deadline:
|
|
t.Fatal("job never ran after the first interval elapsed")
|
|
case <-time.After(5 * time.Millisecond):
|
|
}
|
|
}
|
|
|
|
cancel()
|
|
<-done
|
|
}
|
|
|
|
// A slow run must not overlap with itself, and ticks that fired mid-run must
|
|
// be skipped, not queued — an immediate back-to-back run would double-spend
|
|
// the archive-fetch quota just like a concurrent one.
|
|
func TestSlowJobNeverOverlapsAndSkipsMissedTicks(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
const interval = 30 * time.Millisecond
|
|
|
|
var inFlight, maxInFlight, runs atomic.Int32
|
|
release := make(chan struct{})
|
|
started := make(chan struct{}, 16)
|
|
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
Run(ctx, discard(), Job{
|
|
Name: "slow",
|
|
Interval: interval,
|
|
Run: func(context.Context) error {
|
|
n := inFlight.Add(1)
|
|
for {
|
|
m := maxInFlight.Load()
|
|
if n <= m || maxInFlight.CompareAndSwap(m, n) {
|
|
break
|
|
}
|
|
}
|
|
runs.Add(1)
|
|
started <- struct{}{}
|
|
<-release // block until the test lets each run finish
|
|
inFlight.Add(-1)
|
|
return nil
|
|
},
|
|
})
|
|
}()
|
|
|
|
// First run starts; hold it across several intervals.
|
|
<-started
|
|
time.Sleep(4 * interval)
|
|
if got := maxInFlight.Load(); got != 1 {
|
|
t.Fatalf("job overlapped with itself: max in-flight = %d", got)
|
|
}
|
|
if got := runs.Load(); got != 1 {
|
|
t.Fatalf("expected exactly 1 run while the first is still blocked, got %d", got)
|
|
}
|
|
release <- struct{}{}
|
|
|
|
// After release the schedule resumes, but the ticks missed during the
|
|
// block must have been dropped: the next run arrives roughly one interval
|
|
// later, and only one more within that window (not a burst of catch-ups).
|
|
select {
|
|
case <-started:
|
|
case <-time.After(500 * time.Millisecond):
|
|
t.Fatal("job never resumed after the blocked run finished")
|
|
}
|
|
if got := runs.Load(); got != 2 {
|
|
t.Fatalf("missed ticks were replayed as a burst: %d runs total, want 2", got)
|
|
}
|
|
release <- struct{}{}
|
|
|
|
cancel()
|
|
<-done
|
|
if got := maxInFlight.Load(); got != 1 {
|
|
t.Fatalf("job overlapped with itself: max in-flight = %d", got)
|
|
}
|
|
}
|
|
|
|
// One failed tick must never kill the ticker — nothing restarts the schedule
|
|
// short of a container restart.
|
|
func TestFailedTickDoesNotStopSchedule(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
var runs atomic.Int32
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
Run(ctx, discard(), Job{
|
|
Name: "flaky",
|
|
Interval: 20 * time.Millisecond,
|
|
Run: func(context.Context) error {
|
|
if runs.Add(1) == 1 {
|
|
return errors.New("backend briefly down")
|
|
}
|
|
return nil
|
|
},
|
|
})
|
|
}()
|
|
|
|
deadline := time.After(1 * time.Second)
|
|
for runs.Load() < 3 {
|
|
select {
|
|
case <-deadline:
|
|
t.Fatalf("schedule stalled after a failure: only %d run(s)", runs.Load())
|
|
case <-time.After(5 * time.Millisecond):
|
|
}
|
|
}
|
|
|
|
cancel()
|
|
<-done
|
|
}
|
|
|
|
// Cancellation must stop Run promptly even while a job is mid-call: the job
|
|
// callbacks are ctx-aware HTTP calls, so cancelling the context aborts the
|
|
// in-flight request and the loop must then exit instead of ticking again.
|
|
func TestCancelStopsRunWhileJobInFlight(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
started := make(chan struct{})
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
Run(ctx, discard(),
|
|
Job{
|
|
Name: "blocking",
|
|
Interval: 10 * time.Millisecond,
|
|
Run: func(jobCtx context.Context) error {
|
|
close(started)
|
|
<-jobCtx.Done() // behaves like an HTTP call aborted by cancellation
|
|
return jobCtx.Err()
|
|
},
|
|
},
|
|
// A second, idle job proves Run waits for ALL jobs to stop.
|
|
Job{
|
|
Name: "idle",
|
|
Interval: time.Hour,
|
|
Run: func(context.Context) error { return nil },
|
|
},
|
|
)
|
|
}()
|
|
|
|
<-started
|
|
cancel()
|
|
|
|
select {
|
|
case <-done:
|
|
case <-time.After(1 * time.Second):
|
|
t.Fatal("Run did not return promptly after context cancellation")
|
|
}
|
|
}
|