diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 62002dc..e595651 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,14 +1,18 @@ -# Builds the public site from a database snapshot and deploys it to Cloudflare Pages. +# Builds the public site from the snapshot the API stored in Workers KV and deploys it to Cloudflare Pages. +# CI never touches the database: the API builds the snapshot (internal/republish.Publisher), stores it +# under snapshot:, points "latest" at it, then fires this workflow with the hash. # # Triggers: -# - repository_dispatch "publish": the API fires it after every content write (republish middleware) -# - push to main touching apps/web, packages/ or the snapshot code: code changes always deploy -# - nightly 00:05 Asia/Dhaka: "upcoming" and "registration open" roll over with the date -# - manual run +# - repository_dispatch "publish": the API, after content changed (a write, its nightly 00:05 Asia/Dhaka +# date rollover, its boot after a deploy, or "republish now"); client_payload.hash names the snapshot +# - push to main touching apps/web or packages/: code changes always deploy, with the latest snapshot +# - manual run: the latest snapshot # # Secrets (repo settings → Secrets and variables → Actions): -# SNAPSHOT_DATABASE_URL Supabase connection string for a READ-ONLY role (optional: without it the fixture is used) -# CLOUDFLARE_API_TOKEN token with "Cloudflare Pages: Edit" +# SNAPSHOT_KV_NAMESPACE_ID the Workers KV namespace the API writes (optional: without it the fixture is +# built and nothing is deployed) +# SNAPSHOT_KV_READ_TOKEN token with "Workers KV Storage: Read" +# CLOUDFLARE_API_TOKEN token with "Cloudflare Pages: Edit" # CLOUDFLARE_ACCOUNT_ID name: publish @@ -20,12 +24,8 @@ on: paths: - apps/web/** - packages/** - - apps/api/internal/site/** - - apps/api/cmd/snapshot/** - pnpm-lock.yaml - .github/workflows/publish.yml - schedule: - - cron: "5 18 * * *" workflow_dispatch: permissions: @@ -47,28 +47,43 @@ jobs: steps: - uses: actions/checkout@v7 - - uses: actions/setup-go@v7 - with: - go-version-file: apps/api/go.mod - cache-dependency-path: apps/api/go.sum - - - name: Snapshot the database + - name: Fetch the snapshot id: snapshot - working-directory: apps/api env: - DATABASE_URL: ${{ secrets.SNAPSHOT_DATABASE_URL }} + ACCOUNT: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + NAMESPACE: ${{ secrets.SNAPSHOT_KV_NAMESPACE_ID }} + TOKEN: ${{ secrets.SNAPSHOT_KV_READ_TOKEN }} + WANT: ${{ github.event.client_payload.hash }} run: | - if [ -z "$DATABASE_URL" ]; then - echo "SNAPSHOT_DATABASE_URL is not set; building from the committed fixture." + if [ -z "$NAMESPACE" ] || [ -z "$TOKEN" ] || [ -z "$ACCOUNT" ]; then + echo "::warning::SNAPSHOT_KV_* is not set; building the committed fixture, which is never deployed." echo "hash=fixture" >> "$GITHUB_OUTPUT" exit 0 fi - version=$(go run ./cmd/snapshot -out ../web) - echo "hash=$(echo "$version" | jq -r .hash)" >> "$GITHUB_OUTPUT" + kv="https://api.cloudflare.com/client/v4/accounts/$ACCOUNT/storage/kv/namespaces/$NAMESPACE/values" + get() { curl -fsS --max-time 20 -H "Authorization: Bearer $TOKEN" "$kv/$1"; } + mkdir -p apps/web/.snapshot + out=apps/web/.snapshot/site.json + # Workers KV is eventually consistent: a key the API just wrote can take up to a minute to be + # readable here, so retry until the snapshot with the wanted hash arrives. + for delay in 0 5 10 20 30 60; do + sleep "$delay" + hash="$WANT" + [ -n "$hash" ] || hash=$(get latest | jq -r '.hash // empty') || true + if [ -n "$hash" ] && get "snapshot%3A$hash" > "$out" && [ "$(jq -r .version.hash "$out")" = "$hash" ]; then + echo "snapshot $hash" + echo "hash=$hash" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "snapshot ${hash:-latest} not readable yet" + done + echo "::error::could not read snapshot ${WANT:-latest} from Workers KV" + exit 1 - name: Skip if the live site already has this content id: live - if: github.event_name != 'push' && github.event_name != 'workflow_dispatch' + # "Republish now" (client_payload.force) deploys even when the live site already has this hash. + if: github.event_name != 'push' && github.event_name != 'workflow_dispatch' && github.event.client_payload.force != 'true' run: | live=$(curl -fsS --max-time 10 "$SITE_URL/version.json" | jq -r .hash || echo none) echo "live hash: $live, new hash: ${{ steps.snapshot.outputs.hash }}" @@ -93,7 +108,7 @@ jobs: pnpm turbo run build --filter=@binarysust/web - name: Deploy to Cloudflare Pages - if: steps.live.outputs.unchanged != 'true' + if: steps.live.outputs.unchanged != 'true' && steps.snapshot.outputs.hash != 'fixture' working-directory: apps/web env: WRANGLER_SEND_METRICS: false diff --git a/apps/api/cmd/server/main.go b/apps/api/cmd/server/main.go index cd99d7e..5a23520 100644 --- a/apps/api/cmd/server/main.go +++ b/apps/api/cmd/server/main.go @@ -8,6 +8,7 @@ package main import ( "context" + "encoding/json" "flag" "log/slog" "os" @@ -15,6 +16,7 @@ import ( "slices" "strings" "syscall" + "time" _ "github.com/jackc/pgx/v5/stdlib" // the "pgx" database/sql driver @@ -28,6 +30,7 @@ import ( "github.com/BinarySUST/binarysust-web/apps/api/internal/club" "github.com/BinarySUST/binarysust-web/apps/api/internal/media" "github.com/BinarySUST/binarysust-web/apps/api/internal/republish" + "github.com/BinarySUST/binarysust-web/apps/api/internal/site" ) // Config is read from the environment (see .env.example at the repository root and infra/vps/binarysust-api.env.example). @@ -46,7 +49,17 @@ type Config struct { MediaToken string // GITHUB_MEDIA_TOKEN: contents:write on the media repo MediaRepository string // GITHUB_MEDIA_REPOSITORY: owner/name; set it to store uploads on GitHub MediaBranch string // GITHUB_MEDIA_BRANCH: default main + CloudflareAccount string // CLOUDFLARE_ACCOUNT_ID + SnapshotKV string // SNAPSHOT_KV_NAMESPACE_ID: set it (and SNAPSHOT_KV_TOKEN) to publish snapshots to Workers KV + SnapshotKVToken string // SNAPSHOT_KV_TOKEN: "Workers KV Storage: Edit" CORS []string + + cloudflareAPI, githubAPI string // tests point these at fakes +} + +// snapshotKV reports whether snapshots are published to Workers KV. +func (c Config) snapshotKV() bool { + return c.CloudflareAccount != "" && c.SnapshotKV != "" && c.SnapshotKVToken != "" } // LoadConfig reads Config from getenv. @@ -72,12 +85,22 @@ func LoadConfig(getenv func(string) string) Config { MediaToken: getenv("GITHUB_MEDIA_TOKEN"), MediaRepository: getenv("GITHUB_MEDIA_REPOSITORY"), MediaBranch: getenv("GITHUB_MEDIA_BRANCH"), + CloudflareAccount: getenv("CLOUDFLARE_ACCOUNT_ID"), + SnapshotKV: getenv("SNAPSHOT_KV_NAMESPACE_ID"), + SnapshotKVToken: getenv("SNAPSHOT_KV_TOKEN"), CORS: cors, } } +// Server is the wired API. +type Server struct { + App *ekman.App + Svc *club.Services + Publisher *republish.Publisher // nil unless snapshots go to Workers KV; Start it when serving +} + // NewApp builds the whole API from cfg over database. -func NewApp(cfg Config, database *db.DB, logger *slog.Logger) (*ekman.App, *club.Services, error) { +func NewApp(cfg Config, database *db.DB, logger *slog.Logger) (*Server, error) { svc := club.New(database, club.Deps{ Mail: mailer(cfg, logger), Bucket: bucket(cfg), @@ -110,11 +133,35 @@ func NewApp(cfg Config, database *db.DB, logger *slog.Logger) (*ekman.App, *club Description: "The Binary SUST club API. Public pages never call it; they are built from the snapshot."}, }) if err != nil { - return nil, nil, err + return nil, err + } + s := &Server{App: app, Svc: svc} + var n republish.Notifier = notifier(cfg, logger) + if cfg.snapshotKV() { + s.Publisher = &republish.Publisher{ + Build: func(ctx context.Context) (republish.Built, error) { + snap, err := site.Build(ctx, svc.Sources, time.Now()) + if err != nil { + return republish.Built{}, err + } + body, err := json.MarshalIndent(snap, "", " ") // the same file cmd/snapshot writes + return republish.Built{Hash: snap.Version.Hash, BuiltAt: snap.Version.BuiltAt, Body: body}, err + }, + Store: &republish.KV{AccountID: cfg.CloudflareAccount, NamespaceID: cfg.SnapshotKV, + Token: cfg.SnapshotKVToken, BaseURL: cfg.cloudflareAPI}, + Dispatch: n.(republish.Dispatcher), + Log: logger, + } + n = s.Publisher } - app.Use(republish.Middleware(svc.Access, notifier(cfg, logger), logger)) + if s.Publisher != nil { + svc.Site.SetRepublisher(s.Publisher) + } else { + svc.Site.SetRepublisher(dispatchOnly{n}) + } + app.Use(republish.Middleware(svc.Access, n, logger)) app.Register(svc.Modules()...) - return app, svc, nil + return s, nil } func mailer(cfg Config, logger *slog.Logger) mail.Sender { @@ -135,9 +182,20 @@ func bucket(cfg Config) storage.Bucket { return nil } -func notifier(cfg Config, logger *slog.Logger) republish.Notifier { +// dispatchOnly forces a build without a stored snapshot (KV not configured). +type dispatchOnly struct{ republish.Notifier } + +func (d dispatchOnly) Republish(ctx context.Context, reason string) error { + return d.Notify(ctx, reason) +} + +// notifier dispatches without a snapshot (KV not configured), or is the Publisher's Dispatcher. +func notifier(cfg Config, logger *slog.Logger) interface { + republish.Notifier + republish.Dispatcher +} { if cfg.DispatchToken != "" && cfg.Repository != "" { - return &republish.GitHub{Token: cfg.DispatchToken, Repository: cfg.Repository} + return &republish.GitHub{Token: cfg.DispatchToken, Repository: cfg.Repository, BaseURL: cfg.githubAPI} } return republish.Log{Logger: logger} } @@ -169,7 +227,7 @@ func main() { os.Exit(1) } defer database.Close() - app, _, err := NewApp(cfg, database, logger) + s, err := NewApp(cfg, database, logger) if err != nil { logger.Error("configure", "err", err.Error()) os.Exit(1) @@ -177,7 +235,7 @@ func main() { // `openapi [-o file]`: ekman's document plus the enums it cannot express (club.OpenAPI), // written to stdout or to file (`pnpm gen` writes openapi.json without a shell redirect). if len(os.Args) > 1 && os.Args[1] == "openapi" { - if err := writeOpenAPI(app, os.Args[2:]); err != nil { + if err := writeOpenAPI(s.App, os.Args[2:]); err != nil { logger.Error("openapi", "err", err.Error()) os.Exit(1) } @@ -190,7 +248,7 @@ func main() { // `serve --migrate`: migrate first, then hand over to ekman's serve. if len(os.Args) > 2 && os.Args[1] == "serve" && slices.Contains(os.Args[2:], "--migrate") { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - err := app.Migrate(ctx) + err := s.App.Migrate(ctx) stop() if err != nil { logger.Error("migrate", "err", err.Error()) @@ -199,5 +257,26 @@ func main() { logger.Info("migrations applied") os.Args = os.Args[:2] } - app.Main() + if serving && s.Publisher != nil { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + s.Publisher.Start(ctx) + go func() { // the date rollover changes "upcoming" and "registration open" + for range republish.Daily(ctx, dhaka) { + _ = s.Publisher.Notify(ctx, "nightly") + } + }() + defer func() { + stop() + sctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + s.Publisher.Stop(sctx) + }() + } else if serving { + logger.Warn("SNAPSHOT_KV_* not set: content changes dispatch builds without storing a snapshot") + } + s.App.Main() } + +// dhaka is the club's day: "upcoming" and "registration open" roll over at 00:05 here. +// Bangladesh has had no daylight saving since 2009, so a fixed zone needs no tzdata. +var dhaka = time.FixedZone("Asia/Dhaka", 6*60*60) diff --git a/apps/api/cmd/server/main_test.go b/apps/api/cmd/server/main_test.go index 768f42b..d368645 100644 --- a/apps/api/cmd/server/main_test.go +++ b/apps/api/cmd/server/main_test.go @@ -35,11 +35,11 @@ func serve(t *testing.T, cfg Config, d *db.DB) *httptest.Server { t.Fatal(err) } } - app, _, err := NewApp(cfg, d, quiet) + s, err := NewApp(cfg, d, quiet) if err != nil { t.Fatal(err) } - h, err := app.Handler() + h, err := s.App.Handler() if err != nil { t.Fatalf("boot: %v", err) } @@ -82,10 +82,11 @@ func TestDevSignInOnlyOnLocalOrigins(t *testing.T) { func TestBootAndOpenAPI(t *testing.T) { lazy, _ := db.Open("pgx", "postgres://nobody@127.0.0.1:1/none") - app, _, err := NewApp(LoadConfig(env(nil)), lazy, quiet) + wired, err := NewApp(LoadConfig(env(nil)), lazy, quiet) if err != nil { t.Fatal(err) } + app := wired.App doc, err := club.OpenAPI(app) if err != nil { t.Fatalf("openapi: %v", err) @@ -114,7 +115,7 @@ func TestBootAndOpenAPI(t *testing.T) { } _ = json.Unmarshal(spec.Components.Schemas["Permission"], &perms) want := []string{"blog.review", "blog.write", "events.checkin", "events.manage", "media.upload", "people.manage", - "profile.edit_own", "roles.manage", "sponsors.manage", "talks.manage"} + "profile.edit_own", "roles.manage", "site.publish", "sponsors.manage", "talks.manage"} if !slices.Equal(perms.Enum, want) { t.Errorf("permissions: %v", perms.Enum) } @@ -151,10 +152,11 @@ func TestDevSignInFlow(t *testing.T) { t.Fatal(err) } cfg.PublicURL = "http://" + ln.Addr().String() - app, _, err := NewApp(cfg, d, quiet) + wired, err := NewApp(cfg, d, quiet) if err != nil { t.Fatal(err) } + app := wired.App if err := app.Migrate(context.Background()); err != nil { t.Fatal(err) } diff --git a/apps/api/cmd/server/publish_test.go b/apps/api/cmd/server/publish_test.go new file mode 100644 index 0000000..182bdd7 --- /dev/null +++ b/apps/api/cmd/server/publish_test.go @@ -0,0 +1,415 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/sakib412/ekman/db" + "github.com/sakib412/ekman/ekmantest" +) + +// kvFake is Cloudflare's Workers KV REST API for one namespace, recording every write in order. +type kvFake struct { + mu sync.Mutex + vals map[string]string + writes []string // "key ttl" + down bool +} + +const kvValues = "/accounts/acc/storage/kv/namespaces/ns/values/" + +func (f *kvFake) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + if f.down || !strings.HasPrefix(r.URL.Path, kvValues) || r.Header.Get("Authorization") != "Bearer kv-token" { + http.Error(w, `{"success":false}`, http.StatusInternalServerError) + return + } + key := strings.TrimPrefix(r.URL.Path, kvValues) + switch r.Method { + case http.MethodPut: + b, _ := io.ReadAll(r.Body) + f.vals[key] = string(b) + f.writes = append(f.writes, strings.TrimSpace(key+" "+r.URL.Query().Get("expiration_ttl"))) + case http.MethodGet: + v, ok := f.vals[key] + if !ok { + http.NotFound(w, r) + return + } + _, _ = io.WriteString(w, v) + } +} + +func (f *kvFake) takeWrites() []string { + f.mu.Lock() + defer f.mu.Unlock() + w := f.writes + f.writes = nil + return w +} + +func (f *kvFake) setDown(down bool) { + f.mu.Lock() + defer f.mu.Unlock() + f.down = down +} + +// dispatchFake is GitHub's repository_dispatch endpoint. +type dispatchFake struct { + mu sync.Mutex + sent []map[string]any // client_payload of each dispatch +} + +func (f *dispatchFake) ServeHTTP(w http.ResponseWriter, r *http.Request) { + var body struct { + EventType string `json:"event_type"` + ClientPayload map[string]any `json:"client_payload"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + f.mu.Lock() + defer f.mu.Unlock() + if r.URL.Path == "/repos/BinarySUST/binarysust-web/dispatches" && body.EventType == "publish" { + f.sent = append(f.sent, body.ClientPayload) + } + w.WriteHeader(http.StatusNoContent) +} + +func (f *dispatchFake) take() []map[string]any { + f.mu.Lock() + defer f.mu.Unlock() + s := f.sent + f.sent = nil + return s +} + +type publishRig struct { + srv *httptest.Server + admin *http.Client + server *Server + kv *kvFake + dispatch *dispatchFake + stop func() // stops the publisher, as SIGTERM does +} + +// newPublishRig boots the real wiring against Postgres, with KV and GitHub faked, an admin +// signed in, and the publisher running (its boot publish already done). +func newPublishRig(t *testing.T, kv *kvFake) *publishRig { return boot(t, kv, nil) } + +// newPublishRigOn boots a second API process over prev's database and KV (a restart). +func newPublishRigOn(t *testing.T, kv *kvFake, prev *publishRig) *publishRig { + return boot(t, kv, prev.server.Svc.Sources.DB) +} + +func boot(t *testing.T, kv *kvFake, d *db.DB) *publishRig { + t.Helper() + if d == nil { + d = ekmantest.DB(t, "pgx") + } + if kv == nil { + kv = &kvFake{vals: map[string]string{}} + } + gh := &dispatchFake{} + kvSrv, ghSrv := httptest.NewServer(kv), httptest.NewServer(gh) + t.Cleanup(kvSrv.Close) + t.Cleanup(ghSrv.Close) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + cfg := LoadConfig(env(map[string]string{ + "DEV_ADMIN_EMAIL": "admin@binarysust.local", + "GITHUB_DISPATCH_TOKEN": "gh-token", + "GITHUB_REPOSITORY": "BinarySUST/binarysust-web", + "CLOUDFLARE_ACCOUNT_ID": "acc", + "SNAPSHOT_KV_NAMESPACE_ID": "ns", + "SNAPSHOT_KV_TOKEN": "kv-token", + })) + cfg.PublicURL = "http://" + ln.Addr().String() + cfg.cloudflareAPI, cfg.githubAPI = kvSrv.URL, ghSrv.URL + s, err := NewApp(cfg, d, quiet) + if err != nil { + t.Fatal(err) + } + if err := s.App.Migrate(context.Background()); err != nil { + t.Fatal(err) + } + h, err := s.App.Handler() + if err != nil { + t.Fatal(err) + } + srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: h}} + srv.Start() + t.Cleanup(srv.Close) + + for _, q := range []string{ + `DELETE FROM role_grants`, `DELETE FROM persons WHERE handle = 'dev-admin'`, + `INSERT INTO persons (handle, name, email, listed) VALUES ('dev-admin', 'Dev Admin', 'admin@binarysust.local', false)`, + `INSERT INTO role_grants (person_id, role) SELECT id, 'admin' FROM persons WHERE handle = 'dev-admin'`, + } { + if _, err := d.SQL().Exec(q); err != nil { + t.Fatal(err) + } + } + jar, _ := cookiejar.New(nil) + admin := &http.Client{Jar: jar, CheckRedirect: func(r *http.Request, _ []*http.Request) error { + if strings.HasSuffix(r.URL.Path, "/dashboard") { + return http.ErrUseLastResponse + } + return nil + }} + resp, err := admin.Get(srv.URL + "/api/v1/auth/dev/start?next=/dashboard") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + + ctx, cancel := context.WithCancel(context.Background()) + s.Publisher.Start(ctx) + stop := func() { + cancel() + sctx, scancel := context.WithTimeout(context.Background(), 10*time.Second) + defer scancel() + s.Publisher.Stop(sctx) + } + t.Cleanup(stop) + r := &publishRig{srv: srv, admin: admin, server: s, kv: kv, dispatch: gh, stop: stop} + r.idle(t) + return r +} + +func (r *publishRig) idle(t *testing.T) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.server.Publisher.Wait(ctx); err != nil { + t.Fatalf("publisher never went idle: %v", err) + } +} + +func (r *publishRig) do(t *testing.T, client *http.Client, method, path string, body any) int { + t.Helper() + var rd io.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = bytes.NewReader(b) + } + req, _ := http.NewRequest(method, r.srv.URL+path, rd) + req.Header.Set("Content-Type", "application/json") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + return resp.StatusCode +} + +// previewHash is the hash the next build would publish, from the dashboard's preview endpoint. +func (r *publishRig) previewHash(t *testing.T) string { + t.Helper() + resp, err := r.admin.Get(r.srv.URL + "/api/v1/site/preview") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var snap struct { + Version struct { + Hash string `json:"hash"` + } `json:"version"` + } + if err := json.NewDecoder(resp.Body).Decode(&snap); err != nil || snap.Version.Hash == "" { + t.Fatalf("preview: %v", err) + } + return snap.Version.Hash +} + +func sponsor(name string) map[string]any { + return map[string]any{"name": name, "tier": "gold", "logoUrl": "https://example.com/logo.png", "url": "https://example.com", "since": 2024} +} + +func TestWriteStoresSnapshotThenDispatches(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + + if code := r.do(t, r.admin, "POST", "/api/v1/sponsors", sponsor("Acme")); code != http.StatusCreated { + t.Fatalf("create sponsor: %d", code) + } + r.idle(t) + + hash := r.previewHash(t) + writes := r.kv.takeWrites() + if len(writes) != 2 || writes[0] != "snapshot:"+hash+" 2592000" || writes[1] != "latest" { + t.Fatalf("writes %v, want snapshot:%s with a 30-day TTL, then latest", writes, hash) + } + var stored struct { + Version struct{ Hash string } `json:"version"` + Sponsors []struct{ Name string } `json:"sponsors"` + } + if err := json.Unmarshal([]byte(r.kv.vals["snapshot:"+hash]), &stored); err != nil || + stored.Version.Hash != hash || len(stored.Sponsors) != 1 || stored.Sponsors[0].Name != "Acme" { + t.Fatalf("stored snapshot: %+v %v", stored, err) + } + var latest struct { + Hash string `json:"hash"` + BuiltAt time.Time `json:"builtAt"` + } + if err := json.Unmarshal([]byte(r.kv.vals["latest"]), &latest); err != nil || latest.Hash != hash || latest.BuiltAt.IsZero() { + t.Fatalf("latest: %s", r.kv.vals["latest"]) + } + sent := r.dispatch.take() + if len(sent) != 1 || sent[0]["hash"] != hash || sent[0]["reason"] != "POST /api/v1/sponsors" || sent[0]["force"] != nil { + t.Fatalf("dispatches %v", sent) + } +} + +func TestBootPublishesOnlyWhenContentDiffersFromKV(t *testing.T) { + kv := &kvFake{vals: map[string]string{}} + r := newPublishRig(t, kv) + hash := r.previewHash(t) + if w := kv.takeWrites(); len(w) != 2 || w[0] != "snapshot:"+hash+" 2592000" { + t.Fatalf("first boot writes %v", w) + } + if sent := r.dispatch.take(); len(sent) != 1 || sent[0]["reason"] != "boot" || sent[0]["hash"] != hash { + t.Fatalf("first boot dispatches %v", sent) + } + + // A restart with KV already holding this content: nothing to do. + r.stop() + again := newPublishRigOn(t, kv, r) + if w := kv.takeWrites(); len(w) != 0 { + t.Fatalf("restart writes %v", w) + } + if sent := again.dispatch.take(); len(sent) != 0 { + t.Fatalf("restart dispatches %v", sent) + } +} + +func TestBurstOfWritesPublishesOnce(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + // Hold the worker in its first run so the rest of the burst queues behind it. + r.kv.mu.Lock() + var wg sync.WaitGroup + for _, name := range []string{"A", "B", "C", "D"} { + wg.Add(1) + go func() { + defer wg.Done() + if code := r.do(t, r.admin, "POST", "/api/v1/sponsors", sponsor(name)); code != http.StatusCreated { + t.Errorf("create %s: %d", name, code) + } + }() + } + wg.Wait() // every write answered while KV was blocked: publishing never delays the editor + r.kv.mu.Unlock() + r.idle(t) + hash := r.previewHash(t) + sent := r.dispatch.take() + if len(sent) == 0 || len(sent) > 2 || sent[len(sent)-1]["hash"] != hash { + t.Fatalf("a burst of 4 writes dispatched %v; want at most 2 (the run in progress, then one for the rest)", sent) + } +} + +func TestUnchangedContentPublishesNothing(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + // A write that changes nothing public (say, an unlisted person's profile) signals the publisher + // exactly as the middleware does; the snapshot hash is unchanged. + _ = r.server.Publisher.Notify(context.Background(), "PUT /api/v1/people/{handle}") + r.idle(t) + if w, s := r.kv.takeWrites(), r.dispatch.take(); len(w) != 0 || len(s) != 0 { + t.Fatalf("unchanged content: writes %v, dispatches %v", w, s) + } +} + +func TestKVFailureNeverFailsTheWriteAndRetriesNextTime(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + r.kv.setDown(true) + if code := r.do(t, r.admin, "POST", "/api/v1/sponsors", sponsor("Acme")); code != http.StatusCreated { + t.Fatalf("a KV outage must not fail the write: %d", code) + } + r.idle(t) + if s := r.dispatch.take(); len(s) != 0 { + t.Fatalf("dispatched without a stored snapshot: %v", s) + } + // KV is back; the next trigger (here the nightly run) publishes the same content. + r.kv.setDown(false) + _ = r.server.Publisher.Notify(context.Background(), "nightly") + r.idle(t) + if s := r.dispatch.take(); len(s) != 1 || s[0]["hash"] != r.previewHash(t) { + t.Fatalf("retry dispatches %v", s) + } +} + +// main turns each republish.Daily tick (00:05 Asia/Dhaka, see TestNextRollover) into this Notify. +func TestNightlyRunRepublishesOnlyWhenContentChanged(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + nightly := func() { _ = r.server.Publisher.Notify(context.Background(), "nightly") } + // Nothing changed overnight: the run costs nothing. + nightly() + r.idle(t) + if w, s := r.kv.takeWrites(), r.dispatch.take(); len(w) != 0 || len(s) != 0 { + t.Fatalf("idle night: writes %v, dispatches %v", w, s) + } + // Content changed (here directly in the database, as a date rollover would change the build). + if _, err := r.server.Svc.Sources.DB.SQL().Exec(`INSERT INTO sponsors (name, tier, logo_url, url, since) VALUES ('Night', 'gold', 'https://example.com/l.png', '', 2024)`); err != nil { + t.Fatal(err) + } + nightly() + r.idle(t) + if s := r.dispatch.take(); len(s) != 1 || s[0]["reason"] != "nightly" || s[0]["hash"] != r.previewHash(t) { + t.Fatalf("nightly dispatches %v", s) + } +} + +func TestRepublishNowIsAdminOnlyAndAlwaysDispatches(t *testing.T) { + r := newPublishRig(t, nil) + r.kv.takeWrites() + r.dispatch.take() + anon := &http.Client{} + if code := r.do(t, anon, "POST", "/api/v1/site/republish", nil); code != http.StatusUnauthorized { + t.Fatalf("anonymous republish: %d", code) + } + if code := r.do(t, r.admin, "POST", "/api/v1/site/republish", nil); code != http.StatusAccepted { + t.Fatalf("admin republish: %d", code) + } + r.idle(t) + hash := r.previewHash(t) + // force tells the workflow to deploy even though the live site already has this hash. + if s := r.dispatch.take(); len(s) != 1 || s[0]["hash"] != hash || s[0]["reason"] != "POST /api/v1/site/republish" || s[0]["force"] != "true" { + t.Fatalf("republish dispatches %v (content unchanged, so only a forced run dispatches)", s) + } +} + +func TestWithoutKVWritesDispatchAsBefore(t *testing.T) { + gh := &dispatchFake{} + ghSrv := httptest.NewServer(gh) + t.Cleanup(ghSrv.Close) + d := ekmantest.DB(t, "pgx") + cfg := LoadConfig(env(map[string]string{"GITHUB_DISPATCH_TOKEN": "gh-token", "GITHUB_REPOSITORY": "BinarySUST/binarysust-web"})) + cfg.githubAPI = ghSrv.URL + s, err := NewApp(cfg, d, quiet) + if err != nil { + t.Fatal(err) + } + if s.Publisher != nil { + t.Fatal("no SNAPSHOT_KV_*: there must be no publisher") + } +} diff --git a/apps/api/cmd/snapshot/main.go b/apps/api/cmd/snapshot/main.go index 6334a76..9931f3c 100644 --- a/apps/api/cmd/snapshot/main.go +++ b/apps/api/cmd/snapshot/main.go @@ -1,11 +1,11 @@ -// Command snapshot writes the public-site snapshot. CI runs it against Supabase directly (with a -// read-only role), so a site build never depends on the API being up. +// Command snapshot writes the public-site snapshot from a database, for local site builds +// (`pnpm snapshot`). Production does not use it: the API stores the snapshot in Workers KV and +// the publish workflow downloads it (internal/republish.Publisher, docs/adr/0002). // // DATABASE_URL=... go run ./cmd/snapshot -out ../web // // It writes /.snapshot/site.json (the whole site.Snapshot; the web build slices it and -// writes public/version.json from its version field) and prints the version to stdout, so CI can -// compare the hash with the deployed /version.json and skip an unchanged deploy. +// writes public/version.json from its version field) and prints the version to stdout. package main import ( diff --git a/apps/api/internal/republish/kv.go b/apps/api/internal/republish/kv.go new file mode 100644 index 0000000..3e61689 --- /dev/null +++ b/apps/api/internal/republish/kv.go @@ -0,0 +1,94 @@ +package republish + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// ErrNotFound is returned by KV.Get for a key that does not exist (or has expired). +var ErrNotFound = errors.New("kv: key not found") + +// KV is one Cloudflare Workers KV namespace, reached through Cloudflare's REST API +// (https://developers.cloudflare.com/api/resources/kv/). Workers KV is free without a card +// (1,000 writes and 100,000 reads a day), which is why the snapshot lives here and not in R2. +type KV struct { + AccountID string + NamespaceID string + Token string // an API token with "Workers KV Storage: Edit" + BaseURL string // default https://api.cloudflare.com/client/v4 + Client *http.Client // default: 15 s timeout +} + +func (k *KV) url(key string) string { + base := k.BaseURL + if base == "" { + base = "https://api.cloudflare.com/client/v4" + } + return strings.TrimSuffix(base, "/") + "/accounts/" + url.PathEscape(k.AccountID) + + "/storage/kv/namespaces/" + url.PathEscape(k.NamespaceID) + "/values/" + url.PathEscape(key) +} + +func (k *KV) do(req *http.Request) (*http.Response, error) { + client := k.Client + if client == nil { + client = &http.Client{Timeout: 15 * time.Second} + } + req.Header.Set("Authorization", "Bearer "+k.Token) + return client.Do(req) +} + +// Put stores value under key. A positive ttl makes the key expire (KV's minimum is 60 s); +// zero keeps it forever. +func (k *KV) Put(ctx context.Context, key string, value []byte, ttl time.Duration) error { + u := k.url(key) + if ttl > 0 { + u += "?expiration_ttl=" + strconv.Itoa(int(ttl/time.Second)) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPut, u, bytes.NewReader(value)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/octet-stream") + resp, err := k.do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return statusErr("put "+key, resp) + } + return nil +} + +// Get returns the value under key, or ErrNotFound. +func (k *KV) Get(ctx context.Context, key string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, k.url(key), nil) + if err != nil { + return nil, err + } + resp, err := k.do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return nil, ErrNotFound + } + if resp.StatusCode/100 != 2 { + return nil, statusErr("get "+key, resp) + } + return io.ReadAll(io.LimitReader(resp.Body, 25<<20)) // KV's value limit +} + +func statusErr(op string, resp *http.Response) error { + msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) + return fmt.Errorf("kv %s: %s: %s", op, resp.Status, bytes.TrimSpace(msg)) +} diff --git a/apps/api/internal/republish/kv_test.go b/apps/api/internal/republish/kv_test.go new file mode 100644 index 0000000..d06e547 --- /dev/null +++ b/apps/api/internal/republish/kv_test.go @@ -0,0 +1,127 @@ +package republish_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/BinarySUST/binarysust-web/apps/api/internal/republish" +) + +// fakeKV is Cloudflare's Workers KV REST API for one namespace, in memory. +type fakeKV struct { + vals map[string]string + ttls map[string]string + auths []string + paths []string + down bool +} + +const kvPrefix = "/accounts/acc/storage/kv/namespaces/ns/values/" + +func newFakeKV() *fakeKV { return &fakeKV{vals: map[string]string{}, ttls: map[string]string{}} } + +func (f *fakeKV) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.auths = append(f.auths, r.Header.Get("Authorization")) + f.paths = append(f.paths, r.Method+" "+r.URL.EscapedPath()) + if f.down { + http.Error(w, `{"success":false}`, http.StatusInternalServerError) + return + } + if len(r.URL.Path) <= len(kvPrefix) || r.URL.Path[:len(kvPrefix)] != kvPrefix { + http.NotFound(w, r) + return + } + key := r.URL.Path[len(kvPrefix):] + switch r.Method { + case http.MethodPut: + b, _ := io.ReadAll(r.Body) + f.vals[key] = string(b) + f.ttls[key] = r.URL.Query().Get("expiration_ttl") + _, _ = w.Write([]byte(`{"success":true}`)) + case http.MethodGet: + v, ok := f.vals[key] + if !ok { + http.Error(w, `{"success":false,"errors":[{"code":10009,"message":"key not found"}]}`, http.StatusNotFound) + return + } + _, _ = w.Write([]byte(v)) + } +} + +func TestKV(t *testing.T) { + f := newFakeKV() + srv := httptest.NewServer(f) + defer srv.Close() + kv := &republish.KV{AccountID: "acc", NamespaceID: "ns", Token: "t0ken", BaseURL: srv.URL} + ctx := context.Background() + + if err := kv.Put(ctx, "snapshot:abc", []byte(`{"a":1}`), 30*24*time.Hour); err != nil { + t.Fatal(err) + } + if err := kv.Put(ctx, "latest", []byte(`{"hash":"abc"}`), 0); err != nil { + t.Fatal(err) + } + if f.vals["snapshot:abc"] != `{"a":1}` || f.ttls["snapshot:abc"] != "2592000" { + t.Fatalf("stored %q with ttl %q", f.vals["snapshot:abc"], f.ttls["snapshot:abc"]) + } + if f.ttls["latest"] != "" { + t.Fatalf("latest must not expire, ttl %q", f.ttls["latest"]) + } + got, err := kv.Get(ctx, "latest") + if err != nil || string(got) != `{"hash":"abc"}` { + t.Fatalf("get: %q %v", got, err) + } + for _, a := range f.auths { + if a != "Bearer t0ken" { + t.Fatalf("auth header %q", a) + } + } + + if _, err := kv.Get(ctx, "missing"); !errors.Is(err, republish.ErrNotFound) { + t.Fatalf("missing key: %v", err) + } + f.down = true + if err := kv.Put(ctx, "latest", []byte("x"), 0); err == nil || errors.Is(err, republish.ErrNotFound) { + t.Fatalf("server error must be an error, got %v", err) + } +} + +func TestKVTimeout(t *testing.T) { + block := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-block })) + defer srv.Close() + defer close(block) + kv := &republish.KV{AccountID: "acc", NamespaceID: "ns", Token: "t", BaseURL: srv.URL, + Client: &http.Client{Timeout: 50 * time.Millisecond}} + if err := kv.Put(context.Background(), "k", []byte("v"), 0); err == nil { + t.Fatal("expected a timeout") + } +} + +func TestNextRollover(t *testing.T) { + dhaka := time.FixedZone("Asia/Dhaka", 6*60*60) + at := func(s string) time.Time { + v, err := time.ParseInLocation("2006-01-02 15:04", s, dhaka) + if err != nil { + t.Fatal(err) + } + return v + } + cases := map[string]string{ + "2026-11-20 00:04": "2026-11-20 00:05", + "2026-11-20 00:05": "2026-11-21 00:05", // strictly after: a run at 00:05 waits a day + "2026-11-20 13:00": "2026-11-21 00:05", + "2026-12-31 23:59": "2027-01-01 00:05", + } + for now, want := range cases { + // The VPS clock is UTC: the club's day still turns over in Dhaka. + if got := republish.NextRollover(at(now).UTC(), dhaka); !got.Equal(at(want)) { + t.Errorf("after %s: got %s, want %s", now, got.In(dhaka).Format("2006-01-02 15:04"), want) + } + } +} diff --git a/apps/api/internal/republish/publisher.go b/apps/api/internal/republish/publisher.go new file mode 100644 index 0000000..9313483 --- /dev/null +++ b/apps/api/internal/republish/publisher.go @@ -0,0 +1,285 @@ +package republish + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "sync" + "time" +) + +// Built is one snapshot build: the JSON the site is built from and its content hash. +type Built struct { + Hash string + BuiltAt time.Time + Body []byte +} + +// Store holds snapshots (KV in production). +type Store interface { + Put(ctx context.Context, key string, value []byte, ttl time.Duration) error + Get(ctx context.Context, key string) ([]byte, error) +} + +// Dispatch is one build request: the snapshot to build (empty: the latest) and whether to deploy +// even when the live site already serves that hash. +type Dispatch struct { + Reason string + Hash string + Force bool +} + +// Dispatcher asks CI to rebuild the site (GitHub in production). +type Dispatcher interface { + Dispatch(ctx context.Context, d Dispatch) error +} + +// LatestKey points at the newest stored snapshot: {"hash", "builtAt"}. Snapshots themselves live +// under SnapshotKey(hash), so a build always fetches exactly the version it was told about, even +// while Workers KV is still propagating an older "latest". +const LatestKey = "latest" + +// SnapshotKey is where the snapshot with hash is stored. +func SnapshotKey(hash string) string { return "snapshot:" + hash } + +// Latest is the value stored under LatestKey. +type Latest struct { + Hash string `json:"hash"` + BuiltAt time.Time `json:"builtAt"` +} + +// Publisher makes the API the only producer of the snapshot. Each run builds the snapshot, +// stores it (SnapshotKey, then LatestKey) and dispatches the build, skipping all of it when the +// hash equals the last one published. Runs happen on one background goroutine: signals that +// arrive while a run is in progress collapse into a single next run, so a burst of edits costs +// one build, two KV writes and one CI run. +// +// It implements Notifier, so the republish Middleware signals it after every content write +// without waiting for the build. +type Publisher struct { + Build func(ctx context.Context) (Built, error) + Store Store + Dispatch Dispatcher + Log *slog.Logger + TTL time.Duration // of stored snapshots; default 30 days + Timeout time.Duration // of one run; default 2 minutes + + mu sync.Mutex + pending bool + force bool + reason string + running bool + idle chan struct{} // closed while nothing is pending or running + wake chan struct{} + done chan struct{} + last string // hash of the last fully published snapshot + seeded bool +} + +// Notify implements Notifier: it queues a run and returns at once. +func (p *Publisher) Notify(_ context.Context, reason string) error { + p.signal(reason, false) + return nil +} + +// Republish queues a run that stores and dispatches even when the hash is unchanged. +func (p *Publisher) Republish(_ context.Context, reason string) error { + p.signal(reason, true) + return nil +} + +func (p *Publisher) init() { + if p.wake == nil { + p.wake = make(chan struct{}, 1) + p.done = make(chan struct{}) + p.idle = make(chan struct{}) + close(p.idle) + } +} + +func (p *Publisher) signal(reason string, force bool) { + p.mu.Lock() + p.init() + if !p.pending && !p.running { + p.idle = make(chan struct{}) + } + p.pending, p.reason = true, reason + p.force = p.force || force + p.mu.Unlock() + select { + case p.wake <- struct{}{}: + default: + } +} + +// Start runs the publisher until ctx is canceled, beginning with a "boot" run: a deploy that +// changes what Build produces publishes without waiting for an edit. +func (p *Publisher) Start(ctx context.Context) { + p.signal("boot", false) + go p.loop(ctx) +} + +// Stop waits for the goroutine to finish after Start's ctx is canceled: a run in progress +// completes (bounded by Timeout); a run still pending is dropped, the next boot covers it. +func (p *Publisher) Stop(ctx context.Context) { + p.mu.Lock() + p.init() + done := p.done + p.mu.Unlock() + select { + case <-done: + case <-ctx.Done(): + } +} + +// Wait blocks until nothing is pending or running. +func (p *Publisher) Wait(ctx context.Context) error { + for { + p.mu.Lock() + p.init() + if !p.pending && !p.running { + p.mu.Unlock() + return nil + } + idle := p.idle + p.mu.Unlock() + select { + case <-idle: + case <-ctx.Done(): + return ctx.Err() + } + } +} + +func (p *Publisher) loop(ctx context.Context) { + p.mu.Lock() + p.init() + wake, done := p.wake, p.done + p.mu.Unlock() + defer close(done) + for { + select { + case <-ctx.Done(): + return + case <-wake: + } + p.mu.Lock() + if !p.pending { + p.mu.Unlock() + continue + } + reason, force := p.reason, p.force + p.pending, p.force, p.running = false, false, true + p.mu.Unlock() + + p.run(ctx, reason, force) + + p.mu.Lock() + p.running = false + if !p.pending { + close(p.idle) + } + p.mu.Unlock() + } +} + +func (p *Publisher) run(parent context.Context, reason string, force bool) { + timeout := p.Timeout + if timeout <= 0 { + timeout = 2 * time.Minute + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), timeout) + defer cancel() + log := p.Log + if log == nil { + log = slog.Default() + } + fail := func(msg string, err error) { + log.ErrorContext(ctx, "republish: "+msg, "err", err.Error(), "reason", reason) + } + if !p.seeded { + p.seed(ctx, log) + } + b, err := p.Build(ctx) + if err != nil { + fail("build snapshot", err) + return + } + if b.Hash == p.last && !force { + return + } + ttl := p.TTL + if ttl <= 0 { + ttl = 30 * 24 * time.Hour + } + if err := p.Store.Put(ctx, SnapshotKey(b.Hash), b.Body, ttl); err != nil { + fail("store snapshot", err) + return + } + latest, _ := json.Marshal(Latest{Hash: b.Hash, BuiltAt: b.BuiltAt}) + if err := p.Store.Put(ctx, LatestKey, latest, 0); err != nil { + fail("store latest", err) + return + } + if err := p.Dispatch.Dispatch(ctx, Dispatch{Reason: reason, Hash: b.Hash, Force: force}); err != nil { + fail("dispatch failed", err) + return + } + // Only a fully published snapshot counts: after any failure the next trigger tries again. + p.last = b.Hash + log.InfoContext(ctx, "republish: published snapshot", "hash", b.Hash, "reason", reason) +} + +// seed learns the last published hash from the store, so a restart with unchanged content +// writes nothing and dispatches nothing. +func (p *Publisher) seed(ctx context.Context, log *slog.Logger) { + raw, err := p.Store.Get(ctx, LatestKey) + if err != nil { + if !errors.Is(err, ErrNotFound) { + log.WarnContext(ctx, "republish: read latest", "err", err.Error()) + return // try again next run + } + p.seeded = true + return + } + var l Latest + if json.Unmarshal(raw, &l) == nil { + p.last = l.Hash + } + p.seeded = true +} + +// NextRollover is the next 00:05 in loc strictly after now: the moment "upcoming" and +// "registration open" change for the club's own day. +func NextRollover(now time.Time, loc *time.Location) time.Time { + t := now.In(loc) + next := time.Date(t.Year(), t.Month(), t.Day(), 0, 5, 0, 0, loc) + if !next.After(t) { + next = next.AddDate(0, 0, 1) + } + return next +} + +// Daily ticks at every NextRollover in loc; the channel closes when ctx is canceled. +func Daily(ctx context.Context, loc *time.Location) <-chan time.Time { + ch := make(chan time.Time) + go func() { + defer close(ch) + for { + timer := time.NewTimer(time.Until(NextRollover(time.Now(), loc))) + select { + case <-ctx.Done(): + timer.Stop() + return + case t := <-timer.C: + select { + case ch <- t: + case <-ctx.Done(): + return + } + } + } + }() + return ch +} diff --git a/apps/api/internal/republish/republish.go b/apps/api/internal/republish/republish.go index 5fe3cd8..c83804d 100644 --- a/apps/api/internal/republish/republish.go +++ b/apps/api/internal/republish/republish.go @@ -50,9 +50,10 @@ type Notifier interface { Notify(ctx context.Context, reason string) error } -// Middleware runs after the handler, inside the same request, so a free instance that sleeps -// right after responding cannot drop the notification. Failures are logged, never returned: -// the user's write already succeeded, and the next write or the nightly build catches up. +// Middleware runs after the handler: it records the change inside the request, then notifies. +// In production the Notifier is a Publisher, which only queues a run, so building and storing +// the snapshot never delays the response. Failures are logged, never returned: the user's write +// already succeeded, and the next write, the nightly run or the next boot catches up. func Middleware(rec Recorder, n Notifier, log *slog.Logger) ekman.Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -113,8 +114,14 @@ type GitHub struct { Client *http.Client // default: 5 s timeout } -// Notify implements Notifier. +// Notify implements Notifier: a dispatch without a snapshot hash. func (g *GitHub) Notify(ctx context.Context, reason string) error { + return g.Dispatch(ctx, Dispatch{Reason: reason}) +} + +// Dispatch implements Dispatcher. The publish workflow fetches the snapshot with d.Hash from KV +// (or the latest one when it is empty), and with force it deploys even an unchanged hash. +func (g *GitHub) Dispatch(ctx context.Context, d Dispatch) error { base := g.BaseURL if base == "" { base = "https://api.github.com" @@ -123,10 +130,14 @@ func (g *GitHub) Notify(ctx context.Context, reason string) error { if client == nil { client = &http.Client{Timeout: 5 * time.Second} } - body, _ := json.Marshal(map[string]any{ - "event_type": "publish", - "client_payload": map[string]string{"reason": reason}, - }) + payload := map[string]string{"reason": d.Reason} + if d.Hash != "" { + payload["hash"] = d.Hash + } + if d.Force { + payload["force"] = "true" + } + body, _ := json.Marshal(map[string]any{"event_type": "publish", "client_payload": payload}) req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(base, "/")+"/repos/"+g.Repository+"/dispatches", bytes.NewReader(body)) if err != nil { @@ -148,11 +159,17 @@ func (g *GitHub) Notify(ctx context.Context, reason string) error { return nil } -// Log is the Notifier used when no GitHub token is configured (local development). +// Log is the Notifier (and Dispatcher) used when no GitHub token is configured (local development). type Log struct{ Logger *slog.Logger } // Notify implements Notifier. func (l Log) Notify(ctx context.Context, reason string) error { - l.Logger.InfoContext(ctx, "republish: content changed (no GITHUB_DISPATCH_TOKEN; not dispatching)", "route", reason) + return l.Dispatch(ctx, Dispatch{Reason: reason}) +} + +// Dispatch implements Dispatcher. +func (l Log) Dispatch(ctx context.Context, d Dispatch) error { + l.Logger.InfoContext(ctx, "republish: content changed (no GITHUB_DISPATCH_TOKEN; not dispatching)", + "route", d.Reason, "hash", d.Hash, "force", d.Force) return nil } diff --git a/apps/api/internal/site/site.go b/apps/api/internal/site/site.go index fb3aa00..ebd2834 100644 --- a/apps/api/internal/site/site.go +++ b/apps/api/internal/site/site.go @@ -1,7 +1,8 @@ // Package site owns the public contract: Snapshot, the single value the static site is built // from (docs/snapshot.md). Build reads every module through its own Published function inside // one read-only, repeatable-read transaction, so a snapshot is a consistent cut of the database. -// cmd/snapshot (CI) and GET /site/preview (dashboard) run the same Build. +// The API's republish.Publisher (production), cmd/snapshot (local) and GET /site/preview +// (dashboard) run the same Build. package site import ( @@ -16,11 +17,13 @@ import ( "github.com/sakib412/ekman" "github.com/sakib412/ekman/db" + "github.com/sakib412/ekman/rbac" "github.com/BinarySUST/binarysust-web/apps/api/internal/access" "github.com/BinarySUST/binarysust-web/apps/api/internal/blog" "github.com/BinarySUST/binarysust-web/apps/api/internal/events" "github.com/BinarySUST/binarysust-web/apps/api/internal/people" + "github.com/BinarySUST/binarysust-web/apps/api/internal/republish" "github.com/BinarySUST/binarysust-web/apps/api/internal/sponsors" "github.com/BinarySUST/binarysust-web/apps/api/internal/talks" ) @@ -165,14 +168,26 @@ func contentHash(s Snapshot) (string, error) { return hex.EncodeToString(sum[:]), nil } +// Publish lets a role force a republish (admins hold it through rbac.All). +const Publish rbac.Permission = "site.publish" + +// Republisher queues a rebuild and deploy even when content is unchanged (republish.Publisher). +type Republisher interface { + Republish(ctx context.Context, reason string) error +} + // Service serves the dashboard's site endpoints. type Service struct { src Sources publicURL string client *http.Client now func() time.Time + rep Republisher } +// SetRepublisher sets what POST /site/republish calls; without one it answers 503. +func (s *Service) SetRepublisher(r Republisher) { s.rep = r } + // New returns the site service. publicURL is where the static site (and its /version.json) lives. func New(src Sources, publicURL string) *Service { return &Service{src: src, publicURL: strings.TrimSuffix(publicURL, "/"), @@ -182,11 +197,15 @@ func New(src Sources, publicURL string) *Service { // Module wires the site endpoints into the app. It owns no tables. func (s *Service) Module() ekman.Module { return ekman.Module{ - Name: "site", + Name: "site", + Permissions: []rbac.Permission{Publish}, Routes: func(r *ekman.Router) { ekman.Handle(r, "GET /site/status", ekman.SignedIn(), s.status, ekman.Summary("Is my change live?")) ekman.Handle(r, "GET /site/preview", ekman.SignedIn(), s.preview, ekman.Summary("The snapshot the next build would publish")) + ekman.Handle(r, "POST /site/republish", ekman.Requires(Publish), s.republish, + ekman.Status(http.StatusAccepted), republish.Skip(), // it publishes by itself, forced + ekman.Summary("Rebuild and deploy the site now, even if content is unchanged")) }, } } @@ -195,6 +214,23 @@ func (s *Service) preview(ctx context.Context, _ ekman.Caller, _ *struct{}) (Sna return Build(ctx, s.src, s.now()) } +// Queued answers POST /site/republish: the rebuild runs in the background. +type Queued struct { + Queued bool `json:"queued"` +} + +func (s *Service) republish(ctx context.Context, _ ekman.Caller, _ *struct{}) (Queued, error) { + if s.rep == nil { + return Queued{}, &ekman.Error{Status: http.StatusServiceUnavailable, Code: "republish_unavailable", + Message: "publishing is not configured on this server"} + } + ri, _ := ekman.RouteFrom(ctx) + if err := s.rep.Republish(ctx, http.MethodPost+" "+ri.Pattern); err != nil { + return Queued{}, err + } + return Queued{Queued: true}, nil +} + // LiveVersion is the deployed site's /version.json, as far as status needs it. type LiveVersion struct { ContentChangedAt time.Time `json:"contentChangedAt"` diff --git a/apps/api/openapi.json b/apps/api/openapi.json index 74536dc..df492e2 100644 --- a/apps/api/openapi.json +++ b/apps/api/openapi.json @@ -56,6 +56,7 @@ "people.manage", "profile.edit_own", "roles.manage", + "site.publish", "sponsors.manage", "talks.manage" ], @@ -2266,6 +2267,17 @@ ], "type": "string" }, + "site.Queued": { + "properties": { + "queued": { + "type": "boolean" + } + }, + "required": [ + "queued" + ], + "type": "object" + }, "site.Snapshot": { "properties": { "club": { @@ -4795,6 +4807,42 @@ "x-ekman-access": "signed_in" } }, + "/api/v1/site/republish": { + "post": { + "operationId": "postSiteRepublish", + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/site.Queued" + } + } + }, + "description": "Accepted" + }, + "401": { + "$ref": "#/components/responses/Error" + }, + "403": { + "$ref": "#/components/responses/Error" + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "session": [] + } + ], + "summary": "Rebuild and deploy the site now, even if content is unchanged", + "tags": [ + "site" + ], + "x-ekman-access": "site.publish" + } + }, "/api/v1/site/status": { "get": { "operationId": "getSiteStatus", diff --git a/apps/web/src/content/slices.test.ts b/apps/web/src/content/slices.test.ts index f1483d0..9d7a25f 100644 --- a/apps/web/src/content/slices.test.ts +++ b/apps/web/src/content/slices.test.ts @@ -77,6 +77,13 @@ describe("slices.committee", () => { } }); + it("lists only terms that have a committee, so the term nav never links to a missing page", () => { + const s: Snapshot = { ...fixture, terms: [...fixture.terms, { slug: "1999-00", label: "1999-00", startsOn: "1999-07-01" }] }; + const c = slices.committee(s, fixture.currentTerm!.slug)!; + expect(c.terms.map((t) => t.slug)).not.toContain("1999-00"); + expect(c.terms.every((t) => s.committees.some((cm) => cm.term === t.slug))).toBe(true); + }); + it("is null for a term without a committee", () => { expect(slices.committee(fixture, "1999-00")).toBeNull(); }); diff --git a/apps/web/src/content/slices.ts b/apps/web/src/content/slices.ts index c311a63..206c0dc 100644 --- a/apps/web/src/content/slices.ts +++ b/apps/web/src/content/slices.ts @@ -117,7 +117,10 @@ export const slices = { const t = s.terms.find((x) => x.slug === term); const c = s.committees.find((x) => x.term === term); if (!t || !c) return null; - return { term: t, isCurrent: s.currentTerm?.slug === term, terms: s.terms, seats: [...c.seats].sort(bySeat) }; + // Only terms with a committee get a page (allPaths), so the term nav must not link to the others: the + // pre-render crawls those links and fails on the 404. + const terms = s.terms.filter((x) => s.committees.some((cm) => cm.term === x.slug)); + return { term: t, isCurrent: s.currentTerm?.slug === term, terms, seats: [...c.seats].sort(bySeat) }; }, events(s: Snapshot): EventCard[] { diff --git a/apps/web/src/dashboard/sections.test.ts b/apps/web/src/dashboard/sections.test.ts index c99d77c..d9abdc4 100644 --- a/apps/web/src/dashboard/sections.test.ts +++ b/apps/web/src/dashboard/sections.test.ts @@ -40,6 +40,7 @@ describe("dashboard sections", () => { "people.manage", "profile.edit_own", "roles.manage", + "site.publish", "sponsors.manage", "talks.manage", ]; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a164184..f9829d1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -70,16 +70,16 @@ A Turborepo + pnpm monorepo: `apps/web` (TanStack Start), `apps/api` (Go, a nati ``` Visitor ─► Cloudflare Pages (static HTML from the snapshot) ─── never touches the API Member ─► Pages Function /api/* (same-origin proxy) ─► Cloudflare Tunnel ─► VPS: Go API on ekman ─► Supabase Postgres -Write ─► API commit ─► republish middleware ─► GitHub repository_dispatch -CI ─► go run ./cmd/snapshot (reads Supabase directly, read-only role) ─► vite build (TanStack Start prerender) ─► wrangler pages deploy +Write ─► API commit ─► republish middleware ─► Publisher (background): site.Build ─► Workers KV ─► GitHub repository_dispatch {hash} +CI ─► fetch snapshot: from Workers KV ─► vite build (TanStack Start prerender) ─► wrangler pages deploy ``` ### Load-bearing decisions 1. **The public site is built from a single snapshot of the database.** - `site.Snapshot` is the public contract. It holds every public view, with markdown already rendered to sanitized HTML by the one Go renderer (`internal/md`). The dashboard preview uses the same renderer, so what authors see is exactly what gets published. - - CI produces the snapshot by reading Supabase directly, so a build never depends on the API being up. -2. **Republishing is on by default.** After every 2xx response to a non-GET request, middleware updates `site_settings.content_changed_at` and fires a GitHub `repository_dispatch`, unless the route carries `republish.Skip()` (RSVP, check-in, uploads). Forgetting `Skip` costs only a no-op build, because builds whose content hash hasn't changed skip the deploy. GitHub's concurrency group merges bursts of edits into one running build plus one pending. _Is my change live?_ compares `content_changed_at` with the deployed `/version.json`. + - The API produces the snapshot and stores it in Workers KV under its content hash, then dispatches the build with that hash. CI never touches the database, and a build never depends on the API being up: it reads the last stored snapshot (ADR 0002). +2. **Republishing is on by default.** After every 2xx response to a non-GET request, middleware updates `site_settings.content_changed_at` and signals the `republish.Publisher`, unless the route carries `republish.Skip()` (RSVP, check-in, uploads). The publisher runs in the background, merges bursts of edits into one run, and stores and dispatches only when the content hash changed, so forgetting `Skip` costs nothing. It also runs at boot, at 00:05 Asia/Dhaka (the date rollover), and on an admin's `POST /site/republish`. _Is my change live?_ compares `content_changed_at` with the deployed `/version.json`. 3. **Roles follow the committee.** - Roles are defined in code (`club.Roles`). - A person holds a role through one of two sources: @@ -129,7 +129,8 @@ CI ─► go run ./cmd/snapshot (reads Supabase directly, read-only role) | Go API | Oracle Cloud VPS (ARM64, systemd), behind Cloudflare Tunnel; deployed by `deploy-api.yml` | Always on, no cold starts; no open ports, and the web server already on the box is untouched | | Postgres | Supabase free | Managed Postgres with backups; 500 MB is far more than needed | | Media | GitHub repo `binarysust-media`, deployed to its own Pages project at `media.binarysust.org` | Org-owned and versioned. Kept out of the site build, so the site stays under Pages' 20k-files-per-deploy limit | -| Builds | GitHub Actions (public repo, unlimited minutes) | Snapshot, build and deploy | +| Snapshot store | Cloudflare Workers KV free (1,000 writes/day) | The API writes the snapshot, CI reads it. R2 was rejected because enabling it needs a card | +| Builds | GitHub Actions (public repo, unlimited minutes) | Build and deploy | | Bot token | GitHub App installed on the org | Outlives any one student's personal token | | Sign-in | Google OAuth (Cloud project without billing) | No passwords, and every SUST student already has a Google account | | Mail | Brevo free (300/day, single verified sender) | RSVP confirmation and waitlist promotion. Optional. Resend was rejected because it needs a verified domain | @@ -166,7 +167,7 @@ Two structurally different designs were produced and judged independently: ## Tradeoffs accepted - We accept 2–4 minutes of publish latency in exchange for a public site that is fast, free, and still up when the API is down or broken. -- We accept a read-only Supabase credential in GitHub Actions secrets in exchange for builds that never depend on the API. +- We accept that the site is built from the snapshot the _deployed_ API produces, so a change to `site.Snapshot` must stay readable by the current web code (or the API ships first), in exchange for keeping database credentials out of CI. - We accept over-triggered CI runs (republish on by default) in exchange for never shipping a stale site because someone forgot to opt in. - We accept that `site.Snapshot` is a second list next to `club.Modules()`. It is checked at compile time, and it is the explicit public contract. - We accept up to a minute of "Waking the server…" on the first sign-in or RSVP after a quiet period. Islands start waking the API as soon as they mount, so by the time the user acts, it's usually awake. @@ -180,12 +181,13 @@ Two structurally different designs were produced and judged independently: - **Dynamic SSR with an edge cache (Next.js on Vercel, or Astro or TanStack Start on Workers).** Every cache miss waits on a sleeping API. It also needs a server runtime under a 10 ms CPU limit, and caching rules leak into every page. - **Content stored in git (markdown plus a git-based CMS).** Portfolios edited by hundreds of members, role-gated review and committee history are relational data with permissions. Putting them in git hands merge conflicts and access control to students. -- **The build pulls the snapshot from the API.** Every build would first wait about a minute for Render to wake, and would fail when Render is down. +- **The build pulls the snapshot from the API.** A deploy would fail whenever the API is down. The API now pushes the snapshot to Workers KV instead (ADR 0002). +- **CI reads Supabase directly (the original design).** It kept a database credential in GitHub secrets and needed Supabase's IPv4 pooler. Replaced by ADR 0002. +- **R2 as the snapshot store.** Cloudflare requires a payment method before R2 can be enabled, which breaks "no card anywhere". ## Open questions and risks - The club owns `binarysust.org` (Namecheap, expires 2027-09-20). Who keeps renewing it? An expired domain takes the site, sign-in and media down together. -- GitHub disables scheduled workflows on public repos after 60 days with no commits, so the nightly rebuild could silently stop. Should a Cloudflare cron trigger the nightly rebuild instead? Note that the client-side "hide past events" script already covers stale pages. - Should non-SUST guests be able to RSVP? Today anyone with a Google account can. ## Next implementation step diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index da7f93c..960ce57 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -60,8 +60,7 @@ Terraform (step 0) creates project `binarysust` in Singapore (`ap-southeast-1`) 1. **Turn off the Data API** (Project Settings → Data API → disable). Left on, Supabase serves tables in `public` over REST and GraphQL to anyone holding the project's anon key. -2. In the SQL editor, take away what Supabase grants its Data API roles, and create the read-only role for the - site build: +2. In the SQL editor, take away what Supabase grants its Data API roles: ```sql -- Supabase-only roles get nothing in the API's schema, now or for tables created later. REVOKE ALL ON ALL TABLES IN SCHEMA public FROM anon, authenticated; @@ -70,16 +69,12 @@ Terraform (step 0) creates project `binarysust` in Singapore (`ap-southeast-1`) ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated; ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON SEQUENCES FROM anon, authenticated; ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public REVOKE ALL ON FUNCTIONS FROM anon, authenticated; - - CREATE ROLE site_reader LOGIN PASSWORD ''; - GRANT CONNECT ON DATABASE postgres TO site_reader; - GRANT USAGE ON SCHEMA public TO site_reader; - GRANT SELECT ON ALL TABLES IN SCHEMA public TO site_reader; - ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT SELECT ON TABLES TO site_reader; ``` 3. Connect → **Session pooler** connection string (IPv4, supports prepared statements; the direct connection is - IPv6-only on the free plan). With the `postgres` password it is `DATABASE_URL` for the VPS (step 3). With - user `site_reader.` and its password it is `SNAPSHOT_DATABASE_URL` for GitHub Actions (step 5). + IPv6-only on the free plan). With the `postgres` password it is `DATABASE_URL` for the VPS (step 3). The API + is the only database client: CI builds the site from the snapshot the API stores in Workers KV (step 5). +4. Projects set up before the API published snapshots had a read-only `site_reader` role for CI. Drop it: + `REASSIGN OWNED BY site_reader TO postgres; DROP OWNED BY site_reader; DROP ROLE site_reader;` ## 2. Google sign-in @@ -119,7 +114,8 @@ hostname directly: the site's `/api/*` Pages Function proxies to it, so members - `DATABASE_URL`: Supabase session pooler string (user `postgres.`, with the password) - Optional, each turns on a feature: `PUBLIC_URL`, `EKMAN_SECRET` (`openssl rand -base64 48`), `GOOGLE_CLIENT_ID`/`GOOGLE_CLIENT_SECRET` (Google sign-in), the `GITHUB_MEDIA_*` trio (uploads), - `GITHUB_REPOSITORY`/`GITHUB_DISPATCH_TOKEN` (auto-republish, step 5), `BREVO_API_KEY` (mail). Uncomment them + `GITHUB_REPOSITORY`/`GITHUB_DISPATCH_TOKEN` (auto-republish, step 5), the `SNAPSHOT_KV_*` pair with + `CLOUDFLARE_ACCOUNT_ID` (the snapshot the site is built from, step 5), `BREVO_API_KEY` (mail). Uncomment them as you get the values, then `sudo systemctl restart binarysust-api`. 3. **Cloudflare Tunnel**: Terraform (step 0) creates tunnel `binarysust-vps`, routes `api.binarysust.org` to `localhost:8081` and adds the DNS record. Install the connector on the VPS once, with the token from @@ -158,8 +154,9 @@ The club owns `binarysust.org` at Namecheap (expires 2027-09-20). Cloudflare's f In `BinarySUST/binarysust-web` → Settings → Secrets and variables → Actions: -- `SNAPSHOT_DATABASE_URL`: Supabase `site_reader` string - `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`: written by Terraform (step 0) +- `SNAPSHOT_KV_NAMESPACE_ID`, `SNAPSHOT_KV_READ_TOKEN`: see "Snapshot store" below +- Delete `SNAPSHOT_DATABASE_URL` if it is still there: CI no longer reads the database. - `VPS_HOST`, `VPS_USER`: the VM's address and an SSH user with passwordless sudo - `VPS_SSH_KEY`: that user's private key - `VPS_KNOWN_HOSTS`: output of `ssh-keyscan -t ed25519 `, so the workflow pins the host key @@ -173,6 +170,23 @@ GitHub account, owned by the `BinarySUST` org: Set their expiry to one year and add renewing them to the committee handover checklist. A GitHub App is the long-term replacement (see ARCHITECTURE.md, open questions). +### Snapshot store (Workers KV) + +The API builds the snapshot and stores it in Workers KV, and the publish workflow reads it from there +(docs/adr/0002-snapshot-in-workers-kv.md). Workers KV is on Cloudflare's free plan with no card; R2 would need one. + +1. Cloudflare dashboard → Storage & Databases → **Workers KV** → Create namespace `binarysust-snapshot`. Copy its ID. +2. My Profile → API Tokens → two custom tokens, each with Account: _Workers KV Storage_ only: + - **Edit**, for the API: `SNAPSHOT_KV_TOKEN` in `/etc/binarysust-api.env`, next to `SNAPSHOT_KV_NAMESPACE_ID` + and `CLOUDFLARE_ACCOUNT_ID`. + - **Read**, for CI: the `SNAPSHOT_KV_READ_TOKEN` secret, next to the `SNAPSHOT_KV_NAMESPACE_ID` secret. +3. `sudo systemctl restart binarysust-api`. At boot the API stores the current snapshot and dispatches a build; + its log says `republish: published snapshot`. + +Each changed publish writes two keys: `snapshot:` (expires after 30 days) and `latest`. That stays far below +the free plan's 1,000 writes a day. The API also republishes at 00:05 Asia/Dhaka when the date changes what the +site shows, and an admin can force a rebuild with `POST /api/v1/site/republish`. + `binarysust-media` deploys itself to the `binarysust-media` Pages project on every push. It needs the same two Cloudflare secrets: add `binarysust-media` to `github_repositories` in `infra/terraform/variables.tf` once that repository exists. @@ -196,7 +210,7 @@ After that, give out every other role from the dashboard's **Committee & roles** ## Yearly handover checklist - Dashboard → Committee & roles → create the new term, fill its seats, click **Make current**. -- Rotate `GITHUB_*` and `TF_*` tokens if they expire within 3 months. +- Rotate `GITHUB_*`, `TF_*` and the two `SNAPSHOT_KV` tokens if they expire within 3 months. - Hand over the HCP Terraform organization (it holds the state) along with the other club accounts. - Check the `binarysust.org` renewal date at Namecheap (next: 2027-09-20). - Make sure at least two people know the club Google account's password and have recovery set up. The account diff --git a/docs/adr/0002-snapshot-in-workers-kv.md b/docs/adr/0002-snapshot-in-workers-kv.md new file mode 100644 index 0000000..3f006d2 --- /dev/null +++ b/docs/adr/0002-snapshot-in-workers-kv.md @@ -0,0 +1,43 @@ +# ADR 0002: The API publishes the snapshot to Workers KV + +- Status: accepted +- Date: 2026-11-20 +- Spec: BinarySUST/binarysust-web#7. Research: `docs/research/publish-snapshot-source.md` + +## Context + +The public site is built from one `site.Snapshot` (ARCHITECTURE.md, decision 1). Until now, the publish workflow +built it itself: it installed Go, compiled `cmd/snapshot` and connected to Supabase with a read-only role whose +connection string lived in GitHub secrets. That meant: + +- **A database credential in CI.** GitHub's hosted-runner IPs can't usefully be allowlisted, so the credential is effectively reachable from the whole internet. +- **The IPv4 pooler.** GitHub runners are IPv4-only, and Supabase's free direct connection is IPv6, so CI had to go through the pooler. +- **Slow runs.** About half a minute of every run went to downloading Go modules and compiling. +- **Repeated database reads.** Every run, including the nightly one and code-only pushes, queried the database again. + +The project rule is "$0, no card anywhere" on free plans. + +## Decision + +The API is the only producer of the snapshot, and Cloudflare Workers KV holds it between the API and CI. + +- **`republish.Publisher` (in the API) produces it.** It implements the existing `republish.Notifier`, so the middleware and `republish.Skip()` are unchanged. The middleware only signals it, so an editor's write is never delayed. +- **One background goroutine builds it.** Each run calls `site.Build` and compares the hash with the last published one. If the hash changed, it stores `snapshot:` (30-day TTL), then `latest` (`{hash, builtAt}`), then fires `repository_dispatch` with `client_payload.hash`. Signals that arrive during a run merge into one next run. +- **Runs are triggered by** content writes, API boot (so a deploy that changes `site.Build` publishes at once), 00:05 Asia/Dhaka (the date rollover, replacing the workflow cron), and `POST /site/republish` (permission `site.publish`, forced). +- **A failure is retried on the next trigger.** A failure is logged and never returned to the editor. The hash only counts as published after the dispatch succeeds. +- **The publish workflow reads the snapshot from KV.** It fetches `snapshot:`, or `latest` for push and manual runs, with a read-only KV token. It retries for about two minutes, because KV is eventually consistent, and builds as before. Without KV secrets (forks) it builds the fixture and never deploys. +- **`SNAPSHOT_DATABASE_URL` and the `site_reader` role are removed.** `cmd/snapshot` stays for local builds. + +## Alternatives + +- **R2.** Strongly consistent and free at this size, but Cloudflare requires a payment method before R2 can be enabled. +- **CI pulls from an API endpoint (OIDC-authenticated).** Simpler, but a deploy fails whenever the API is down, and code-only pushes would depend on the API. +- **Keep CI on Supabase and fix the Go cache.** Fixes the speed, keeps the credential. +- **Render at request time.** Reverses decision 1. + +## Consequences + +- No database credential in GitHub, and publish runs no longer need Go. +- The site is built from what the deployed API produces. A change to `site.Snapshot` must stay readable by the current web code, or the API must ship first so its boot publish refreshes KV. +- The free plan allows 1,000 KV writes a day. Each changed publish uses two. +- One process publishes: running more than one API instance would need coordination. diff --git a/docs/research/publish-snapshot-source.md b/docs/research/publish-snapshot-source.md new file mode 100644 index 0000000..67f98c3 --- /dev/null +++ b/docs/research/publish-snapshot-source.md @@ -0,0 +1,427 @@ +# Where should the publish pipeline get its content snapshot? + +> **Decision (2026-11-20):** the maintainers chose a push model, as in option A, but storing the snapshot +> in **Workers KV** rather than R2, because R2 needs a payment method on the Cloudflare account and the +> project has a "no card anywhere" rule. See docs/adr/0002-snapshot-in-workers-kv.md and +> BinarySUST/binarysust-web#7. The comparison below is kept as written. + +Research note, 2026-11-20. Question: how `.github/workflows/publish.yml` should obtain the `site.Snapshot` +that the static site is pre-rendered from. Option B (CI fetches it from an authenticated API endpoint) is the +main candidate. Every external claim links to its primary source. Claims about this repo cite the file. + +## TL;DR + +- **Recommendation: B, authenticated with GitHub Actions OIDC, not a static bearer token.** The API verifies + a short-lived JWT from `https://token.actions.githubusercontent.com` and pins `repository_id`, `ref` and + `workflow_ref`. This removes `SNAPSHOT_DATABASE_URL` from GitHub, and no new long-lived secret replaces it. +- B has two real costs. A build now depends on the API being up. And on a push that changes the snapshot shape, + the build reads from whatever API version is deployed. Fix the first with curl retries plus a cached + last-good snapshot. Fix the second by having publish run after `deploy-api` succeeds instead of racing it. +- `docs/ARCHITECTURE.md` lists "The build pulls the snapshot from the API" as a rejected alternative. The + reason was "wait about a minute for Render to wake". That premise is gone: the API now runs on an always-on VPS + (`docs/DEPLOY.md` §3). The other reason, "would fail when Render is down", still applies, and the fallback + below addresses it. Update that section and the "Tradeoffs accepted" bullet when B lands. +- **The `go: downloading` lines found along the way are a cache bug, not a slow network.** The setup-go cache + entry is 7.29 KiB and empty. The cache key never changes, so it is never re-saved (details under Q6). The + same entry affects `deploy-api`. +- A (R2) adds a bucket, a token and an upload path to the API with no benefit over B at this scale. C only fixes + speed and keeps the DB credential in CI. D conflicts with the architecture's core decision. + +## Current state (repo facts) + +- `publish.yml` runs `go run ./cmd/snapshot -out ../web` with `DATABASE_URL=${{ secrets.SNAPSHOT_DATABASE_URL }}`. + It reads the printed `version.hash`, compares it with `$SITE_URL/version.json`, and skips the deploy when they + match. The skip is not used for `push` or `workflow_dispatch`. + (`.github/workflows/publish.yml`) +- `cmd/snapshot` opens Postgres, calls `site.Build(ctx, svc.Sources, time.Now())` and writes + `apps/web/.snapshot/site.json`. (`apps/api/cmd/snapshot/main.go`) +- `site.Build` is the same function the dashboard's `GET /api/v1/site/preview` (signed-in) calls. + It runs in one read-only, repeatable-read transaction, and `Version.Hash` is the sha256 of everything except + `Version`. (`apps/api/internal/site/site.go`) +- The republish middleware fires `repository_dispatch {event_type: "publish", client_payload: {reason}}` after + every 2xx non-GET request unless the route opts out with `republish.Skip()`. It uses a fine-grained PAT + (`GITHUB_DISPATCH_TOKEN`). (`apps/api/internal/republish/republish.go`, `docs/DEPLOY.md` §5) +- The API is a systemd service on an Oracle VM. Cloudflare Tunnel publishes it as `api.binarysust.org`, and the + site's `/api/*` Pages Function proxies to it. (`docs/DEPLOY.md` §3, `apps/web/functions/api/[[path]].ts`, + `.github/workflows/deploy-api.yml`) +- Measured on run 44619272155 (2026-11-19): the snapshot step took about 26 s. Module downloads finished in + under 0.5 s, so nearly all of the 26 s was compiling with a cold build cache. The real snapshot was small + (2 people, 0 events). + +## Options compared + +| | B: CI GETs snapshot from API | A: API pushes to R2, CI downloads | C: keep direct DB, cache/prebuild Go | D: render at request time | +| ----------------------- | ---------------------------- | ------------------------------------------- | ----------------------------------------- | ---------------------------- | +| DB credential in GitHub | none | none | yes (`site_reader`) | none | +| New CI secret | none with OIDC | R2 read token (or public bucket) | none | n/a | +| New API code | 1 route + OIDC verifier | R2 client, upload after each write, retries | none | whole SSR path | +| Build depends on API up | yes (mitigated by fallback) | no, if the object exists | no | every cache miss | +| Snapshot code version | the deployed API's | the deployed API's | the commit being built | the deployed API's | +| Extra infra | none | R2 bucket + token | none | Workers runtime, cache rules | +| Speed of the step | one HTTP GET (~1 s) | one GET | ~26 s today, a few s with a working cache | n/a | + +### B: authenticated endpoint (main candidate) + +- **Removes a credential class.** A Postgres login for Supabase that GitHub runners can reach cannot be + IP-restricted in any useful way. GitHub says hosted-runner IP ranges are "shared with unrelated services and + customers" and advises against allowlisting them + ([GitHub-hosted runners reference](https://docs.github.com/en/actions/reference/runners/github-hosted-runners)). + Supabase network restrictions cover "all connection routes, whether pooled or direct" + ([Supabase network restrictions](https://supabase.com/docs/guides/platform/network-restrictions)). With B, + only the VPS connects to the DB, so restrictions could be set to the VPS's IP. +- **Keeps one renderer.** It serves the same `site.Build` the dashboard preview already uses + (`apps/api/internal/site/site.go`). +- **Cost: the snapshot comes from the deployed API, not from `github.sha`.** `publish.yml` also triggers on pushes + touching `apps/api/internal/site/**` and `apps/api/cmd/snapshot/**`, and `deploy-api.yml` triggers on the same + push (`apps/api/**`). With B, publish could fetch an old-shape snapshot from an API that is still mid-deploy. + Fix: publish on `workflow_run` of `deploy-api` with `conclusion == 'success'`. Both workflows must be on + the default branch, and chaining is capped at three levels + ([events that trigger workflows: workflow_run](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)). + Alternatively, `deploy-api` can fire the `publish` dispatch itself after its health check passes. +- **Cost: API down means no fresh snapshot.** See Q5. + +### A: API renders and uploads to R2 after each write + +- R2 is strongly consistent for read-after-write: "readers will immediately see the latest object globally" + ([R2 consistency](https://developers.cloudflare.com/r2/reference/consistency/)). It is free for this size + (10 GB-month storage, 1M Class A and 10M Class B operations per month, no egress fee) + ([R2 pricing](https://developers.cloudflare.com/r2/pricing/)). +- Tokens can be scoped to one bucket with "Object Read only" or "Object Read & Write". Those object-level + permissions work only with the S3-compatible API + ([R2 API tokens](https://developers.cloudflare.com/r2/api/tokens/)). So the API needs an S3 client, and CI + needs either a read token (a new long-lived secret) or a public bucket. +- The upload would run in the write path. The republish middleware deliberately runs inside the request so a + sleeping instance cannot drop it (`republish.go`). A full `site.Build` plus upload on every write is more work + in that path than B, which builds only when CI asks. +- A's benefit is that builds succeed while the API is down. B with a cached fallback gets most of that benefit + without new infrastructure. A also has the same "snapshot from the deployed API version" issue as B. + +### C: keep direct DB access, fix the Go cache + +- This keeps the read-only Postgres credential in GitHub. That is the tradeoff `docs/ARCHITECTURE.md` already + accepts ("We accept a read-only Supabase credential in GitHub Actions secrets"). +- Its only gain is speed, and fixing the broken cache (Q6) gets that with no design change. Worth doing in any + case, because `deploy-api` shares the same broken cache entry. +- C is the only option that builds the snapshot with the code at `github.sha`. + +### D: render at request time + +- Pages Functions can read R2 (`context.env.BUCKET.get(...)`) + ([Pages Functions bindings](https://developers.cloudflare.com/pages/functions/bindings/)). Free Workers allow + 100,000 requests per day and 10 ms CPU per request + ([Workers limits](https://developers.cloudflare.com/workers/platform/limits/)). +- This reverses the architecture's central decision: static pre-rendered pages "still up when the API is down". + "Dynamic SSR with an edge cache" is already a rejected alternative (`docs/ARCHITECTURE.md`). Not pursued. + +## Q1. GitHub Actions secrets vs OIDC + +**Secrets.** Secrets are not passed to workflows triggered from forks (`GITHUB_TOKEN` is the exception), and +values over 48 KB need a workaround +([Using secrets in GitHub Actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions)). +A static bearer token for B would be a second long-lived shared secret, living in GitHub and in +`/etc/binarysust-api.env`. It would need rotation in the yearly handover, like `GITHUB_DISPATCH_TOKEN` +(`docs/DEPLOY.md`, handover checklist). + +**OIDC.** GitHub's stated benefits: "You won't need to duplicate your cloud credentials as long-lived GitHub +secrets", and the provider-issued token "is only valid for a single job, and then automatically expires" +([OpenID Connect concepts](https://docs.github.com/en/actions/concepts/security/openid-connect)). + +How to get a token in a job: + +- The job needs `permissions: id-token: write`. That permission "only enables fetching and setting the OIDC + token; it does not grant write access to other resources" + ([OIDC reference](https://docs.github.com/en/actions/reference/security/oidc)). +- The runner exposes `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`. A custom audience is + passed as `&audience=...` on that URL ([OIDC reference](https://docs.github.com/en/actions/reference/security/oidc)). + The response's `.value` field is the JWT + ([OIDC in cloud providers](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-cloud-providers)). + +How the API verifies it: + +1. **Issuer** must equal `https://token.actions.githubusercontent.com`. Discovery is at + `/.well-known/openid-configuration`. It gives `jwks_uri = https://token.actions.githubusercontent.com/.well-known/jwks` + and the only signing algorithm, `RS256` + ([discovery document](https://token.actions.githubusercontent.com/.well-known/openid-configuration)). +2. **Signature** is checked against the JWKS, and the algorithm is pinned. RFC 8725 §3.1 says libraries "MUST + enable the caller to specify a supported set of algorithms", and §3.8 says the keys must belong to the issuer + ([RFC 8725](https://www.rfc-editor.org/rfc/rfc8725)). +3. **Audience.** The default `aud` is the repository owner's URL + ([OIDC reference](https://docs.github.com/en/actions/reference/security/oidc)). Request a custom one such as + `binarysust-api` and require it. RFC 8725 §3.9 says recipients must reject a missing or mismatched `aud`. +4. **Expiry** (`exp`, `nbf`, `iat`). GitHub does not document a fixed lifetime. Its example token spans 300 s + ([OpenID Connect concepts](https://docs.github.com/en/actions/concepts/security/openid-connect)). +5. **Repository claims.** GitHub says to "define at least one trust condition" so untrusted repositories can't + use your trust, and recommends `repository_id` / `repository_owner_id` because they survive renames and + name recycling ([OIDC reference](https://docs.github.com/en/actions/reference/security/oidc)). For this repo, + require: + - `repository_id` = BinarySUST/binarysust-web's numeric ID (and/or `repository_owner_id`) + - `ref` = `refs/heads/main`. `repository_dispatch` always runs on the default branch with + `GITHUB_REF` = the default branch + ([events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)) + - `workflow_ref` = `BinarySUST/binarysust-web/.github/workflows/publish.yml@refs/heads/main`. The format is + shown in the [OIDC reference](https://docs.github.com/en/actions/reference/security/oidc). + - optionally `event_name` in `{repository_dispatch, push, schedule, workflow_dispatch, workflow_run}` + +In Go, `github.com/coreos/go-oidc/v3/oidc` does this. `NewProvider` performs discovery and rejects an +issuer mismatch, and `Provider.Verifier(&oidc.Config{ClientID: "binarysust-api"})` checks signature, issuer, +audience and expiry. Its `RemoteKeySet` caches keys and re-fetches when it sees an unknown key ID. `IDToken.Claims` +decodes the repository claims ([go-oidc docs](https://pkg.go.dev/github.com/coreos/go-oidc/v3/oidc)). It would be +the API's first JWT dependency (`apps/api/go.mod` has none today). + +**Is OIDC better than a static bearer token for B? Yes, with one caveat.** There is nothing to store, rotate or +hand over. A leaked token is useless within minutes. The claims prove the request came from `publish.yml` on +`main` of this repo. The caveat: anyone who can merge a workflow change to `main` can mint a valid token. The same +is true of any secret available to that workflow, so OIDC is no weaker. + +The snapshot holds only public data (published content, listed people; `docs/snapshot.md`). So auth on this +endpoint mainly prevents abuse: it stops anyone from triggering a full-database repeatable-read `Build` at will. +It is not mainly about confidentiality. + +## Q2. repository_dispatch payload and concurrency + +- **Limits:** `client_payload` allows at most 10 top-level properties and "must be less than 64KB", and + `event_type` is at most 100 characters + ([REST: create a repository dispatch event](https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event)). + The events reference gives the payload limit as 65,535 characters + ([events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)). + A fine-grained PAT needs **Contents: write** + ([fine-grained PAT permissions](https://docs.github.com/en/rest/authentication/permissions-required-for-fine-grained-personal-access-tokens)), + which matches `docs/DEPLOY.md`. +- **Could the snapshot ride in the payload?** No. The committed fixture is already 35,677 bytes + (`apps/web/.snapshot/fixture.json`). A real club with hundreds of people, bios and posts will pass 64 KB. + It would also force the API to run a full `Build` inside every write request. +- **Could the hash ride in the payload?** Possible, but of little use. The middleware does not build a snapshot + (`republish.go`), so it would have to compute one per write. More importantly, under concurrency the pending run + is replaced by the newest one, so a payload describes one write, not "what to build". The run should always + fetch the current state when it starts. The current design already relies on that ("the pending one sees all + edits", `publish.yml`). +- **Concurrency semantics:** with `cancel-in-progress: false`, there is "at most one running job or workflow + in a concurrency group at any time". Under the default `queue: single`, "any existing `pending` job or workflow + run in the same group is canceled and replaced". `queue: max` allows up to 100 pending runs + ([workflow syntax: concurrency](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax)). + With B this still holds: the surviving pending run fetches the snapshot at its own start, after every write + that triggered the runs it replaced. Keep `queue: single`; `max` would only cause redundant builds. +- **Default branch:** `repository_dispatch` runs only if the workflow file is on the default branch, with + `GITHUB_SHA` = the default branch's last commit + ([events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)). + This is why pinning `ref` = `refs/heads/main` in the OIDC check is safe. +- **Scheduled trigger:** scheduled runs may be delayed or dropped under load, and "are automatically disabled" + after 60 days of no repository activity on public repos + ([events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows)). + `docs/ARCHITECTURE.md` already lists this as an open risk. B doesn't change it. + +## Q3. Supabase from CI + +- Supabase lists GitHub Actions among services that "only accept IPv4 connections" + ([Supabase IPv4/IPv6 compatibility](https://supabase.com/docs/guides/troubleshooting/supabase--your-network-ipv4-and-ipv6-compatibility-cHe3BP)). + The direct connection is IPv6 on Free/Pro unless you buy the IPv4 add-on. The shared pooler in session mode + (port 5432) is reachable over IPv4 on every plan and supports prepared statements. Transaction mode (6543) + suits many short-lived connections but has no prepared statements + ([Connecting to Postgres](https://supabase.com/docs/guides/database/connecting-to-postgres)). The repo's choice + of the session pooler for `SNAPSHOT_DATABASE_URL` (`docs/DEPLOY.md` §1.3) is the documented route for an + IPv4-only client that uses pgx's prepared statements. +- Read-only roles: Supabase says never to hand out the `postgres` password and to "create a new user for every + service". Example pooler usernames take the form `role.projectref` + ([Postgres roles](https://supabase.com/docs/guides/database/postgres/roles)). That matches the + `site_reader.` setup. +- **Risks of the current approach:** + 1. A Postgres login reachable from the whole internet, because hosted-runner IPs can't be usefully allowlisted + (Q1 sources). It is read-only, but it can still read every column of every table in `public`, including + emails and grants, not just public fields. `GRANT SELECT ON ALL TABLES` (`docs/DEPLOY.md` §1.2). + 2. A second credential to rotate. A third, if you count the API's own. + 3. Builds use whatever `cmd/snapshot` is at `github.sha`, against a schema migrated by whatever API is + deployed. The same version-skew issue as B, in the other direction. + 4. It prevents turning on Supabase network restrictions, which with B could be locked to the VPS. + +## Q4. Cloudflare: R2, Pages, deploy hooks, Workers + +- **Pages Direct Upload is permanent:** "If you choose Direct Upload, you cannot switch to Git integration + later". Wrangler uploads allow up to 20,000 files of up to 25 MiB each + ([Direct Upload](https://developers.cloudflare.com/pages/get-started/direct-upload/)). The free plan allows + 500 builds per month, one concurrent build, and a 20-minute timeout. Those build limits are written for + Git-integrated builds ([Pages limits](https://developers.cloudflare.com/pages/platform/limits/)). +- **Deploy hooks** are URLs that start a new _build_ on POST + ([deploy hooks](https://developers.cloudflare.com/pages/configuration/deploy-hooks/)). Setting one up requires + a "branch to build", that is, a Git-connected project. The docs do not say they work for Direct Upload + projects, which is what `binarysust` is (`publish.yml` uses `wrangler pages deploy`). Treat them as + unavailable. Even if they worked, they would move the build onto Cloudflare's 500/month quota. That quota is + what `docs/ARCHITECTURE.md` says Actions builds sidestep. +- **R2** for option A: strongly consistent, free at this size, and bucket-scoped tokens only on the S3 API + (sources under option A). +- **Workers Cron Triggers** could replace the GitHub `schedule` trigger that may go dormant. They run in UTC + ([cron triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/)), the free plan + allows 5 per account and 10 ms CPU per run + ([Workers limits](https://developers.cloudflare.com/workers/platform/limits/)). A cron Worker would just POST + the `publish` dispatch. That needs a GitHub token in the Worker, which is out of scope here. +- **Nothing here replaces B's core.** Cloudflare cannot run the Go `site.Build`. The snapshot must come from the + API (B, A) or from the DB (C). + +## Q5. B's failure mode: API down + +The API sits behind Cloudflare Tunnel. When no healthy `cloudflared` is connected, Cloudflare returns error +1033 ([error 1033](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/error-1033/)). +A systemd restart during `deploy-api` gives a short window of 502/connection errors. + +Standard mitigations, in order: + +1. **Retry with exponential backoff.** curl's `--retry N` retries "transient" errors (timeouts, HTTP 408, 429, + 500, 502, 503, 504). It waits 1 s, then doubles the wait up to 10 minutes. `--retry-max-time` caps the total, + and `--retry-all-errors` widens the set, described as the "sledgehammer" (`man curl`, curl 8.x; + [curl manpage](https://curl.se/docs/manpage.html)). A Tunnel error status is not in the transient list, so either + use `--retry-all-errors` (safe for an idempotent GET to a file) or loop in shell. Something like + `--retry 5 --retry-all-errors --retry-max-time 120 --max-time 30` covers a restart window inside the job's + 15-minute timeout. +2. **Fall back to the last good snapshot, by trigger.** + - `repository_dispatch` / `schedule`: if the API stays down, **skip the deploy with a warning**. The live site + is already the newest content anyone could publish. The next write or nightly run catches up, which is the + same "catches up" contract the middleware already uses for failed dispatches (`republish.go`). + Exception: the nightly run exists for date roll-overs (`publish.yml`). Rebuilding from the cached snapshot + still moves `builtAt` and date-derived pages forward, so use the fallback for `schedule` too. + - `push` / `workflow_dispatch` (code changes): build from the **cached last-good snapshot**, so a web-only + fix can still ship during an API outage. + - Cache it with `actions/cache/save` under key `site-snapshot-`, and restore with + `restore-keys: site-snapshot-`. With several partial matches "the action returns the most recently created + cache" ([dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching)). + Entries are immutable, evicted after 7 days unused, and the repository total is 10 GB (same source). The + nightly run keeps the entry warm. + - Last resort if the cache is empty: keep today's fixture path (`hash=fixture`), but **refuse to deploy** it + to production. Deploying the fixture over real content would be worse than not deploying. +3. **Don't let the hash check mask an outage.** The current `curl ... | jq -r .hash || echo none` treats a + missing live `/version.json` as "changed", which is the right direction. Keep that. A failed snapshot fetch must + not produce an empty hash that compares equal to anything. + +## Q6. Caching for option C, and why a fresh run says `go: downloading` + +How `actions/setup-go` caches (source at `main`, commit `d8cbb80`): + +- It caches the directories printed by `go env GOMODCACHE` and `go env GOCACHE` + ([package-managers.ts](https://github.com/actions/setup-go/blob/main/src/package-managers.ts)). +- The key is `setup-go-${RUNNER_OS}-${arch}-${ImageOS}-go-${versionSpec}-${hashFiles(cache-dependency-path)}`. + The default dependency file is `go.mod`, which the README says has been the default since v6. The restore is an + **exact-key restore with no restore-keys** + ([cache-restore.ts](https://github.com/actions/setup-go/blob/main/src/cache-restore.ts), + [README](https://github.com/actions/setup-go)). +- The save runs in the post step only on `success()` + ([action.yml](https://github.com/actions/setup-go/blob/main/action.yml)). It **does not save when the primary + key was hit** ("Cache hit occurred on the primary key ..., not saving cache") + ([cache-save.ts](https://github.com/actions/setup-go/blob/main/src/cache-save.ts)). +- Cache entries can't be modified, only replaced under a new key + ([dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching)). +- The Go command "will automatically download modules as needed during ordinary execution" into the module + cache, and `go mod download` pre-fills it ([Go modules reference](https://go.dev/ref/mod#go-mod-download)). + `go run` "compiles and runs the named main Go package" ([cmd/go](https://pkg.go.dev/cmd/go)), so a cold + `GOCACHE` means a full compile. + +**Why this repo's runs show `go: downloading` (verified with `gh cache list` and run logs):** + +1. Run 41347866158 (publish, push, 2026-11-01) had no `SNAPSHOT_DATABASE_URL` yet, so it took the fixture + branch and never ran a Go command. Its setup-go post step warned + `Cache folder path is retrieved but doesn't exist on disk: /home/runner/go/pkg/mod`, then saved an almost + empty entry: `setup-go-Linux-x64-ubuntu26-go-1.27.0-baa8afe3...`, **7.29 KiB**. +2. Every later run computes the same key (same Go version, same `apps/api/go.sum`). It gets an exact hit on that + empty entry ("Cache Size: ~0 MB (7474 B)"), so it never saves again. Every run then downloads all modules and + compiles from scratch (about 26 s in run 44619272155). +3. `deploy-api.yml` uses the same `go-version-file` and `cache-dependency-path`, so it hits the same empty + entry. + +Fixes for C, or for `deploy-api` under any option: delete that one cache entry once with `gh cache delete`. +Better, make the key depend on something that guarantees content, such as a per-workflow suffix via a different +`cache-dependency-path` glob, or a separate `actions/cache` step keyed on +`hashFiles('apps/api/**/*.go', 'apps/api/go.sum')` that caches a prebuilt `snapshot` binary. Running +`go mod download` before the fixture early-exit would also stop an empty entry being saved. + +## Recommendation and outline for B + +**Do B with OIDC, a retry-plus-cache fallback, and publish ordered after `deploy-api`.** Separately, delete the +empty setup-go cache entry, because it slows `deploy-api` either way. + +### Endpoint + +- `GET /api/v1/site/snapshot`, in the `site` module next to `/site/preview`. It returns `site.Snapshot` exactly as + `cmd/snapshot` writes it, built by the same `site.Build(ctx, src, now)`. +- Response headers: + - `ETag: ""` + - `Cache-Control: no-store` + - `X-Api-Commit: `, so CI can check it serves the code it expects. +- Optional `If-None-Match` → `304`. CI could then skip the build without downloading, though the body is small + enough that this is a nicety. +- Route option `republish.Skip()` is irrelevant because it is a GET (`ShouldPublish` ignores GETs). +- CI should call `https://api.binarysust.org` directly, not `www.binarysust.org/api`. That avoids a hop through + the Pages Function, and the proxy forwards the `Authorization` header anyway. + +### Auth + +- Add a middleware/access rule, e.g. `ekman.Requires(GitHubOIDC)`, backed by `go-oidc`: + - issuer `https://token.actions.githubusercontent.com` + - audience `binarysust-api` + - RS256 only + - `repository_id` = this repo's ID + - `ref` = `refs/heads/main` + - `workflow_ref` = `BinarySUST/binarysust-web/.github/workflows/publish.yml@refs/heads/main` +- Config: + - `SNAPSHOT_OIDC_AUDIENCE`, `SNAPSHOT_OIDC_REPOSITORY_ID` in `/etc/binarysust-api.env`. These are not secrets. + - If unset, the route returns 404 or 503, so local development is unaffected. +- Log `run_id` and `event_name` from the claims for an audit trail. + +### Workflow step (replaces "Snapshot the database") + +```yaml +permissions: + contents: read + id-token: write + +on: + repository_dispatch: { types: [publish] } + workflow_run: { workflows: [deploy-api], types: [completed] } # replaces apps/api/** push paths + push: { branches: [main], paths: [apps/web/**, packages/**, pnpm-lock.yaml, .github/workflows/publish.yml] } + schedule: [{ cron: "5 18 * * *" }] + workflow_dispatch: + +jobs: + publish: + if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' + steps: + - uses: actions/cache/restore@v5 # last-good snapshot, newest first + with: { path: apps/web/.snapshot/site.json, key: site-snapshot-none, restore-keys: site-snapshot- } + - name: Fetch the snapshot + id: snapshot + run: | + jwt=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ + "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=binarysust-api" | jq -r .value) + if curl -fsS --retry 5 --retry-all-errors --retry-max-time 120 --max-time 30 \ + -H "Authorization: Bearer $jwt" -o "$RUNNER_TEMP/site.json" \ + https://api.binarysust.org/api/v1/site/snapshot; then + mv "$RUNNER_TEMP/site.json" apps/web/.snapshot/site.json + echo "source=api" >> "$GITHUB_OUTPUT" + elif [ -f apps/web/.snapshot/site.json ] && [ "${{ github.event_name }}" != repository_dispatch ]; then + echo "::warning::API unreachable; building from the cached last-good snapshot." + echo "source=cache" >> "$GITHUB_OUTPUT" + else + echo "::warning::API unreachable; nothing new to publish, skipping." + echo "source=none" >> "$GITHUB_OUTPUT"; exit 0 + fi + echo "hash=$(jq -r .version.hash apps/web/.snapshot/site.json)" >> "$GITHUB_OUTPUT" + - if: steps.snapshot.outputs.source == 'api' + uses: actions/cache/save@v5 + with: { path: apps/web/.snapshot/site.json, key: "site-snapshot-${{ steps.snapshot.outputs.hash }}" } + # existing "Skip if the live site already has this content", build and deploy steps, + # each additionally gated on steps.snapshot.outputs.source != 'none' +``` + +The last-resort fixture build stays for forks and local use, but never deploys to production. The setup-go step +goes away from `publish.yml`. + +### Follow-ups when implementing + +- `deploy-api`: either rely on `workflow_run`, or fire the `publish` dispatch after its health check. Pick one so a + site-contract change publishes exactly once, against the new API. +- Remove the `SNAPSHOT_DATABASE_URL` secret and `DROP ROLE site_reader` in Supabase. Consider Supabase network + restrictions limited to the VPS's IP. +- Update `docs/ARCHITECTURE.md`: + - the CI flow line + - point 1 ("CI produces the snapshot by reading Supabase directly") + - the "read-only Supabase credential" tradeoff + - the "build pulls the snapshot from the API" rejected alternative +- Also update `docs/DEPLOY.md` §1.2–1.3 and §5, and the comment in `cmd/snapshot/main.go`. `cmd/snapshot` can stay + as a local tool. +- Optionally record the decision as an ADR in `docs/adr/`. diff --git a/docs/snapshot.md b/docs/snapshot.md index e502bcb..badc073 100644 --- a/docs/snapshot.md +++ b/docs/snapshot.md @@ -1,7 +1,9 @@ # Snapshot contract -`site.Snapshot` (Go, `apps/api/internal/site`) is the only thing the public site reads. `cmd/snapshot` writes it -two ways from one value: +`site.Snapshot` (Go, `apps/api/internal/site`) is the only thing the public site reads. In production the API +builds it and stores it in Workers KV (`snapshot:` plus a `latest` pointer, ADR 0002), and the publish +workflow downloads it. Locally `pnpm snapshot` (`cmd/snapshot`) writes it from your database. Either way the +build uses it two ways from one value: - `apps/web/.snapshot/site.json`: the whole snapshot, read from disk at pre-render time. - `apps/web/public/data/**.json`: per-route slices, fetched by the browser on client-side navigation. diff --git a/infra/terraform/github.tf b/infra/terraform/github.tf index 6f8de89..0eb2ec7 100644 --- a/infra/terraform/github.tf +++ b/infra/terraform/github.tf @@ -1,6 +1,6 @@ # Actions secrets the Pages deploys need, in every repository in var.github_repositories. -# The VPS deploy secrets (VPS_*) and SNAPSHOT_DATABASE_URL stay out of Terraform on purpose: an SSH key and a -# database password would otherwise sit in state. Set those with `gh secret set` (docs/DEPLOY.md step 5). +# The VPS deploy secrets (VPS_*) and the SNAPSHOT_KV_* pair stay out of Terraform on purpose: an SSH key and an +# API token would otherwise sit in state. Set those with `gh secret set` (docs/DEPLOY.md step 5). resource "github_actions_secret" "cloudflare_account_id" { for_each = var.github_repositories diff --git a/infra/terraform/supabase.tf b/infra/terraform/supabase.tf index 084234b..ce4aa5f 100644 --- a/infra/terraform/supabase.tf +++ b/infra/terraform/supabase.tf @@ -1,6 +1,6 @@ # The production database. The API connects through the session pooler (IPv4, prepared statements); -# the `supabase_pooler` output has its connection strings. Roles and grants (site_reader, revoking the -# Data API roles) are SQL, applied once from the SQL editor: docs/DEPLOY.md step 1. +# the `supabase_pooler` output has its connection strings. Grants (revoking the Data API +# roles) are SQL, applied once from the SQL editor: docs/DEPLOY.md step 1. resource "random_password" "db" { length = 40 diff --git a/infra/vps/binarysust-api.env.example b/infra/vps/binarysust-api.env.example index de44195..ce949c0 100644 --- a/infra/vps/binarysust-api.env.example +++ b/infra/vps/binarysust-api.env.example @@ -31,6 +31,12 @@ DATABASE_URL= # GITHUB_REPOSITORY=BinarySUST/binarysust-web # GITHUB_DISPATCH_TOKEN= +# Workers KV namespace the site snapshot is stored in; the publish workflow builds from it (docs/DEPLOY.md, step 5). +# Unset: writes still dispatch, but CI has no snapshot to fetch. +# CLOUDFLARE_ACCOUNT_ID= +# SNAPSHOT_KV_NAMESPACE_ID= +# SNAPSHOT_KV_TOKEN= + # Mail. Unset BREVO_API_KEY: emails are logged instead of sent. # BREVO_API_KEY= # MAIL_FROM=binary.sust@gmail.com diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 1178fac..9b05bb3 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -540,6 +540,23 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/site/republish": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** Rebuild and deploy the site now, even if content is unchanged */ + post: operations["postSiteRepublish"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/site/status": { parameters: { query?: never; @@ -704,7 +721,7 @@ export interface components { * @description A permission declared by a module. * @enum {string} */ - Permission: "blog.review" | "blog.write" | "events.checkin" | "events.manage" | "media.upload" | "people.manage" | "profile.edit_own" | "roles.manage" | "sponsors.manage" | "talks.manage"; + Permission: "blog.review" | "blog.write" | "events.checkin" | "events.manage" | "media.upload" | "people.manage" | "profile.edit_own" | "roles.manage" | "site.publish" | "sponsors.manage" | "talks.manage"; "access.Account": { avatarUrl: string | null; email: string; @@ -1226,6 +1243,9 @@ export interface components { }; /** @enum {string} */ "site.PublishState": "live" | "publishing"; + "site.Queued": { + queued: boolean; + }; "site.Snapshot": { club: components["schemas"]["site.Club"]; committees: components["schemas"]["people.Committee"][]; @@ -2526,6 +2546,29 @@ export interface operations { default: components["responses"]["Error"]; }; }; + postSiteRepublish: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Accepted */ + 202: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["site.Queued"]; + }; + }; + 401: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + default: components["responses"]["Error"]; + }; + }; getSiteStatus: { parameters: { query?: never;