Merge remote-tracking branch 'origin/benvin/timings' into benvin/timings
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful

# Conflicts:
#	internal/deploy/deploy.go
This commit is contained in:
2026-11-08 21:47:44 +11:00
3 changed files with 266 additions and 51 deletions
+106 -34
View File
@@ -222,12 +222,9 @@ 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.
func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error {
ctx, end := d.phase(ctx, "run")
want := map[string]bool{}
for _, e := range only {
want[e] = true
}
d.mu.Lock()
maps.DeleteFunc(d.flights, func(_ string, f *flight) bool {
select {
@@ -240,16 +237,21 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
clear(d.skips)
clear(d.counts)
d.mu.Unlock()
found := map[string]bool{}
var errs []error
var plans []*srcPlan
for _, s := range d.Sources() {
if err := d.deploySource(ctx, s, want, found, modules); err != nil {
p, err := d.planSource(ctx, s)
if err != nil {
d.count("failed")
errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err))
continue
}
plans = append(plans, p)
}
for e := range want {
if !found[e] {
errs = append(errs, fmt.Errorf("environment %s not found", e))
errs = append(errs, d.selectEnvs(plans, only)...)
for _, p := range plans {
if err := d.deploySource(ctx, p, modules); err != nil {
errs = append(errs, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
errs = append(errs, d.gc(ctx, len(only) == 0))
@@ -266,6 +268,68 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
return errors.Join(errs...)
}
// srcPlan is a source's resolved envs, the branches that got none and why, and the envs to build (nil = all).
type srcPlan struct {
s *Source
envs map[string]envRef
skipped map[string]error
want map[string]bool
}
// selectEnvs resolves args to envs as a full deploy would: env names in any source first, else raw branch names.
func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error {
if len(only) == 0 {
return nil
}
var errs []error
for _, p := range plans {
p.want = map[string]bool{}
}
for _, a := range only {
isEnv := slices.ContainsFunc(plans, func(p *srcPlan) bool { _, ok := p.envs[a]; return ok })
hit := false
var why []error
for _, p := range plans {
if isEnv {
if _, ok := p.envs[a]; ok {
p.want[a], hit = true, true
}
continue
}
for name, ref := range p.envs {
if ref.branch == a {
p.want[name], hit = true, true
}
}
for _, err := range p.skipErrs(func(b string) bool {
name, _, _ := p.s.EnvName(b)
return b == a || name == a
}) {
d.count("failed")
why = append(why, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
if !hit && len(why) == 0 {
why = append(why, fmt.Errorf("environment %s not found", a))
}
errs = append(errs, why...)
}
return errs
}
// skipErrs returns the distinct reasons, in branch order, for skipped branches match accepts.
func (p *srcPlan) skipErrs(match func(string) bool) []error {
var out []error
seen := map[error]bool{}
for _, b := range slices.Sorted(maps.Keys(p.skipped)) {
if err := p.skipped[b]; match(b) && !seen[err] {
seen[err] = true
out = append(out, err)
}
}
return out
}
func (d *Deployer) count(outcome string) {
d.mu.Lock()
d.counts[outcome]++
@@ -274,10 +338,11 @@ func (d *Deployer) count(outcome string) {
type envRef struct{ branch, sha string }
func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, []error) {
// Environments maps env name -> branch and sha, and each branch that gets no env to why.
func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, map[string]error, error) {
all, err := d.branches(ctx, d.srcMirror(s))
if err != nil {
return nil, []error{err}
return nil, nil, err
}
names := make([]string, 0, len(all))
for b := range all {
@@ -286,14 +351,14 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR
sort.Strings(names)
claims := map[string][]string{}
exact := map[string]string{}
var errs []error
skipped := map[string]error{}
for _, b := range names {
if s.Ignored(b) {
continue
}
name, corrected, err := s.EnvName(b)
if err != nil {
errs = append(errs, err)
skipped[b] = err
continue
}
if !corrected {
@@ -309,50 +374,57 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR
win = bs[0]
}
if win == "" {
errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name))
err := fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)
for _, b := range bs {
skipped[b] = err
}
continue
}
for _, b := range bs {
if b != win {
errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name))
skipped[b] = 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
return envs, skipped, nil
}
func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[string]bool, modules bool) error {
func (d *Deployer) planSource(ctx context.Context, s *Source) (*srcPlan, error) {
fctx, end := d.phase(ctx, "source.fetch", "source", s.Name)
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs)
end()
if err != nil {
d.count("failed")
return err
return nil, err
}
bctx, end := d.phase(ctx, "source.branches", "source", s.Name)
envs, errs := d.Environments(bctx, s)
envs, skipped, err := d.Environments(bctx, s)
end("envs", len(envs))
for range errs {
d.count("failed")
return &srcPlan{s: s, envs: envs, skipped: skipped}, err
}
func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) error {
s, full := p.s, p.want == nil
var errs []error
if full {
errs = p.skipErrs(func(string) bool { return true })
for range errs {
d.count("failed")
}
}
if envs == nil {
return errors.Join(errs...)
}
full := len(want) == 0
if err := os.MkdirAll(s.Basedir, 0o755); err != nil {
return err
return errors.Join(append(errs, err)...)
}
var mu sync.Mutex
var wg sync.WaitGroup
for name, ref := range envs {
if !full && !want[name] {
for _, name := range slices.Sorted(maps.Keys(p.envs)) {
ref := p.envs[name]
if !full && !p.want[name] {
continue
}
found[name] = true
if _, corrected, _ := s.EnvName(ref.branch); corrected && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", ref.branch, name)
}
wg.Add(1)
go func() {
defer wg.Done()
@@ -365,7 +437,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[
}
wg.Wait()
if full {
errs = append(errs, d.purge(s, envs))
errs = append(errs, d.purge(s, p.envs))
}
return errors.Join(errs...)
}
+126
View File
@@ -797,6 +797,132 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) {
}
}
func TestNamedDeployTouchesOnlyNamed(t *testing.T) {
f := newFixture(t)
old := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "gone")
commit(t, f.control, map[string]string{"manifests/site.pp": "node other {}\n"})
gitT(t, f.control, "branch", "gone2")
commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"})
gitT(t, f.control, "branch", "benvin/foo-bar")
f.mustDeploy(false)
gone, gone2 := f.env("gone"), f.env("gone2")
gitT(t, f.control, "branch", "-D", "gone", "gone2")
f.mustDeploy(false)
f.clock = f.clock.Add(11 * time.Minute)
marks := func() map[string]time.Time {
m := map[string]time.Time{}
if err := json.Unmarshal([]byte(readFileT(t, f.cache(gcStateFile))), &m); err != nil {
t.Fatal(err)
}
return m
}
before := marks()
if _, ok := before[gone2]; !ok {
t.Fatalf("gone2 must be marked: %v", before)
}
gitT(t, f.control, "branch", "-f", "benvin/foo-bar", old)
main := f.env("main")
if err := f.deploy(false, "benvin/foo-bar"); err != nil {
t.Fatal(err)
}
if f.env("benvin_foo_bar") != gone {
t.Fatal("a raw branch name deploys its sanitised env, reviving the matching worktree")
}
delete(before, gone)
if f.env("main") != main || !exists(gone2) || !maps.Equal(marks(), before) {
t.Fatalf("a named deploy must clear only the marks of what it revives: %v", marks())
}
sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"})
if err := f.deploy(false, "main"); err != nil || !strings.HasPrefix(filepath.Base(f.env("main")), sha+"-") {
t.Fatalf("env name deploys: %v", err)
}
if err := f.deploy(false, "main", "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") {
t.Fatalf("unknown env must error: %v", err)
}
if !exists(gone2) {
t.Fatal("named deploys never GC")
}
}
func TestNamedDeployCollisionLoserKeepsOut(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", "a_b")
win := commit(t, f.control, map[string]string{"manifests/site.pp": "node a {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "a-b")
commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"})
_ = f.deploy(false)
err := f.deploy(false, "a-b")
if !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of collision loser a-b took env a_b: %s", f.env("a_b"))
}
if err == nil || !strings.Contains(err.Error(), "a-b collides") {
t.Fatalf("want collision error for a-b, got %v", err)
}
if err := f.deploy(false, "a_b"); err != nil || !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of a_b must keep the full-deploy winner: %v", err)
}
}
func TestNamedDeployCorrectedCollisionSkipsAll(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "a-b")
gitT(t, f.control, "branch", "a.b")
for _, arg := range []string{"a.b", "a_b"} {
err := f.deploy(false, arg)
if exists(filepath.Join(f.basedir, "a_b")) {
t.Fatalf("deploy %s built a_b, which a full deploy skips", arg)
}
if err == nil || !strings.Contains(err.Error(), "a-b") || !strings.Contains(err.Error(), "a.b") {
t.Fatalf("deploy %s: want collision error naming both branches, got %v", arg, err)
}
}
}
func TestNamedDeployPrefixedSources(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "benvin/x")
pbase := filepath.Join(f.root, "code", "penvs")
p := &Source{Name: "p", Remote: f.control, Basedir: pbase, Prefix: "p", InvalidBranches: "correct_and_warn"}
f.cfg.Sources["p"] = p
penv := func(name string) string { return f.deployer().owned(p, filepath.Join(pbase, name)) }
var logs bytes.Buffer
log.SetOutput(&logs)
defer log.SetOutput(os.Stderr)
if err := f.deploy(false, "main"); err != nil || f.env("main") == "" {
t.Fatalf("deploy main: %v", err)
}
if strings.Contains(logs.String(), "benvin/x") {
t.Fatalf("named deploy warned about a branch it did not deploy:\n%s", logs.String())
}
if penv("p_main") != "" {
t.Fatal("env name main also deployed branch main of source p as p_main")
}
if err := f.deploy(false, "p_main"); err != nil || penv("p_main") == "" {
t.Fatalf("deploy p_main: %v", err)
}
if err := f.deploy(false, "benvin/x"); err != nil || f.env("benvin_x") == "" || penv("p_benvin_x") == "" {
t.Fatalf("raw branch benvin/x must deploy in every source: %v", err)
}
}
func TestNamedDeployIgnoresUnrelatedInvalid(t *testing.T) {
f := newFixture(t)
f.cfg.Sources["unkin"].InvalidBranches = "error"
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "bad-name")
if err := f.deploy(false, "main"); err != nil {
t.Fatalf("unrelated invalid branch failed named deploy: %v", err)
}
if err := f.deploy(false, "bad-name"); err == nil || !strings.Contains(err.Error(), "not a valid environment name") {
t.Fatalf("named invalid branch must error: %v", err)
}
}
func timingLines(s string) []map[string]string {
var out []map[string]string
for line := range strings.Lines(s) {
+34 -17
View File
@@ -4,10 +4,11 @@ import (
"context"
"fmt"
"log/slog"
"maps"
"os"
"os/signal"
"path/filepath"
"sort"
"slices"
"strings"
"syscall"
"time"
@@ -50,6 +51,24 @@ func rootCmd() *cobra.Command {
}
return d, nil
}
live := func() ([][3]string, error) {
d, err := load()
if err != nil {
return nil, err
}
var rows [][3]string
for _, s := range d.Sources() {
live, err := d.Live(s)
if err != nil {
return nil, err
}
for _, e := range slices.Sorted(maps.Keys(live)) {
sha, _, _ := strings.Cut(filepath.Base(live[e]), "-")
rows = append(rows, [3]string{s.Name, e, sha})
}
}
return rows, nil
}
locked := func(fn func(*deploy.Deployer) error) error {
d, err := load()
if err != nil {
@@ -77,10 +96,20 @@ func rootCmd() *cobra.Command {
var modules bool
deployCmd := &cobra.Command{
Use: "deploy [env...]",
Short: "Deploy all environments, or only the named ones",
Short: "Deploy all environments, or only the named ones (env or branch names)",
RunE: func(cmd *cobra.Command, args []string) error {
return locked(func(d *deploy.Deployer) error { return d.Deploy(cmd.Context(), args, modules) })
},
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
rows, _ := live()
var envs []string
for _, r := range rows {
if !slices.Contains(args, r[1]) && !slices.Contains(envs, r[1]) {
envs = append(envs, r[1])
}
}
return envs, cobra.ShellCompDirectiveNoFileComp
},
}
deployCmd.Flags().BoolVarP(&modules, "modules", "m", false, "re-resolve Puppetfile modules for unchanged environments")
@@ -89,24 +118,12 @@ func rootCmd() *cobra.Command {
Short: "List deployed environments",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
d, err := load()
rows, err := live()
if err != nil {
return err
}
for _, s := range d.Sources() {
live, err := d.Live(s)
if err != nil {
return err
}
envs := make([]string, 0, len(live))
for e := range live {
envs = append(envs, e)
}
sort.Strings(envs)
for _, e := range envs {
sha, _, _ := strings.Cut(filepath.Base(live[e]), "-")
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", s.Name, e, sha)
}
for _, r := range rows {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", r[0], r[1], r[2])
}
return nil
},