When stuck, the admin can ask Claude for an intuitive explanation of a problem. It is committed as explain.md and shown as folded sections, so the reader opens only as much as they need: the key observation, hints that get stronger, the approach, a walkthrough with an SVG diagram per step, complexity, pitfalls and a pseudocode sketch. - internal/claude: streamed call with a JSON-schema reply, high effort, the server-side refusal fallback, fixed error messages and logged token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5); without a key only this feature is off. - internal/explain: the prompt, the schema, rendering to markdown, and a per-problem job tracker. The request starts a job and the page polls, since a call outlasts nginx's 120s timeout. - internal/statement: fetches statements from LeetCode's GraphQL API and USACO's problem pages. Others (Codeforces is behind Cloudflare) are pasted. - problem.md holds the statement, editable from the meta editor and shown only to the admin. Diagrams are sanitized with DOMPurify. Co-Authored-By: Claude Opus 5.5 <[email protected]>
172 lines
5.1 KiB
Go
172 lines
5.1 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) and Claude-written
|
|
// 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/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"
|
|
)
|
|
|
|
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)
|
|
}
|
|
|
|
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
|
|
}
|