Files
usaco/site/cmd/usacosite/main.go
T
adamfandClaude Opus 5.5 6d956f1c76 Add the website: Go server + Vue SPA in site/, with CI
A standalone container for web_server, shaped like job-tracker: serves
/usaco/ with solved problems public and solving/skipped plus edits
(status, link, notes) for the site admin. Git is the only store: the
server clones adamf/usaco from Gitea, pulls on the push webhook, and
commits edits back. CI builds the image only when site/ changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:51:34 +01:00

160 lines
4.6 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, status) 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/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")
}
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
}