Files
usaco/site/cmd/usacosite/main.go
T
adamfandClaude Opus 5.5 63608f130c
Test and publish the site / test (push) Successful in 2m4s
Test and publish the site / publish (push) Successful in 1m44s
Review recorded explanations of a solution on the site
The admin can upload a recording of themselves explaining a problem's
solution out loud (mp3, m4a, wav, webm, ogg or flac, up to 25 MB) and
get interview-style feedback, committed as reviews/<id>.md so every
attempt is kept.

Claude can't take audio, so the recording is transcribed first by an
OpenAI-compatible endpoint (whisper-1 by default; TRANSCRIBE_API_KEY,
with TRANSCRIBE_URL for a self-hosted server). Pace, pauses, filler
words and when complexity first comes up are measured from the word
timestamps and given to Claude with the timestamped transcript, the
statement and optionally the code. The reply covers the verdict, scores
in five areas, the approach and its complexity, missed edge cases,
delivery and what to work on.

Recordings are kept for playback in an S3 bucket (Garage) when the
S3_* settings are given, and are thrown away otherwise. Reviews are
admin-only. The job runs in the background like Explain, and the
statement fetch and save-error handling are now shared between the two.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 01:56:55 +01:00

207 lines
6.4 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), 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"
"log"
"os"
"path/filepath"
"strings"
"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/repo"
"adam-french.co.uk/usaco-site/internal/transcribe"
)
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")
}
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.
if c, err := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL")); err == nil {
srv.Claude = c
log.Printf("[claude] explanations use %s", c.Model())
} else {
log.Printf("[claude] %v: explanations are off", err)
}
// 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")
}
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 = rp
// 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")
log.Printf("listening on %s%s/", addr, basePath)
if err := r.Run(addr); err != nil {
log.Fatal(err)
}
}
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)
}
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
}