Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/named-deploy

# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/forge.go
This commit is contained in:
2026-11-08 21:02:45 +11:00
4 changed files with 273 additions and 94 deletions
+77 -68
View File
@@ -51,7 +51,6 @@ type Deployer struct {
mu sync.Mutex
flights map[string]*flight
skips map[string]int
revived []string
counts map[string]int
Timings *slog.Logger
wtLocks sync.Map
@@ -215,7 +214,7 @@ func (d *Deployer) Sources() []*Source {
return out
}
// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC but unmarks what it swaps in.
// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC.
func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error {
ctx, end := d.phase(ctx, "run")
want := map[string]bool{}
@@ -225,7 +224,6 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
d.mu.Lock()
clear(d.skips)
clear(d.counts)
d.revived = nil
d.mu.Unlock()
found := map[string]bool{}
var errs []error
@@ -239,13 +237,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
errs = append(errs, fmt.Errorf("environment %s not found", e))
}
}
if len(only) == 0 {
if err := d.GC(ctx); err != nil {
errs = append(errs, err)
}
} else if err := d.unmark(d.revived); err != nil {
errs = append(errs, err)
}
errs = append(errs, d.gc(ctx, len(only) == 0))
d.mu.Lock()
for _, e := range slices.Sorted(maps.Keys(d.skips)) {
log.Printf("environment %s: %d types skipped", e, d.skips[e])
@@ -278,7 +270,8 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string]
names = append(names, b)
}
sort.Strings(names)
envs := map[string]envRef{}
claims := map[string][]string{}
exact := map[string]string{}
var errs []error
for _, b := range names {
if s.Ignored(b) {
@@ -292,14 +285,31 @@ func (d *Deployer) Environments(ctx context.Context, s *Source, want map[string]
errs = append(errs, err)
continue
}
if corrected && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", b, name)
if !corrected {
exact[name] = b
}
if _, dup := envs[name]; dup {
errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name))
claims[name] = append(claims[name], b)
}
envs := map[string]envRef{}
for _, name := range slices.Sorted(maps.Keys(claims)) {
bs := claims[name]
win, isExact := exact[name]
if !isExact && len(bs) == 1 {
win = bs[0]
}
if win == "" {
errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name))
continue
}
envs[name] = envRef{b, all[b]}
for _, b := range bs {
if b != win {
errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name))
}
}
if !isExact && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", win, name)
}
envs[name] = envRef{win, all[win]}
}
return envs, errs
}
@@ -432,12 +442,6 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en
if err != nil {
return err
}
d.mu.Lock()
d.revived = append(d.revived, target)
for _, m := range mods {
d.revived = append(d.revived, m.dir)
}
d.mu.Unlock()
outcome = "updated"
if cur == "" {
outcome = "created"
@@ -854,27 +858,49 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri
}
}
func (d *Deployer) GC(ctx context.Context) error {
func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) }
// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed.
func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) {
start := time.Now()
g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}}
statePath := d.path(gcStateFile)
if b, err := os.ReadFile(statePath); err == nil {
if err := json.Unmarshal(b, &g.marks); err != nil {
return fmt.Errorf("gc: %s: %w", statePath, err)
g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}}
defer func() {
for p := range g.marks {
if !g.seen[p] {
delete(g.marks, p)
}
}
} else if !os.IsNotExist(err) {
return err
}
err = errors.Join(append(g.errs, d.saveMarks(g.marks))...)
d.emit(ctx, "gc.mark", time.Since(start)-g.delDur, "marked", g.marked, "pending", len(g.marks))
d.emit(ctx, "gc.delete", g.delDur, "removed", g.removed)
}()
liveEnv := map[string]bool{}
var ok []*Source
for _, s := range d.Sources() {
live, err := d.Live(s)
if err != nil {
return fmt.Errorf("gc: %w", err)
g.errs = append(g.errs, fmt.Errorf("gc: %w", err))
continue
}
ok = append(ok, s)
for _, t := range live {
liveEnv[t] = true
}
}
if !sweep {
liveMod, err := d.moduleRefs(liveEnv)
if err != nil || len(g.errs) > 0 {
g.errs = append(g.errs, err)
return nil
}
for p := range g.marks {
g.seen[p] = !liveEnv[p] && !liveMod[p]
}
return nil
}
for _, s := range ok {
mirror := d.srcMirror(s)
g.sweep(mirror, d.srcWorktrees(s), liveEnv, func(p string) error {
if err := os.Remove(d.doneFile(p)); err != nil && !os.IsNotExist(err) {
@@ -889,7 +915,9 @@ func (d *Deployer) GC(ctx context.Context) error {
}
}
}
if len(ok) < len(d.cfg.Sources) {
return nil
}
liveMod, err := d.moduleRefs(liveEnv)
if err != nil {
g.errs = append(g.errs, err)
@@ -901,48 +929,29 @@ func (d *Deployer) GC(ctx context.Context) error {
}
g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) })
}
for p := range g.marks {
if !g.seen[p] {
delete(g.marks, p)
}
}
b, err := json.MarshalIndent(g.marks, "", " ")
if err == nil {
tmp := statePath + ".tmp"
if err = os.WriteFile(tmp, b, 0o644); err == nil {
err = os.Rename(tmp, statePath)
}
}
d.emit(ctx, "gc.mark", time.Since(start)-g.delDur, "marked", g.marked, "pending", len(g.marks))
d.emit(ctx, "gc.delete", g.delDur, "removed", g.removed)
return errors.Join(append(g.errs, err)...)
return nil
}
// unmark drops GC marks for paths a named deploy made live again, so they get a fresh grace period once unreferenced.
func (d *Deployer) unmark(paths []string) error {
statePath := d.path(gcStateFile)
b, err := os.ReadFile(statePath)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
// loadMarks treats an unreadable state file as empty, which only delays deletion.
func (d *Deployer) loadMarks() map[string]time.Time {
marks := map[string]time.Time{}
if err := json.Unmarshal(b, &marks); err != nil {
return fmt.Errorf("gc: %s: %w", statePath, err)
b, err := os.ReadFile(d.path(gcStateFile))
if err == nil {
err = json.Unmarshal(b, &marks)
}
n := len(marks)
for _, p := range paths {
delete(marks, p)
if err != nil && !os.IsNotExist(err) {
log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err)
marks = map[string]time.Time{}
}
if len(marks) == n {
return nil
}
if b, err = json.MarshalIndent(marks, "", " "); err != nil {
return marks
}
func (d *Deployer) saveMarks(marks map[string]time.Time) error {
b, err := json.MarshalIndent(marks, "", " ")
if err != nil {
return err
}
return writeAtomic(statePath, b)
return writeAtomic(d.path(gcStateFile), b)
}
// moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir.
+146 -19
View File
@@ -843,25 +843,6 @@ func TestNamedDeployTouchesOnlyNamed(t *testing.T) {
}
}
func TestNamedDeployRevivedWorktreeKeepsGrace(t *testing.T) {
f := newFixture(t)
a := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node a {}\n"})
f.mustDeploy(false)
wa := f.env("main")
commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"})
f.mustDeploy(false)
f.clock = f.clock.Add(11 * time.Minute)
gitT(t, f.control, "reset", "-q", "--hard", a)
if err := f.deploy(false, "main"); err != nil || f.env("main") != wa {
t.Fatalf("named deploy must revive wa: %v", err)
}
commit(t, f.control, map[string]string{"manifests/site.pp": "node c {}\n"})
f.mustDeploy(false)
if !exists(wa) {
t.Fatal("replaced worktree GC'd on a stale mark; grace skipped")
}
}
func TestTimingsPhases(t *testing.T) {
f := newFixture(t)
f.cfg.W10k.GenerateTypes = true
@@ -1167,3 +1148,149 @@ func TestDeployMarkerNameIsBranch(t *testing.T) {
t.Fatalf("marker name %q, want branch feat/x", m.Name)
}
}
func TestTargetedDeploySkipsGC(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
f.mustDeploy(false)
old := f.env("main")
commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"})
f.mustDeploy(false)
f.clock = f.clock.Add(time.Hour)
if err := f.deploy(false, "main"); err != nil {
t.Fatal(err)
}
if !exists(old) {
t.Fatalf("targeted deploy ran GC and removed %s", old)
}
}
func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) {
f := newFixture(t)
sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
f.mustDeploy(false)
w1 := f.env("main")
commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"})
f.mustDeploy(false)
f.clock = f.clock.Add(time.Hour)
gitT(t, f.control, "reset", "-q", "--hard", sha1)
if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 {
t.Fatalf("targeted deploy did not reuse %s: %v", w1, err)
}
commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"})
if err := f.deploy(false, "main"); err != nil {
t.Fatal(err)
}
f.mustDeploy(false)
if !exists(w1) {
t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace")
}
}
func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) {
root := t.TempDir()
s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")}
u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")}
cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}}
clock := time.Unix(1_700_000_000, 0)
gc := func() error {
d := New(cfg, 1, 10*time.Minute)
d.now = func() time.Time { return clock }
return d.GC(context.Background())
}
d := New(cfg, 1, 0)
old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur")
mkdirs(t, old, cur, s.Basedir, filepath.Dir(d.doneFile(old)))
for _, p := range []string{old, cur} {
if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil {
t.Fatal(err)
}
}
link := filepath.Join(s.Basedir, "develop")
if err := Swap(cur, link); err != nil {
t.Fatal(err)
}
if err := gc(); err != nil {
t.Fatal(err)
}
clock = clock.Add(time.Hour)
if err := Swap(old, link); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil {
t.Fatal(err)
}
if err := gc(); err == nil {
t.Fatal("want Live error")
}
if err := os.Remove(u.Basedir); err != nil {
t.Fatal(err)
}
if err := Swap(cur, link); err != nil {
t.Fatal(err)
}
_ = gc()
if !exists(old) {
t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return")
}
}
func TestGCCorruptStateTreatedAsEmpty(t *testing.T) {
root := t.TempDir()
s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")}
cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}}
d := New(cfg, 1, 10*time.Minute)
old := filepath.Join(d.srcWorktrees(s), "old")
mkdirs(t, old, s.Basedir)
state := d.path(gcStateFile)
if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil {
t.Fatal(err)
}
if err := d.GC(context.Background()); err != nil {
t.Fatalf("corrupt state wedged GC: %v", err)
}
b, err := os.ReadFile(state)
if err != nil {
t.Fatal(err)
}
var marks map[string]time.Time
if err := json.Unmarshal(b, &marks); err != nil {
t.Fatalf("state not rewritten: %v", err)
}
if _, ok := marks[old]; !ok || !exists(old) {
t.Fatal("unreferenced worktree must be freshly marked, not deleted")
}
}
func TestExactBranchWinsEnvName(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "feature_x")
legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "feature-x")
commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"})
err := f.deploy(false)
if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") {
t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit)
}
if err == nil || !strings.Contains(err.Error(), "feature-x") {
t.Fatalf("want collision error naming feature-x, got %v", err)
}
}
func TestCorrectedBranchCollisionSkipsAll(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "feature-x")
gitT(t, f.control, "branch", "feature.x")
err := f.deploy(false)
if exists(filepath.Join(f.basedir, "feature_x")) {
t.Fatal("colliding corrected branches must not deploy feature_x")
}
if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") {
t.Fatalf("want collision error naming both branches, got %v", err)
}
if f.env("main") == "" {
t.Fatal("collision must not block other envs")
}
}
+27 -5
View File
@@ -14,7 +14,11 @@ import (
"time"
)
const defaultForge = "https://forgeapi.puppet.com"
const (
defaultForge = "https://forgeapi.puppet.com"
maxForgeDownload = 100 << 20
maxForgeExtracted = 512 << 20
)
var httpClient = &http.Client{Timeout: 5 * time.Minute}
@@ -81,25 +85,43 @@ func forgeInstall(ctx context.Context, base, release, dir string) (time.Duration
if err != nil {
return 0, err
}
tr := &timedReader{r: body, d: time.Since(start)}
if err := extract(tr, tmp); err != nil {
tr := &timedReader{r: &capReader{r: body, n: maxForgeDownload}, d: time.Since(start)}
if err := extract(tr, tmp, maxForgeExtracted); err != nil {
_ = os.RemoveAll(tmp)
return tr.d, fmt.Errorf("%s: %w", release, err)
}
return tr.d, os.Rename(tmp, dir)
}
func extract(r io.Reader, dst string) error {
// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently.
type capReader struct {
r io.Reader
n int64
}
func (c *capReader) Read(p []byte) (int, error) {
if int64(len(p)) > c.n+1 {
p = p[:c.n+1]
}
n, err := c.r.Read(p)
if c.n -= int64(n); c.n < 0 {
return 0, fmt.Errorf("archive exceeds size cap")
}
return n, err
}
func extract(r io.Reader, dst string, limit int64) error {
gz, err := gzip.NewReader(r)
if err != nil {
return err
}
cr := &capReader{r: gz, n: limit}
root, err := os.OpenRoot(dst)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
tr := tar.NewReader(gz)
tr := tar.NewReader(cr)
for {
hdr, err := tr.Next()
if err == io.EOF {
+23 -2
View File
@@ -4,8 +4,10 @@ import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -58,7 +60,7 @@ func TestExtractStripsTopDir(t *testing.T) {
entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644},
entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700},
entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink},
)), dst)
)), dst, maxForgeExtracted)
if err != nil {
t.Fatal(err)
}
@@ -75,7 +77,7 @@ func TestExtractStripsTopDir(t *testing.T) {
func TestExtractRejectsTraversal(t *testing.T) {
dst := t.TempDir()
err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst)
err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst, maxForgeExtracted)
if err == nil {
t.Fatal("expected traversal error")
}
@@ -95,3 +97,22 @@ func TestForgeURL(t *testing.T) {
}
}
}
func TestExtractRejectsOversize(t *testing.T) {
big := entry{name: "m/a", body: strings.Repeat("x", 4096), mode: 0o644}
if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1024); err == nil {
t.Fatal("want extracted size cap error")
}
if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1<<20); err != nil {
t.Fatal(err)
}
}
func TestCapReaderErrorsAtCap(t *testing.T) {
if _, err := io.ReadAll(&capReader{r: strings.NewReader("abcdef"), n: 4}); err == nil {
t.Fatal("want cap error")
}
if b, err := io.ReadAll(&capReader{r: strings.NewReader("abc"), n: 4}); err != nil || string(b) != "abc" {
t.Fatalf("under cap: %q %v", b, err)
}
}