gunk-dev/the-valley

main.go

source005ffb79321fmain's published tip history
39.6 KiB
1// valley-restacker rebases ready changes onto main when main moves under
2// them, as its own principal, so their evidence stays fresh without their
3// owners rebasing and approving again by hand.
4//
5// `valley-restacker run` reconciles at its start and then every
6// --interval, 15 seconds by default, until it is stopped. Each
7// reconciliation is one write pass. `valley-restacker once` is one write
8// pass on its own.
9//
10// A write pass first finishes the journal of earlier operations, if the
11// state directory holds one (publish.go). It then reads one snapshot of
12// origin, plans every family, builds the writes it would make for each
13// family it would restack or hold (build.go), adds them to the journal,
14// and makes them the way recovery would after a crash: the branch push,
15// then the versions, then the reports, reading origin again between each
16// (recover.go). A family the journal still holds, such as one whose
17// versions a request has paused, stays there, and each family that
18// shares a change or a branch with it waits: the pass builds nothing for
19// it. So does each family that shares a change or a branch with another
20// family the pass would build for, as two changes that name one branch
21// do (overlapping). Every other family is planned as usual.
22//
23// `valley-restacker once --report-only` reads one snapshot of origin and
24// says which families it would restack, which it would hold and why, and
25// what capacity allows. For each family it would restack or hold, it
26// builds every write a pass would make, in its scratch repository, and
27// shows them: the one branch push, each change's next version and each
28// recorded change's report. It decides the journal of earlier
29// operations, if the state directory holds one, as recovery would. It
30// pushes nothing, and writes no journal.
31//
32// It talks to origin only over git, as a client, from a scratch repository
33// under its state directory. Hooks and external filters are off there:
34// the scratch repository's hooks path is /dev/null, and git reads neither
35// the system's nor the user's configuration, nor any the environment
36// injects, so no filter driver is defined. No git variable that points git
37// at another repository, program or configuration reaches anything a pass
38// runs (passes). A service that needs ssh settings passes them in
39// GIT_SSH_COMMAND. The scratch repository commits under the identity its
40// flags give, and never under one inherited from the environment, whether
41// as an identity variable or as configuration.
42//
43// A pass holds a lock on its state directory from start to end, so a
44// second pass on the same directory fails while one runs; run holds it
45// for as long as it runs. The directory belongs to one repository, target
46// and principal, the first a pass used it for, and a pass for any other
47// is refused. Every git, cue and attest a pass runs is killed, with what
48// it started, once the pass's --timeout passes. A pass whose output
49// nobody reads ends then too, and lets go of the lock. A message of its
50// own that nobody reads, such as the error it ends with, is given up on
51// after a few seconds.
52package main
53
54import (
55 "bytes"
56 "context"
57 "encoding/json"
58 "errors"
59 "flag"
60 "fmt"
61 "io"
62 "os"
63 "os/exec"
64 "os/signal"
65 "path/filepath"
66 "sort"
67 "strings"
68 "syscall"
69 "time"
70
71 "the-valley/change"
72 "the-valley/composed"
73 "the-valley/note"
74 "the-valley/rebase"
75)
76
77const usage = `valley-restacker: rebase ready changes onto main when main moves.
78
79usage: valley-restacker run [--interval DURATION] [flags]
80 valley-restacker once [--report-only] [flags]
81
82 run reconcile at once and then every --interval until stopped: each
83 reconciliation is one write pass. A pass that fails is said on
84 stderr, and the next waits twice as long as the one before, up to
85 5 minutes, until a pass succeeds
86 once one write pass: finish the journal of earlier operations, if the
87 state directory holds one; then plan every family, add the writes
88 for each family to restack or hold to the journal, and push them:
89 the branch push, then each change's next version, then each
90 change's report, reading origin again before each. A family the
91 journal still holds, such as one a request has paused, stays
92 there, and each family that shares a change or a branch with it
93 waits. So do two families that share a change or a branch with
94 each other
95 once --report-only
96 read one snapshot of origin and print what a pass would do: each
97 family, restack or hold with the reason, its capacity, the
98 integration requests it considered, and the writes a pass would
99 make for it, built in the scratch repository and not pushed: the
100 branch push, each change's next version, and each change's
101 report. If the state directory holds a journal, print what
102 recovery decides of each write it names.
103 Pushes nothing, and writes no journal.
104
105flags:
106 --repo URL origin: the repository the restacker serves (required)
107 --target NAME the target changes are rebased onto (only main)
108 --state DIR where the scratch repository lives (required). A pass
109 locks it, and it belongs to the first repository,
110 target and principal a pass used it for
111 --principal NAME the principal the restacker pushes as (required)
112 --commit-name NAME the name the restacker commits under (default: the
113 principal)
114 --commit-email EMAIL the email it commits under
115 (default: restacker@the-valley.invalid)
116 --interval DURATION run: how long to wait after one pass before the next
117 (default 15s)
118 --timeout DURATION the longest a pass may run, writing its output
119 included; what it runs is killed then (default 10m)
120 --known-signers FILE verifier keys, for landings proved by integrator evidence
121 --integrator-name N the name the integrator signs under
122 --signer-projects F the signer projects file the integrator reads; while
123 it names the --integrator-name, no landing is proved
124 by integrator evidence. A file that does not read
125 stops the pass
126 --attest PATH the attest helper that checks a note (default: attest on PATH)
127 --instance-repo URL the repository carrying the group's floor
128 --instance-ref REF the ref whose tip carries the floor, a full ref name
129 read by that exact name (refs/heads/main)
130 --instance-policy DIR the floor's directory in that tip (policy/instance)
131 --instance DIR a materialized floor, for a host that serves none
132 --project-policy DIR the project layer, in the target tip (policy/project)
133 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
134 --json print each pass as JSON
135`
136
137func main() {
138 if len(os.Args) < 2 {
139 say(os.Stderr, usage)
140 os.Exit(2)
141 }
142 switch os.Args[1] {
143 case "once", "run":
144 // An interrupt or a stop ends the pass as its timeout does: what it
145 // runs is killed, and the lock on its state is let go. It ends run
146 // between passes too.
147 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
148 command := once
149 if os.Args[1] == "run" {
150 command = loop
151 }
152 err := command(ctx, os.Args[2:], os.Stdout, os.Stderr)
153 stop()
154 if err != nil {
155 say(os.Stderr, fmt.Sprintf("valley-restacker: %v\n", err))
156 os.Exit(1)
157 }
158 case "help", "-h", "--help":
159 say(os.Stdout, usage)
160 default:
161 say(os.Stderr, fmt.Sprintf("valley-restacker: unknown command %q\n\n%s", os.Args[1], usage))
162 os.Exit(2)
163 }
164}
165
166// sayBound is the longest the process waits to write a message of its
167// own, such as the error it ends with.
168const sayBound = 5 * time.Second
169
170// say writes a message of the process's own, and gives up after sayBound.
171// A stderr nobody reads would otherwise hold the process after its pass
172// has ended and let go of its lock. The write given up on ends with the
173// process.
174func say(w io.Writer, message string) {
175 ctx, cancel := context.WithTimeout(context.Background(), sayBound)
176 defer cancel()
177 _ = writeOut(ctx, w, []byte(message))
178}
179
180// config is a pass's configuration, from flags.
181type config struct {
182 repo, target, state, principal string
183 commitName, commitEmail string
184 timeout, interval time.Duration
185 verify rebase.Verifier
186 floor composed.Floor
187 instanceRepo, projectPolicy string
188 schema, cue string
189 json bool
190}
191
192// defaultEmail is the email the restacker commits under unless
193// --commit-email names another. The .invalid domain is reserved, so the
194// address names no mailbox, as the integrator's does not.
195const defaultEmail = "restacker@the-valley.invalid"
196
197// maxBackoff is the longest run waits after a pass that failed.
198const maxBackoff = 5 * time.Minute
199
200// parse reads a command's flags into a configuration. --report-only is
201// once's, and --interval is run's.
202func parse(name string, args []string, errOut io.Writer) (c config, reportOnly bool, err error) {
203 fs := flag.NewFlagSet("valley-restacker "+name, flag.ContinueOnError)
204 fs.SetOutput(io.Discard)
205 fs.Usage = func() { say(errOut, usage) }
206 var only *bool
207 if name == "once" {
208 only = fs.Bool("report-only", false, "")
209 } else {
210 fs.DurationVar(&c.interval, "interval", 15*time.Second, "")
211 }
212 fs.StringVar(&c.repo, "repo", "", "")
213 fs.StringVar(&c.target, "target", rebase.Target, "")
214 fs.StringVar(&c.state, "state", "", "")
215 fs.StringVar(&c.principal, "principal", "", "")
216 fs.StringVar(&c.commitName, "commit-name", "", "")
217 fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "")
218 fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "")
219 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
220 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
221 fs.StringVar(&c.verify.Attest, "attest", "", "")
222 signerProjects := fs.String("signer-projects", "", "")
223 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
224 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
225 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
226 fs.StringVar(&c.floor.Path, "instance", "", "")
227 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
228 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
229 fs.BoolVar(&c.json, "json", false, "")
230 if err := fs.Parse(args); err != nil {
231 return c, false, err
232 }
233 if only != nil {
234 reportOnly = *only
235 }
236 switch {
237 case fs.NArg() > 0:
238 return c, false, fmt.Errorf("unexpected argument %q", fs.Arg(0))
239 case c.target != rebase.Target:
240 return c, false, fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
241 case name == "run" && c.interval <= 0:
242 return c, false, fmt.Errorf("--interval %v: run waits some time between passes", c.interval)
243 }
244 for _, f := range []struct{ flag, value string }{
245 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
246 } {
247 if f.value == "" {
248 return c, false, fmt.Errorf("%s is required", f.flag)
249 }
250 }
251 if !change.ValidPrincipal(c.principal) {
252 return c, false, fmt.Errorf("--principal %q is not a principal", c.principal)
253 }
254 if c.commitName == "" {
255 c.commitName = c.principal
256 }
257 if err := checkIdentity(c.commitName, c.commitEmail); err != nil {
258 return c, false, err
259 }
260 if c.timeout <= 0 {
261 return c, false, fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout)
262 }
263 // The floor comes from the instance repository's tip, or from a
264 // directory on disk, and never from both, as for the integrator.
265 if (c.instanceRepo == "") == (c.floor.Path == "") {
266 return c, false, errors.New("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory")
267 }
268 if c.instanceRepo != "" && !strings.HasPrefix(c.floor.Ref, "refs/") {
269 return c, false, fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", c.floor.Ref)
270 }
271 if c.verify.Attest == "" {
272 c.verify.Attest, _ = exec.LookPath("attest")
273 }
274 if *signerProjects != "" {
275 data, err := os.ReadFile(*signerProjects)
276 if err != nil {
277 return c, false, fmt.Errorf("--signer-projects: %w", err)
278 }
279 if c.verify.SignerProjects, err = note.ParseSignerProjects(data); err != nil {
280 return c, false, fmt.Errorf("--signer-projects %s does not read: %w", *signerProjects, err)
281 }
282 }
283 if c.cue, err = exec.LookPath("cue"); err != nil {
284 return c, false, errors.New("cue is not on the path; the restacker composes the policy with it")
285 }
286 return c, reportOnly, nil
287}
288
289// once is one pass, a write pass unless --report-only says otherwise.
290func once(ctx context.Context, args []string, out, errOut io.Writer) error {
291 // What the pass runs inherits no git variable that points git
292 // elsewhere or gives it configuration (passes).
293 controlEnvironment()
294 c, reportOnly, err := parse("once", args, errOut)
295 if err != nil {
296 return err
297 }
298 release, err := lockState(c.state)
299 if err != nil {
300 return err
301 }
302 defer release()
303 if err := bindState(c.state, c.binding()); err != nil {
304 return err
305 }
306 _, err = pass(ctx, c, reportOnly, out, errOut, false)
307 return err
308}
309
310// loop is run: a write pass at once, and another every interval after
311// the last one ended, until ctx is done. It holds the lock on its state
312// for as long as it runs. A pass that fails is said, and the wait before
313// the next doubles, up to maxBackoff, until a pass succeeds. A pass that
314// pushed nothing and leaves no journal open prints nothing.
315func loop(ctx context.Context, args []string, out, errOut io.Writer) error {
316 controlEnvironment()
317 c, _, err := parse("run", args, errOut)
318 if err != nil {
319 return err
320 }
321 release, err := lockState(c.state)
322 if err != nil {
323 return err
324 }
325 defer release()
326 if err := bindState(c.state, c.binding()); err != nil {
327 return err
328 }
329 failures := 0
330 for {
331 _, err := pass(ctx, c, false, out, errOut, true)
332 if ctx.Err() != nil {
333 return nil
334 }
335 wait := c.interval
336 if err != nil {
337 failures++
338 wait = backoff(c.interval, failures)
339 say(errOut, fmt.Sprintf("valley-restacker: the pass failed, and the next starts in %v: %v\n", wait, err))
340 } else {
341 failures = 0
342 }
343 select {
344 case <-ctx.Done():
345 return nil
346 case <-time.After(wait):
347 }
348 }
349}
350
351// backoff is how long run waits after the given number of passes in a row
352// have failed: twice as long for each, from the interval, up to
353// maxBackoff.
354func backoff(interval time.Duration, failures int) time.Duration {
355 wait := interval
356 for i := 0; i < failures && wait < maxBackoff; i++ {
357 wait *= 2
358 }
359 return min(wait, maxBackoff)
360}
361
362// pass runs one pass under its timeout and prints it: the plan and what
363// it pushed, or, when quiet, only what it pushed and a journal it leaves
364// open.
365func pass(ctx context.Context, c config, reportOnly bool, out, errOut io.Writer, quiet bool) (*Plan, error) {
366 ctx, cancel := context.WithTimeout(ctx, c.timeout)
367 defer cancel()
368 g, err := scratchRepo(ctx, c)
369 if err != nil {
370 return nil, timedOut(ctx, c, err)
371 }
372 g.Stderr = errOut
373 var p *Plan
374 if reportOnly {
375 p, err = planOnce(ctx, g, c)
376 } else {
377 p, err = writeOnce(ctx, g, c)
378 }
379 if err != nil {
380 return p, timedOut(ctx, c, err)
381 }
382 if quiet && len(p.Actions) == 0 && p.Pending == nil {
383 return p, nil
384 }
385 var text bytes.Buffer
386 switch {
387 case c.json:
388 enc := json.NewEncoder(&text)
389 enc.SetIndent("", " ")
390 if err := enc.Encode(p); err != nil {
391 return p, err
392 }
393 case quiet:
394 printPublished(&text, p)
395 default:
396 printPlan(&text, p)
397 }
398 if err := writeOut(ctx, out, text.Bytes()); err != nil {
399 return p, timedOut(ctx, c, err)
400 }
401 return p, nil
402}
403
404// writeOut writes data to out, and gives up once ctx is done. A reader
405// that stops reading holds the write, and would otherwise hold the pass,
406// and the lock on its state, past its --timeout. The write given up on
407// ends with the process.
408func writeOut(ctx context.Context, out io.Writer, data []byte) error {
409 done := make(chan error, 1)
410 go func() {
411 _, err := out.Write(data)
412 done <- err
413 }()
414 select {
415 case err := <-done:
416 return err
417 case <-ctx.Done():
418 return fmt.Errorf("the plan was not written: %w", ctx.Err())
419 }
420}
421
422// timedOut says so when a pass failed because it ran past its timeout.
423func timedOut(ctx context.Context, c config, err error) error {
424 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
425 return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err)
426 }
427 return err
428}
429
430// checkIdentity refuses a name or an email git cannot commit under: an
431// empty one, or one with a control character or an angle bracket, which
432// would end the name or the email early in a commit's header.
433func checkIdentity(name, email string) error {
434 for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} {
435 if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") ||
436 strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
437 return fmt.Errorf("%s %q: a commit's name and email are not empty and hold no angle bracket or control character", f.flag, f.value)
438 }
439 }
440 return nil
441}
442
443// What a pass passes on to the programs it runs. A git variable can point
444// git at another repository (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR,
445// GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES,
446// GIT_NAMESPACE, GIT_GRAFT_FILE, GIT_REPLACE_REF_BASE), at other programs
447// (GIT_EXEC_PATH, GIT_TEMPLATE_DIR), at other attributes (GIT_ATTR_SOURCE)
448// or at another format (GIT_DEFAULT_HASH). It can inject configuration
449// that beats the repository's own: GIT_CONFIG_COUNT with GIT_CONFIG_KEY_<n>
450// and GIT_CONFIG_VALUE_<n>, and GIT_CONFIG_PARAMETERS, so an inherited
451// author.name would beat user.name and an inherited core.hooksPath would
452// turn hooks back on. The other GIT_CONFIG* variables name configuration
453// files. And GIT_AUTHOR_*, GIT_COMMITTER_* and EMAIL give an identity
454// ahead of the configuration. So a pass passes on no GIT_* variable but
455// the ones that say how to reach origin over ssh, and no EMAIL. It drops
456// them from its own environment as it starts (controlEnvironment), so
457// cue, attest and the git that composes the policy run without them too.
458var passedOn = map[string]bool{"GIT_SSH": true, "GIT_SSH_COMMAND": true, "GIT_SSH_VARIANT": true}
459
460// passes reports whether a pass passes on the environment variable named.
461func passes(name string) bool {
462 switch {
463 case name == "EMAIL":
464 return false
465 case strings.HasPrefix(name, "GIT_"):
466 return passedOn[name]
467 }
468 return true
469}
470
471// gitSettings are what a pass sets for every git it runs, scratch
472// repository or not: no system or user configuration, no system
473// attributes, and no question asked at a terminal.
474var gitSettings = [][2]string{
475 {"GIT_CONFIG_NOSYSTEM", "1"},
476 {"GIT_CONFIG_GLOBAL", "/dev/null"},
477 {"GIT_ATTR_NOSYSTEM", "1"},
478 {"GIT_TERMINAL_PROMPT", "0"},
479}
480
481// controlEnvironment leaves the process's own environment holding only
482// what a pass passes on, and gitSettings.
483func controlEnvironment() {
484 for _, kv := range os.Environ() {
485 if name, _, _ := strings.Cut(kv, "="); !passes(name) {
486 os.Unsetenv(name)
487 }
488 }
489 for _, kv := range gitSettings {
490 os.Setenv(kv[0], kv[1])
491 }
492}
493
494// scratchRepo makes, or reuses, the repository a pass reads origin into,
495// and returns git run in it with hooks and configured filters off,
496// committing under the restacker's identity. git there reads no
497// configuration but the repository's, and is given its author and
498// committer explicitly. A commit it rebases keeps its own author: a
499// rebase takes the author from the commit it picks. git there is
500// unattended: it never asks a question, and every git it runs is killed
501// whole once ctx is done.
502//
503// The repository has a work tree, though nothing is ever checked out in
504// it: attest, which digests a version's tree and verifies the
505// integrator's transfer statements, reads only a repository with a work
506// tree.
507func scratchRepo(ctx context.Context, c config) (rebase.Git, error) {
508 dir := filepath.Join(c.state, "scratch")
509 var env []string
510 for _, kv := range os.Environ() {
511 if name, _, _ := strings.Cut(kv, "="); passes(name) {
512 env = append(env, kv)
513 }
514 }
515 for _, kv := range gitSettings {
516 env = append(env, kv[0]+"="+kv[1])
517 }
518 env = append(env,
519 "GIT_AUTHOR_NAME="+c.commitName,
520 "GIT_AUTHOR_EMAIL="+c.commitEmail,
521 "GIT_COMMITTER_NAME="+c.commitName,
522 "GIT_COMMITTER_EMAIL="+c.commitEmail,
523 )
524 g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr, Unattended: true}
525 if _, err := os.Stat(filepath.Join(dir, ".git", "HEAD")); err != nil {
526 if err := os.MkdirAll(dir, 0o700); err != nil {
527 return g, err
528 }
529 if err := run(ctx, g, "init", "--quiet"); err != nil {
530 return g, err
531 }
532 }
533 // user.useConfigOnly stops git guessing an identity from the host's
534 // name and the user's account. core.attributesFile is set, since git
535 // otherwise reads the user's own attributes file under
536 // XDG_CONFIG_HOME or HOME whatever configuration it reads, and an
537 // attribute such as merge=union there would change how a rebase
538 // merges. core.fsync makes each object and ref a pass writes durable
539 // before git reports it written, as a journal of writes relies on. The
540 // state directory is bound to one repository (bindState), so origin's
541 // URL is the same every pass.
542 for _, kv := range [][2]string{
543 {"core.hooksPath", "/dev/null"},
544 {"core.fsmonitor", "false"},
545 {"core.attributesFile", "/dev/null"},
546 {"core.fsync", "objects,reference"},
547 {"user.name", c.commitName},
548 {"user.email", c.commitEmail},
549 {"user.useConfigOnly", "true"},
550 {"remote.origin.url", c.repo},
551 } {
552 if err := run(ctx, g, "config", kv[0], kv[1]); err != nil {
553 return g, err
554 }
555 }
556 return g, nil
557}
558
559func run(ctx context.Context, g rebase.Git, args ...string) error {
560 _, err := gitOut(ctx, g, args...)
561 return err
562}
563
564// gitOut runs git as the rebase engine runs it (rebase.Git.Command): killed
565// with what it started once ctx is done, and with the wait for its output
566// bounded.
567func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) {
568 cmd := g.Command(ctx, args...)
569 var stderr strings.Builder
570 cmd.Stderr = &stderr
571 b, err := cmd.Output()
572 switch {
573 case ctx.Err() != nil:
574 return "", fmt.Errorf("git %s did not finish: %w", strings.Join(args, " "), ctx.Err())
575 case err != nil && !errors.Is(err, exec.ErrWaitDelay):
576 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
577 }
578 return string(b), nil
579}
580
581// ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a
582// question git could not answer.
583func ancestry(ctx context.Context, g rebase.Git) Ancestry {
584 return func(a, b string) (bool, error) {
585 err := g.Command(ctx, "merge-base", "--is-ancestor", a, b).Run()
586 var exit *exec.ExitError
587 switch {
588 case err == nil || errors.Is(err, exec.ErrWaitDelay):
589 return true, nil
590 case errors.As(err, &exit) && exit.ExitCode() == 1:
591 return false, nil
592 }
593 return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b))
594 }
595}
596
597// incoming reads, once for each head asked about, the commits it reaches
598// that tip does not. A head that is not a commit, or is missing, is an
599// error, asked about again as the same error.
600func incoming(ctx context.Context, g rebase.Git, tip string) Incoming {
601 type read struct {
602 commits map[string]bool
603 err error
604 }
605 seen := map[string]read{}
606 return func(head string) (map[string]bool, error) {
607 if r, ok := seen[head]; ok {
608 return r.commits, r.err
609 }
610 var r read
611 out, err := gitOut(ctx, g, "rev-list", head+"^{commit}", "--not", tip)
612 if err != nil {
613 r.err = fmt.Errorf("could not read the commits %s would bring to %s", short(head), rebase.Target)
614 } else {
615 r.commits = map[string]bool{}
616 for _, c := range strings.Fields(out) {
617 r.commits[c] = true
618 }
619 }
620 if ctx.Err() == nil {
621 seen[head] = r
622 }
623 return r.commits, r.err
624 }
625}
626
627// policyCap composes the policy at the target tip and reads the cap on
628// automatic versions: the floor from the instance repository's tip, read
629// over git into the scratch repository, or from --instance; the project
630// layer from the tip.
631func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) {
632 floor := c.floor
633 if c.instanceRepo != "" {
634 out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref)
635 if ctx.Err() != nil {
636 return 0, err
637 }
638 // ls-remote matches its pattern against the tail of each name,
639 // so it lists refs/heads/refs/heads/main for refs/heads/main, a
640 // branch a pusher can make. Only the ref of that exact name counts.
641 var oid string
642 for _, line := range strings.Split(out, "\n") {
643 if id, name, ok := strings.Cut(line, "\t"); ok && name == floor.Ref {
644 oid = id
645 }
646 }
647 if err != nil || !rebase.IsObjectID(oid) {
648 return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless)
649 }
650 if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil {
651 return 0, err
652 }
653 floor.Repo, floor.Ref = g.Dir, oid
654 }
655 instance, done, err := floor.Open(ctx, "valley-restacker-floor")
656 if err != nil {
657 return 0, err
658 }
659 defer done()
660 project, _, doneProject, err := composed.Project(ctx, g.Dir, tip, c.projectPolicy, "valley-restacker-project")
661 if err != nil {
662 return 0, err
663 }
664 defer doneProject()
665 pol, err := composed.Compose(ctx, c.cue, c.schema, instance, project)
666 if err != nil {
667 return 0, err
668 }
669 return CapOf(pol.MaxAutomaticVersions)
670}
671
672// planOnce reads one snapshot and the cap at its tip, decides the journal
673// in the state directory if there is one, plans every family, and builds
674// the writes a pass would make. It pushes nothing, writes no journal, and
675// lets go of what it prepared.
676func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
677 s, p, err := planned(ctx, g, c)
678 if err != nil {
679 return nil, err
680 }
681 // --report-only: what is built is shown, and neither kept nor pushed.
682 out, err := build(ctx, g, s, p, c.binding(), p.Operation)
683 if err != nil {
684 return nil, err
685 }
686 out.releasePrepared(ctx, g)
687 return p, nil
688}
689
690// planned reads one snapshot and the cap at its tip, and plans it.
691func planned(ctx context.Context, g rebase.Git, c config) (*rebase.Snapshot, *Plan, error) {
692 s, err := rebase.ReadSnapshot(ctx, g, c.verify)
693 if err != nil {
694 return nil, nil, err
695 }
696 if s.Tip == "" {
697 return nil, nil, fmt.Errorf("origin has no %s", rebase.Target)
698 }
699 cap, err := policyCap(ctx, g, c, s.Tip)
700 if err != nil {
701 return nil, nil, err
702 }
703 p, err := plan(ctx, g, c, s, cap)
704 if err != nil {
705 return nil, nil, err
706 }
707 return s, p, nil
708}
709
710// writeOnce is a write pass. It settles the journal of earlier
711// operations first, if the state directory holds one. It then plans, with
712// each family that shares a change or a branch with a family the journal
713// still holds waiting for it, builds the pass's writes, adds them to the
714// journal, keeps it, and settles it (publish.go). A journal that does not
715// read, or is another's, stops the pass: the pass would otherwise write
716// its own in its place, and lose what that one names.
717func writeOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
718 path := filepath.Join(c.state, journalFile)
719 j, err := loadJournal(c.state, c.binding())
720 if err != nil {
721 return nil, fmt.Errorf("%w. A write pass starts nothing while it is there: repair origin by hand, and move the journal aside", err)
722 }
723 actions := []Action{}
724 var found *Recovery
725 if j != nil {
726 st, err := settle(ctx, g, c, j)
727 if err != nil {
728 return nil, err
729 }
730 actions, found = st.actions, st.last
731 found.Journal = path
732 if st.closed {
733 j = nil
734 }
735 }
736 // The planner reads the journal settle left in the state directory.
737 s, p, err := planned(ctx, g, c)
738 if err != nil {
739 return nil, err
740 }
741 p.Recovery, p.Actions = found, actions
742 out, err := build(ctx, g, s, p, c.binding(), p.Operation)
743 if err != nil {
744 return nil, err
745 }
746 defer out.releasePrepared(ctx, g)
747 if len(out.journal.Families) == 0 {
748 if j != nil {
749 p.Pending = found
750 }
751 return p, nil
752 }
753 if j != nil {
754 out.journal.Families = append(j.Families, out.journal.Families...)
755 }
756 if err := keep(ctx, g, c.state, out.journal); err != nil {
757 return nil, err
758 }
759 // The journal keeps every object its writes push reachable now.
760 out.releasePrepared(ctx, g)
761 st, err := settle(ctx, g, c, out.journal)
762 p.Actions = append(p.Actions, st.actions...)
763 if err != nil {
764 return nil, err
765 }
766 if !st.closed {
767 p.Pending = st.last
768 p.Pending.Journal = path
769 }
770 return p, nil
771}
772
773// binding is what a pass's state directory and journal belong to.
774func (c config) binding() binding {
775 return binding{Repository: c.repo, Target: c.target, Principal: c.principal}
776}
777
778// requestsOf is every integration request the snapshot lists, in name
779// order, and the evidence fingerprint of every attestation ref. The refs
780// are a map, read in no fixed order, so the requests are put in name
781// order before anything judges them: their reasons and notes, and the
782// reports that carry them, are then the same for the same snapshot.
783//
784// The snapshot lists request heads and does not fetch them. They are
785// fetched here, before any ancestry is read, all at once and then one by
786// one when that fails, so one head origin cannot serve leaves the others
787// readable.
788func requestsOf(ctx context.Context, g rebase.Git, s *rebase.Snapshot) ([]Request, string) {
789 var attestations []string
790 var requests []Request
791 for ref, oid := range s.Refs {
792 switch {
793 case strings.HasPrefix(ref, rebase.AttestationRefs):
794 attestations = append(attestations, ref+" "+oid)
795 case strings.HasPrefix(ref, rebase.RequestPrefix):
796 requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid})
797 }
798 }
799 sort.Slice(requests, func(i, j int) bool { return requests[i].Name < requests[j].Name })
800 var heads []string
801 for _, r := range requests {
802 heads = append(heads, r.Head)
803 }
804 if rebase.Fetch(ctx, g, heads...) != nil {
805 for _, h := range heads {
806 _ = rebase.Fetch(ctx, g, h)
807 }
808 }
809 return requests, change.EvidenceFingerprint(attestations)
810}
811
812// plan decides the journal in the state directory, if there is one, and
813// plans every family in the snapshot, with the cap given.
814func plan(ctx context.Context, g rebase.Git, c config, s *rebase.Snapshot, cap int) (*Plan, error) {
815 requests, evidence := requestsOf(ctx, g, s)
816 p := &Plan{
817 Target: rebase.Target, Tip: s.Tip, Evidence: evidence, Cap: cap,
818 Operation: newOperation(time.Now()), Actions: []Action{},
819 }
820 in := incoming(ctx, g, s.Tip)
821
822 j, err := loadJournal(c.state, c.binding())
823 switch {
824 case err != nil:
825 p.Recovery = &Recovery{Journal: filepath.Join(c.state, journalFile), Error: err.Error(), Decisions: []Decision{}}
826 case j != nil:
827 p.Recovery = decide(j, reading{
828 s: s, requests: requests, evidence: p.Evidence, in: in, is: ancestry(ctx, g),
829 have: func(oid string) bool { return run(ctx, g, "cat-file", "-e", oid) == nil },
830 landed: s.IsLanded,
831 })
832 p.Recovery.Journal = filepath.Join(c.state, journalFile)
833 }
834 journaled := journaledLayers(j)
835
836 seen := map[string]bool{}
837 for _, n := range s.Changes {
838 if seen[n.ID] || !s.Unlanded(n) {
839 continue
840 }
841 f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true})
842 if err != nil {
843 return nil, err
844 }
845 for _, l := range f.Layers {
846 if l.ID != "" {
847 seen[l.ID] = true
848 }
849 }
850 fp := judge(f, s, c.principal, p, requests, in)
851 if why := waits(f, journaled); why != "" {
852 fp.Action, fp.Reasons = wait, []string{why}
853 }
854 p.Families = append(p.Families, fp)
855 p.families = append(p.families, f)
856 }
857 overlapping(p)
858 return p, nil
859}
860
861// overlapping has each family the pass would build writes for wait when
862// it shares a change or a branch with another such family. Two changes
863// that name one branch are two families when neither's head descends
864// from the other's, and the journal takes no two families that share a
865// branch, since their writes would race. So neither is built while both
866// name it, and every other family is planned as usual.
867func overlapping(p *Plan) {
868 type holder struct {
869 family int
870 name string
871 }
872 whose := map[string][]holder{} // the families that would be written, by each change and branch
873 for i, fp := range p.Families {
874 if fp.Action != restack && fp.Action != hold {
875 continue
876 }
877 for _, l := range p.families[i].Layers {
878 for _, key := range layerKeys(l.ID, l.Branch) {
879 if hs := whose[key]; len(hs) == 0 || hs[len(hs)-1].family != i {
880 whose[key] = append(whose[key], holder{i, l.Name})
881 }
882 }
883 }
884 }
885 for i := range p.Families {
886 fp := &p.Families[i]
887 if fp.Action != restack && fp.Action != hold {
888 continue
889 }
890 why := ""
891 for _, l := range p.families[i].Layers {
892 for _, key := range layerKeys(l.ID, l.Branch) {
893 for _, h := range whose[key] {
894 if h.family != i && why == "" {
895 why = fmt.Sprintf("%s shares the %s with %s, in another family, so neither family is built while both name it", l.Name, key, h.name)
896 }
897 }
898 }
899 }
900 if why != "" {
901 fp.Action, fp.Reasons = wait, []string{why}
902 }
903 }
904}
905
906// journaledLayers is the operation of each family the journal holds, by
907// each of the family's changes and branches (layerKeys).
908func journaledLayers(j *Journal) map[string]string {
909 held := map[string]string{}
910 if j == nil {
911 return held
912 }
913 for _, f := range j.Families {
914 for _, l := range f.Observed.Layers {
915 for _, key := range layerKeys(l.ID, l.Branch) {
916 held[key] = f.Operation
917 }
918 }
919 }
920 return held
921}
922
923// waits says why a family waits for a family the journal holds: it
924// shares a change or a branch with it, and writes built for it would race
925// that family's. "" is a family that shares neither.
926func waits(f *rebase.Family, journaled map[string]string) string {
927 for _, l := range f.Layers {
928 for _, key := range layerKeys(l.ID, l.Branch) {
929 if op, found := journaled[key]; found {
930 return fmt.Sprintf("%s is in a family of operation %s, which the journal still holds, so this family waits for it", l.Name, op)
931 }
932 }
933 }
934 return ""
935}
936
937// judge decides what a pass would do with one family. It judges requests
938// in the order given, which plan makes name order, so the family's
939// requests, reasons and notes come in that order too.
940func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, in Incoming) FamilyPlan {
941 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
942 ready := false
943 for _, l := range f.Layers {
944 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
945 if l.Below != nil {
946 lp.Below = l.Below.Name
947 }
948 if l.State() == rebase.Ready {
949 ready = true
950 } else {
951 fp.Reasons = append(fp.Reasons, stateLine(l))
952 }
953 fp.Layers = append(fp.Layers, lp)
954 }
955 switch {
956 case !ready:
957 fp.Action = leave
958 return fp
959 case f.FastForwards():
960 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
961 return fp
962 }
963 if err := f.Check(); err != nil {
964 fp.Reasons = append(fp.Reasons, err.Error())
965 }
966
967 m := membersOf(f)
968 for _, r := range requests {
969 by, err := Relate(r, m, in)
970 if err != nil {
971 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
972 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
973 continue
974 }
975 if by == nil {
976 continue
977 }
978 o, found := s.OutcomeOf(r.Name)
979 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
980 if found {
981 rp.Decision = o.Decision
982 }
983 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
984 switch {
985 case !rp.Releases:
986 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
987 case o.Decision == "reject":
988 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
989 }
990 fp.Requests = append(fp.Requests, rp)
991 }
992
993 for i, l := range f.Layers {
994 if l.ID == "" || l.Record == nil {
995 continue
996 }
997 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
998 fp.Layers[i].Capacity = cp
999 fp.Reasons = append(fp.Reasons, cp.Over...)
1000 }
1001 fp.Action = restack
1002 if len(fp.Reasons) > 0 {
1003 fp.Action = hold
1004 }
1005 return fp
1006}
1007
1008func printPlan(w io.Writer, p *Plan) {
1009 fmt.Fprintf(w, "%s at %s, evidence %s, at most %d automatic versions a change\n", p.Target, short(p.Tip), p.Evidence, p.Cap)
1010 if r := p.Recovery; r != nil {
1011 printRecovery(w, r)
1012 }
1013 if len(p.Families) == 0 {
1014 fmt.Fprintln(w, "no change to restack")
1015 }
1016 for _, f := range p.Families {
1017 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
1018 for _, l := range f.Layers {
1019 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
1020 if l.Below != "" {
1021 fmt.Fprintf(w, " on %s", l.Below)
1022 }
1023 if c := l.Capacity; c != nil {
1024 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
1025 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
1026 }
1027 fmt.Fprintln(w)
1028 }
1029 for _, r := range f.Requests {
1030 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
1031 }
1032 for _, why := range f.Reasons {
1033 fmt.Fprintf(w, " - %s\n", why)
1034 }
1035 for _, n := range f.Notes {
1036 fmt.Fprintf(w, " note: %s\n", n)
1037 }
1038 if f.Writes != nil {
1039 printWrites(w, f.Writes)
1040 }
1041 }
1042 printPublished(w, p)
1043}
1044
1045// printPublished prints what a write pass pushed, and the journal it
1046// leaves open, if it leaves one.
1047func printPublished(w io.Writer, p *Plan) {
1048 for _, a := range p.Actions {
1049 what := a.Write
1050 if a.ID != "" {
1051 what += " " + a.ID
1052 }
1053 fmt.Fprintf(w, "operation %s, family %d: %s: %s", a.Operation, a.Family, what, a.Result)
1054 if a.Commit != "" {
1055 fmt.Fprintf(w, " %s", short(a.Commit))
1056 }
1057 if a.Why != "" {
1058 fmt.Fprintf(w, ": %s", a.Why)
1059 }
1060 fmt.Fprintln(w)
1061 }
1062 if r := p.Pending; r != nil {
1063 fmt.Fprintln(w, "the journal stays open, and each family that shares a change or a branch with a family it holds waits:")
1064 for _, d := range r.Decisions {
1065 if d.settled() {
1066 continue
1067 }
1068 what := d.Write
1069 if d.ID != "" {
1070 what += " " + d.ID
1071 }
1072 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, d.Action, d.Why)
1073 }
1074 }
1075}
1076
1077// printWrites prints what a pass would push for a family.
1078func printWrites(w io.Writer, ws *Writes) {
1079 fmt.Fprintf(w, " would write, as %s:\n", ws.Result)
1080 for _, b := range ws.Branches {
1081 fmt.Fprintf(w, " push %s %s -> %s\n", b.Branch, short(b.Old), short(b.New))
1082 }
1083 for _, v := range ws.Versions {
1084 fmt.Fprintf(w, " add %s v%d at %s: record %s, leased on %s\n", v.ID, v.Version, short(v.Head), short(v.Record), short(v.Lease))
1085 }
1086 for _, r := range ws.Reports {
1087 switch {
1088 case r.Error != "":
1089 fmt.Fprintf(w, " report %s: none fits: %s\n", r.ID, r.Error)
1090 case r.Unchanged:
1091 fmt.Fprintf(w, " report %s %s: not written, as the current report says the same\n", r.ID, r.Result)
1092 default:
1093 lease := "none"
1094 if r.Lease != "" {
1095 lease = short(r.Lease)
1096 }
1097 fmt.Fprintf(w, " report %s %s: %s, replacing %s\n", r.ID, r.Result, short(r.Commit), lease)
1098 }
1099 if len(r.Omitted) > 0 {
1100 fmt.Fprintf(w, " leaves out %s\n", strings.Join(r.Omitted, ", "))
1101 }
1102 }
1103}
1104
1105// printRecovery prints what recovery decided of the journal.
1106func printRecovery(w io.Writer, r *Recovery) {
1107 if r.Error != "" {
1108 fmt.Fprintf(w, "recovery: %s\n", r.Error)
1109 return
1110 }
1111 state := "settled"
1112 if !r.Settled {
1113 state = "not settled"
1114 }
1115 fmt.Fprintf(w, "recovery: %s, %s\n", r.Journal, state)
1116 for _, d := range r.Decisions {
1117 what := d.Write
1118 if d.ID != "" {
1119 what += " " + d.ID
1120 }
1121 action := d.Action
1122 switch {
1123 case d.Terminal:
1124 action += " (terminal)"
1125 case d.Final:
1126 action += " (final)"
1127 }
1128 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, action, d.Why)
1129 }
1130}