- internal/jobs replaces explain.Jobs: one registry for every kind of background job, with records in DATA_DIR/jobs. A job's draft is written before its commit, so a failed commit can be saved again (POST /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without paying Claude twice. - Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for running ones while still serving the pages that poll them. - internal/usage records every Claude call's tokens and estimated cost in DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a month reaches it. The stats page shows the admin the spend. - auth.SameOrigin refuses cross-origin writes to admin routes. - The LeetCode importer runs the clone's script without the server's secrets in its environment. - A sync that leaves HEAD where it was skips the re-index. - docs_test.go checks README's route table against the routes, and the CLI page against the root README's commands. - The repo is going private: Gitea links on the site are admin-only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
280 lines
9.0 KiB
Go
280 lines
9.0 KiB
Go
// Command usacosite serves the USACO practice log at /usaco/: the problems
|
|
// from adamf/usaco on the site's Gitea, their solutions and tests, and a few
|
|
// admin edits (problem link, notes, statement, status, the solution itself
|
|
// on the solve page), Claude-written explanations and reviews of recorded
|
|
// explanations that it commits back to git.
|
|
//
|
|
// It is built to sit behind adam-french.co.uk's nginx and borrow its login
|
|
// (internal/auth), like the job tracker. There is no database: the server
|
|
// keeps a clone of the repository in DATA_DIR and pulls it when Gitea's push
|
|
// webhook fires, and every PULL_INTERVAL in case a hook was missed. main
|
|
// reads every setting from the environment (all listed in .env.example),
|
|
// wires the pieces together and registers the routes.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"adam-french.co.uk/usaco-site/internal/audiostore"
|
|
"adam-french.co.uk/usaco-site/internal/auth"
|
|
"adam-french.co.uk/usaco-site/internal/claude"
|
|
"adam-french.co.uk/usaco-site/internal/handlers"
|
|
"adam-french.co.uk/usaco-site/internal/jobs"
|
|
"adam-french.co.uk/usaco-site/internal/repo"
|
|
"adam-french.co.uk/usaco-site/internal/runner"
|
|
"adam-french.co.uk/usaco-site/internal/transcribe"
|
|
"adam-french.co.uk/usaco-site/internal/usage"
|
|
)
|
|
|
|
func main() {
|
|
devMode := os.Getenv("DEV_MODE") == "true"
|
|
if !devMode {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
// Everything is served under basePath, and nginx proxies it without
|
|
// stripping the prefix. The SPA is built for /usaco/ (web/vite.config.js),
|
|
// so changing this means rebuilding it with a matching base.
|
|
basePath := strings.TrimRight(getenv("BASE_PATH", "/usaco"), "/")
|
|
dataDir := getenv("DATA_DIR", "/data")
|
|
staticDir := getenv("STATIC_DIR", "/app/static")
|
|
|
|
// AUTH
|
|
// "forward" (the default) asks the main site; "dev" admits everyone and
|
|
// is refused outside DEV_MODE, so a stray setting cannot open the edits
|
|
// in production.
|
|
var checker auth.Checker
|
|
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
|
case "forward":
|
|
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
|
case "dev":
|
|
if !devMode {
|
|
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
|
}
|
|
log.Println("[auth] AUTH_MODE=dev: every request is treated as the admin")
|
|
checker = auth.AllowAll{}
|
|
default:
|
|
log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode)
|
|
}
|
|
|
|
remote := os.Getenv("GIT_REMOTE_URL")
|
|
if remote == "" {
|
|
log.Fatal("GIT_REMOTE_URL is not set")
|
|
}
|
|
|
|
var err error
|
|
srv := &handlers.Server{Checker: checker, WebhookSecret: os.Getenv("WEBHOOK_SECRET")}
|
|
if srv.WebhookSecret == "" {
|
|
log.Println("[webhook] WEBHOOK_SECRET is not set: the push hook is off, pulls happen on the interval only")
|
|
}
|
|
|
|
// CLAUDE
|
|
// Optional: without a key the site runs as before and the Explain
|
|
// button answers 503.
|
|
// Every call's cost goes in a ledger beside the clone, and
|
|
// CLAUDE_MONTHLY_BUDGET (dollars) stops new jobs once a month has spent
|
|
// it.
|
|
budget := 0.0
|
|
if v := os.Getenv("CLAUDE_MONTHLY_BUDGET"); v != "" {
|
|
if budget, err = strconv.ParseFloat(v, 64); err != nil || budget < 0 {
|
|
log.Fatalf("CLAUDE_MONTHLY_BUDGET=%q is not a dollar amount", v)
|
|
}
|
|
}
|
|
ledger, err := usage.Open(filepath.Join(dataDir, "usage.jsonl"), budget)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
srv.Usage = ledger
|
|
if c, err := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL")); err == nil {
|
|
c.Ledger = ledger
|
|
srv.Claude = c
|
|
log.Printf("[claude] explanations use %s; monthly budget %s", c.Model(), dollars(budget))
|
|
} else {
|
|
log.Printf("[claude] %v: explanations are off", err)
|
|
}
|
|
|
|
// JOBS
|
|
// Their records (and the drafts of answers not yet committed) are kept
|
|
// beside the clone, so a restart loses neither.
|
|
srv.Jobs = jobs.New(filepath.Join(dataDir, "jobs"))
|
|
|
|
// REVIEWS
|
|
// A recording needs a transcriber as well as Claude. OPENAI_API_KEY is
|
|
// accepted too, as the key most people already have under that name.
|
|
tkey := os.Getenv("TRANSCRIBE_API_KEY")
|
|
if tkey == "" {
|
|
tkey = os.Getenv("OPENAI_API_KEY")
|
|
}
|
|
if t, err := transcribe.New(os.Getenv("TRANSCRIBE_URL"), tkey, os.Getenv("TRANSCRIBE_MODEL")); err == nil {
|
|
srv.Transcriber = t
|
|
log.Printf("[review] recordings are transcribed with %s", t.Model())
|
|
} else {
|
|
log.Printf("[review] %v: recording reviews are off", err)
|
|
}
|
|
// Optional on top: without it, recordings are thrown away once
|
|
// transcribed. A half-filled config is a mistake worth stopping for.
|
|
store, err := audiostore.New(audiostore.Config{
|
|
Endpoint: os.Getenv("S3_ENDPOINT"),
|
|
Region: os.Getenv("S3_REGION"),
|
|
Bucket: os.Getenv("S3_BUCKET"),
|
|
AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"),
|
|
SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY"),
|
|
})
|
|
switch {
|
|
case err != nil:
|
|
log.Fatal(err)
|
|
case store != nil:
|
|
srv.Audio = store
|
|
log.Printf("[review] recordings are kept in the %s bucket", store.Bucket())
|
|
default:
|
|
log.Println("[review] S3_ENDPOINT is not set: recordings are not kept")
|
|
}
|
|
|
|
// RUNNER
|
|
// Optional: the solve page runs and lints code through the sandboxed
|
|
// runner service. Without it the page still edits and saves code.
|
|
if u := os.Getenv("RUNNER_URL"); u != "" {
|
|
srv.Runner = runner.NewClient(u)
|
|
log.Printf("[runner] code runs on %s", u)
|
|
} else {
|
|
log.Println("[runner] RUNNER_URL is not set: running and linting code are off")
|
|
}
|
|
|
|
rp, err := repo.New(repo.Config{
|
|
Dir: filepath.Join(dataDir, "repo"),
|
|
Remote: remote,
|
|
Branch: getenv("GIT_BRANCH", "main"),
|
|
User: getenv("GIT_USER", "adamf"),
|
|
Token: os.Getenv("GIT_TOKEN"),
|
|
AuthorName: getenv("GIT_AUTHOR_NAME", "usaco site"),
|
|
AuthorEmail: getenv("GIT_AUTHOR_EMAIL", "[email protected]"),
|
|
Push: getenv("GIT_PUSH", "true") == "true",
|
|
}, srv.Reload)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
srv.Repo, srv.Dir = rp, rp.Dir()
|
|
|
|
// SYNC LOOP
|
|
// One goroutine does every pull, so webhook bursts coalesce: a trigger
|
|
// that arrives while a pull is running queues exactly one more. Until
|
|
// the first pull succeeds (Gitea may still be starting), it retries
|
|
// every 30 seconds and /api/health reports not ready.
|
|
trigger := make(chan struct{}, 1)
|
|
srv.Pull = func() {
|
|
select {
|
|
case trigger <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
go syncLoop(rp, srv, trigger, duration("PULL_INTERVAL", 10*time.Minute))
|
|
|
|
r := gin.New()
|
|
r.Use(gin.Logger(), gin.Recovery())
|
|
// Nothing here keys on the client's IP, so no proxy is trusted to
|
|
// report one.
|
|
if err := r.SetTrustedProxies(nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
srv.Routes(r.Group(basePath + "/api"))
|
|
r.NoRoute(handlers.SPA(staticDir, basePath))
|
|
|
|
addr := ":" + getenv("PORT", "8080")
|
|
hs := &http.Server{Addr: addr, Handler: r}
|
|
go func() {
|
|
log.Printf("listening on %s%s/", addr, basePath)
|
|
if err := hs.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatal(err)
|
|
}
|
|
}()
|
|
|
|
// SHUTDOWN
|
|
// A deploy stops the container with SIGTERM. Without a handler the
|
|
// process (PID 1, which has no default one) ignored it until Docker's
|
|
// SIGKILL, mid-job. Now the running jobs get SHUTDOWN_GRACE to finish,
|
|
// while the server keeps answering the pages that poll them and turns
|
|
// new jobs away; the compose file's stop_grace_period must be longer.
|
|
// A job cut off anyway is settled by the next start (internal/jobs).
|
|
stop, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
|
|
defer cancel()
|
|
<-stop.Done()
|
|
grace := duration("SHUTDOWN_GRACE", 5*time.Minute)
|
|
log.Printf("[shutdown] waiting up to %s for running jobs", grace)
|
|
drain, undrain := context.WithTimeout(context.Background(), grace)
|
|
defer undrain()
|
|
if !srv.Jobs.Drain(drain.Done()) {
|
|
log.Println("[shutdown] jobs still running; they are settled on the next start")
|
|
}
|
|
ctx, done := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer done()
|
|
hs.Shutdown(ctx)
|
|
}
|
|
|
|
func dollars(budget float64) string {
|
|
if budget == 0 {
|
|
return "none"
|
|
}
|
|
return fmt.Sprintf("$%.2f", budget)
|
|
}
|
|
|
|
func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, interval time.Duration) {
|
|
pull := func() bool {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
if err := rp.Sync(ctx); err != nil {
|
|
log.Printf("[sync] %v", err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
for !pull() {
|
|
time.Sleep(30 * time.Second)
|
|
}
|
|
// Commits a restart interrupted need the clone, so they wait for it.
|
|
srv.ResumeJobs()
|
|
tick := time.NewTicker(interval)
|
|
defer tick.Stop()
|
|
for {
|
|
select {
|
|
case <-tick.C:
|
|
case <-trigger:
|
|
}
|
|
pull()
|
|
}
|
|
}
|
|
|
|
func getenv(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
// duration reads a Go duration; an unparseable value is logged and the
|
|
// default stands.
|
|
func duration(key string, def time.Duration) time.Duration {
|
|
v := os.Getenv(key)
|
|
if v == "" {
|
|
return def
|
|
}
|
|
d, err := time.ParseDuration(v)
|
|
if err != nil || d <= 0 {
|
|
log.Printf("%s=%q is not a duration; using %s", key, v, def)
|
|
return def
|
|
}
|
|
return d
|
|
}
|