Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 40 additions & 25 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -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:<hash>, 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

Expand All @@ -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:
Expand All @@ -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 }}"
Expand All @@ -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
Expand Down
99 changes: 89 additions & 10 deletions apps/api/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ package main

import (
"context"
"encoding/json"
"flag"
"log/slog"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"time"

_ "github.com/jackc/pgx/v5/stdlib" // the "pgx" database/sql driver

Expand All @@ -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).
Expand All @@ -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.
Expand All @@ -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),
Expand Down Expand Up @@ -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 {
Expand All @@ -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}
}
Expand Down Expand Up @@ -169,15 +227,15 @@ 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)
}
// `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)
}
Expand All @@ -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())
Expand All @@ -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)
12 changes: 7 additions & 5 deletions apps/api/cmd/server/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading