showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
loop.go
5.3 KB · 175 lines
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 // images caches container image details by manifest digest; they are24 // content-addressed, so they never go stale (see images.go)25 images map[string]ImagePlatform26}2728func (b *Builder) siteDir() string { return filepath.Join(b.Data, "site") }2930// Current is the directory the server serves from.31func (b *Builder) Current() string { return filepath.Join(b.siteDir(), "current") }3233// Ready reports whether a good build exists (possibly from an earlier run).34func (b *Builder) Ready() bool {35 _, err := os.Stat(filepath.Join(b.Current(), "index.html"))36 return err == nil37}3839// Run builds now and then every interval until ctx ends. Failures are logged40// and the last good build keeps being served.41func (b *Builder) Run(ctx context.Context, every time.Duration) {42 t := time.NewTicker(every)43 defer t.Stop()44 for {45 start := time.Now()46 if err := b.BuildOnce(ctx); err != nil {47 b.Log.Error("build failed", "err", err, "took", time.Since(start))48 } else {49 b.Log.Info("build done", "took", time.Since(start))50 }51 select {52 case <-ctx.Done():53 return54 case <-t.C:55 }56 }57}5859// BuildOnce renders a new build and publishes it atomically. It never runs60// concurrently with itself, and never publishes a partial build.61func (b *Builder) BuildOnce(ctx context.Context) error {62 b.st.mu.Lock()63 defer b.st.mu.Unlock()64 if err := os.MkdirAll(b.siteDir(), 0o755); err != nil {65 return err66 }67 if b.st.prev == "" { // after a restart: keep serving the old build until the swap68 if t, err := os.Readlink(b.Current()); err == nil {69 b.st.prev = filepath.Join(b.siteDir(), t)70 }71 }72 name := b.Now().UTC().Format("20060102T150405.000")73 tmp := filepath.Join(b.siteDir(), ".tmp-"+name)74 b.st.next = map[string]string{}75 if err := os.Mkdir(tmp, 0o755); err != nil {76 return err77 }78 if err := b.Render(ctx, tmp); err != nil {79 os.RemoveAll(tmp)80 return err81 }82 final := filepath.Join(b.siteDir(), name)83 if err := os.Rename(tmp, final); err != nil {84 return err85 }86 link := b.Current() + ".new"87 os.Remove(link)88 if err := os.Symlink(name, link); err != nil {89 return err90 }91 if err := os.Rename(link, b.Current()); err != nil { // atomic swap92 return err93 }94 b.prune(name, filepath.Base(b.st.prev))95 b.st.prev, b.st.keys = final, b.st.next96 return nil97}9899// prune removes every build except keep (and the previous one, so requests100// already reading it can finish) plus leftovers from crashed builds.101func (b *Builder) prune(keep ...string) {102 entries, _ := os.ReadDir(b.siteDir())103 for _, e := range entries {104 n := e.Name()105 if n == "current" || n == keep[0] || n == keep[1] {106 continue107 }108 os.RemoveAll(filepath.Join(b.siteDir(), n))109 }110}111112// reuse links r's git-derived pages (dirs) from the previous build when the113// repo's HEAD and header data are unchanged. It reports whether it did.114func (b *Builder) reuse(r *repo, dir string, dirs ...string) bool {115 // everything the shared repo header and tabs show116 h, _ := json.Marshal([]any{r.Head, r.Description, r.Website, r.Topics, r.Archived, r.DefaultBranch, r.LatestTag(),117 len(r.Branches), len(r.Tags), len(r.Releases), len(r.Pulls), len(r.Issues), r.PackageCount(), r.License, r.Avatar, r.Status, r.Sigs, b.ageKey(r)})118 key := fmt.Sprintf("%x", sha256.Sum256(h))119 if b.st.next == nil { // -once mode: no previous build120 return false121 }122 b.st.next[r.Name] = key123 if b.st.prev == "" || b.st.keys[r.Name] != key {124 return false125 }126 for _, d := range dirs {127 src := filepath.Join(b.st.prev, r.Name, d)128 if _, err := os.Stat(src); os.IsNotExist(err) {129 continue130 }131 if err := linkTree(src, filepath.Join(dir, r.Name, d)); err != nil {132 b.Log.Warn("reuse failed, re-rendering", "repo", r.Name, "err", err)133 for _, d := range dirs { // never write through links into the old build134 os.RemoveAll(filepath.Join(dir, r.Name, d))135 }136 return false137 }138 }139 return true140}141142// linkTree hard-links every file under src into dst. Builds are never143// modified once published, so sharing inodes between them is safe.144func linkTree(src, dst string) error {145 return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {146 if err != nil {147 return err148 }149 target := filepath.Join(dst, strings.TrimPrefix(p, src))150 if d.IsDir() {151 return os.MkdirAll(target, 0o755)152 }153 return os.Link(p, target)154 })155}156157// ageKey buckets the age of the newest commit like the "updated … ago" pill158// shows it past the first day (days, then weeks, months, years), so reused159// pages are rebuilt when that text or the live dot would change.160func (b *Builder) ageKey(r *repo) string {161 lc := r.LastCommit()162 if lc == nil {163 return ""164 }165 switch d := int(b.Now().Sub(lc.When).Hours() / 24); {166 case d < 7:167 return fmt.Sprintf("d%d", d)168 case d < 30:169 return fmt.Sprintf("w%d", d/7)170 case d < 365:171 return fmt.Sprintf("m%d", d/30)172 default:173 return fmt.Sprintf("y%d", d/365)174 }175}