showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
feat: feat: add build loop with atomic swap and page reuse
Showing 7 changed files with 265 additions and 8 deletions.
cmd/daumdev/main.go
+7 −2
@@ -9,6 +9,7 @@ import (99 "os"1010 "os/signal"1111 "syscall"12 "time"12131314 "daum.dev/showcase/internal/build"1415 "daum.dev/showcase/internal/config"@@ -19,6 +20,7 @@ func main() {1920 once := flag.Bool("once", false, "render the site once into -out and exit")2021 out := flag.String("out", "", "output directory for -once (must not exist)")2122 data := flag.String("data", "/data", "data directory (git mirrors, site builds)")23 every := flag.Duration("interval", 10*time.Minute, "time between builds")2224 flag.Parse()23252426 cfg, err := config.Load(*cfgPath)@@ -28,8 +30,11 @@ func main() {2830 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)2931 defer stop()303233 b := build.New(cfg, *data)3134 if !*once {32 fatal(errors.New("server mode is not implemented yet; use -once -out DIR"))35 slog.Warn("server not implemented yet; only building", "site", b.Current())36 b.Run(ctx, *every)37 return3338 }3439 if *out == "" {3540 fatal(errors.New("-once needs -out"))@@ -37,7 +42,7 @@ func main() {3742 if err := os.Mkdir(*out, 0o755); err != nil {3843 fatal(err)3944 }40 if err := build.New(cfg, *data).Render(ctx, *out); err != nil {45 if err := b.Render(ctx, *out); err != nil {4146 fatal(err)4247 }4348}
docs/decisions.md
+15 −6
@@ -18,12 +18,21 @@ Gitea package visibility follows the owner, not the linked repo, so a package1818linked to a private repo is public. Only packages linked to an allowlisted1919repo are listed.202021## Change detection is keyed on HEAD only2223Repo `updated_at` doesn't reliably change when PRs or releases change. API24pages (profile, releases, pulls, packages) are re-fetched and re-rendered25every build. Only git-derived pages (tree, blob, log, commit) are reused when26HEAD is unchanged.21## Change detection: reuse git pages when nothing they show changed2223Repo `updated_at` doesn't reliably change when PRs or releases change, so it24isn't used. Every build re-fetches the API and re-renders the profile, each25repo's root page, the log page and the releases, pulls and packages pages.26File, folder, raw and commit pages are hard-linked from the previous build27when the reuse key is unchanged. The key is HEAD plus the repo header data28(description, website, topics, archived, default branch, latest tag), because29every page shows that header. Keys live in memory, so a restart (which is30also how config or template changes ship) re-renders everything.3132Builds are written to `site/.tmp-<ts>`, renamed to `site/<ts>`, and published33by renaming a fresh `current.new` symlink over `current`. The newest and the34previous build are kept, and anything else (including temp dirs left by a35crash) is removed after each swap.27362837## Tailnet URLs never reach the page2938
internal/build/build.go
+1 −0
@@ -23,6 +23,7 @@ type Builder struct {2323 Data string // holds mirrors/ (and later site/)2424 Now func() time.Time2525 Log *slog.Logger26 st state2627}27282829func New(cfg *config.Config, data string) *Builder {
internal/build/log.go
+3 −0
@@ -36,6 +36,9 @@ func (b *Builder) renderLog(ctx context.Context, rd *render.Renderer, dir string3636 return err3737 }383839 if b.reuse(r, dir, "commit") {40 return nil41 }3942 listed := map[string]bool{}4043 for _, c := range p.Commits {4144 listed[c.Hash] = true
internal/build/loop.goadded
+150 −0
@@ -0,0 +1,150 @@1package build23import (4 "context"5 "crypto/sha256"6 "encoding/json"7 "fmt"8 "io/fs"9 "os"10 "path/filepath"11 "strings"12 "sync"13 "time"14)1516// Builds live in <data>/site/<timestamp>/; <data>/site/current is a symlink17// to the newest good one. The server only ever reads through current.18type state struct {19 mu sync.Mutex20 prev string // last good build dir, "" before the first21 keys map[string]string // repo -> reuse key of the last good build22 next map[string]string // keys of the build in progress23}2425func (b *Builder) siteDir() string { return filepath.Join(b.Data, "site") }2627// Current is the directory the server serves from.28func (b *Builder) Current() string { return filepath.Join(b.siteDir(), "current") }2930// Ready reports whether a good build exists (possibly from an earlier run).31func (b *Builder) Ready() bool {32 _, err := os.Stat(filepath.Join(b.Current(), "index.html"))33 return err == nil34}3536// Run builds now and then every interval until ctx ends. Failures are logged37// and the last good build keeps being served.38func (b *Builder) Run(ctx context.Context, every time.Duration) {39 t := time.NewTicker(every)40 defer t.Stop()41 for {42 start := time.Now()43 if err := b.BuildOnce(ctx); err != nil {44 b.Log.Error("build failed", "err", err, "took", time.Since(start))45 } else {46 b.Log.Info("build done", "took", time.Since(start))47 }48 select {49 case <-ctx.Done():50 return51 case <-t.C:52 }53 }54}5556// BuildOnce renders a new build and publishes it atomically. It never runs57// concurrently with itself, and never publishes a partial build.58func (b *Builder) BuildOnce(ctx context.Context) error {59 b.st.mu.Lock()60 defer b.st.mu.Unlock()61 if err := os.MkdirAll(b.siteDir(), 0o755); err != nil {62 return err63 }64 if b.st.prev == "" { // after a restart: keep serving the old build until the swap65 if t, err := os.Readlink(b.Current()); err == nil {66 b.st.prev = filepath.Join(b.siteDir(), t)67 }68 }69 name := b.Now().UTC().Format("20060102T150405.000")70 tmp := filepath.Join(b.siteDir(), ".tmp-"+name)71 b.st.next = map[string]string{}72 if err := os.Mkdir(tmp, 0o755); err != nil {73 return err74 }75 if err := b.Render(ctx, tmp); err != nil {76 os.RemoveAll(tmp)77 return err78 }79 final := filepath.Join(b.siteDir(), name)80 if err := os.Rename(tmp, final); err != nil {81 return err82 }83 link := b.Current() + ".new"84 os.Remove(link)85 if err := os.Symlink(name, link); err != nil {86 return err87 }88 if err := os.Rename(link, b.Current()); err != nil { // atomic swap89 return err90 }91 b.prune(name, filepath.Base(b.st.prev))92 b.st.prev, b.st.keys = final, b.st.next93 return nil94}9596// prune removes every build except keep (and the previous one, so requests97// already reading it can finish) plus leftovers from crashed builds.98func (b *Builder) prune(keep ...string) {99 entries, _ := os.ReadDir(b.siteDir())100 for _, e := range entries {101 n := e.Name()102 if n == "current" || n == keep[0] || n == keep[1] {103 continue104 }105 os.RemoveAll(filepath.Join(b.siteDir(), n))106 }107}108109// reuse links r's git-derived pages (dirs) from the previous build when the110// repo's HEAD and header data are unchanged. It reports whether it did.111func (b *Builder) reuse(r *repo, dir string, dirs ...string) bool {112 h, _ := json.Marshal([]any{r.Head, r.Description, r.Website, r.Topics, r.Archived, r.DefaultBranch, r.LatestTag()})113 key := fmt.Sprintf("%x", sha256.Sum256(h))114 if b.st.next == nil { // -once mode: no previous build115 return false116 }117 b.st.next[r.Name] = key118 if b.st.prev == "" || b.st.keys[r.Name] != key {119 return false120 }121 for _, d := range dirs {122 src := filepath.Join(b.st.prev, r.Name, d)123 if _, err := os.Stat(src); os.IsNotExist(err) {124 continue125 }126 if err := linkTree(src, filepath.Join(dir, r.Name, d)); err != nil {127 b.Log.Warn("reuse failed, re-rendering", "repo", r.Name, "err", err)128 for _, d := range dirs { // never write through links into the old build129 os.RemoveAll(filepath.Join(dir, r.Name, d))130 }131 return false132 }133 }134 return true135}136137// linkTree hard-links every file under src into dst. Builds are never138// modified once published, so sharing inodes between them is safe.139func linkTree(src, dst string) error {140 return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {141 if err != nil {142 return err143 }144 target := filepath.Join(dst, strings.TrimPrefix(p, src))145 if d.IsDir() {146 return os.MkdirAll(target, 0o755)147 }148 return os.Link(p, target)149 })150}
internal/build/loop_test.goadded
+86 −0
@@ -0,0 +1,86 @@1package build23import (4 "context"5 "os"6 "path/filepath"7 "syscall"8 "testing"9 "time"1011 "daum.dev/showcase/internal/gitea"12)1314func inode(t *testing.T, p string) uint64 {15 t.Helper()16 fi, err := os.Stat(p)17 if err != nil {18 t.Fatal(err)19 }20 return fi.Sys().(*syscall.Stat_t).Ino21}2223func builds(t *testing.T, b *Builder) []string {24 t.Helper()25 es, _ := os.ReadDir(b.siteDir())26 var names []string27 for _, e := range es {28 if e.Name() != "current" {29 names = append(names, e.Name())30 }31 }32 return names33}3435func TestBuildLoop(t *testing.T) {36 b := testBuilder(t)37 ctx := context.Background()38 if b.Ready() {39 t.Fatal("ready before the first build")40 }41 tick := 042 now := b.Now()43 b.Now = func() time.Time { tick++; return now.Add(time.Duration(tick) * time.Second) }4445 if err := b.BuildOnce(ctx); err != nil {46 t.Fatal(err)47 }48 if !b.Ready() {49 t.Fatal("not ready after a build")50 }51 blob := func() string { return filepath.Join(b.Current(), "repo-a/blob/go.mod.html") }52 first := inode(t, blob())5354 // unchanged HEAD and header: git pages are hard-linked, not re-rendered55 if err := b.BuildOnce(ctx); err != nil {56 t.Fatal(err)57 }58 if inode(t, blob()) != first {59 t.Error("blob page was re-rendered although nothing changed")60 }6162 // a changed key re-renders; only the current and previous builds remain63 b.st.keys["repo-a"] = "changed"64 if err := b.BuildOnce(ctx); err != nil {65 t.Fatal(err)66 }67 if inode(t, blob()) == first {68 t.Error("blob page was reused although the repo changed")69 }70 if n := builds(t, b); len(n) != 2 {71 t.Errorf("want 2 builds kept, got %v", n)72 }7374 // a failing build leaves the current one in place and no temp dir behind75 cur, _ := os.Readlink(b.Current())76 b.Gitea = gitea.New("http://127.0.0.1:1", "daniel")77 if err := b.BuildOnce(ctx); err == nil {78 t.Fatal("build against a dead Gitea succeeded")79 }80 if now, _ := os.Readlink(b.Current()); now != cur {81 t.Error("current changed after a failed build")82 }83 if n := builds(t, b); len(n) != 2 {84 t.Errorf("failed build left files behind: %v", n)85 }86}
internal/build/repo.go
+3 −0
@@ -146,6 +146,9 @@ func (b *Builder) renderRepo(ctx context.Context, rd *render.Renderer, dir strin146146 return err147147 }148148149 if b.reuse(r, dir, "tree", "blob", "raw") {150 return nil151 }149152 for _, e := range entries {150153 switch {151154 case e.Type == "tree":