gunk-dev/the-valley

worker.go

source0820acba4decmain's published tip history
24.9 KiB
1package main
2
3// work is one pass of a check worker. It builds the nix checks that ready
4// changes require before anyone approves them, and publishes the evidence
5// on origin, where approve (bin/valley) reuses it instead of building it,
6// and where the integrator finds it for a request approve filed without it.
7// A timer runs it; it keeps no queue, lease or schedule of its own.
8//
9// A pass reads each project named with --repo, and works through the
10// project's ready changes:
11//
12// 1. It lists the ready changes whose active version has not landed, as
13// valley pending does (pending.go), and pins each one's active head.
14// 2. It derives the checks the head requires, as valley-go checks does
15// (checks.go), over the head's merge base with main. Both policy
16// layers are read at main's tip on origin, as approve reads them,
17// never from the change.
18// 3. It asks coverage (coverage.go) which of the head's nix checks origin
19// already holds evidence for. Command checks are left to approve.
20// 4. It runs the rest in one batch, with attest run --rev <head> under
21// the worker's key, and pushes the one attestation ref attest stored.
22// It pushes nothing else. Given --slots, the batch builds that many
23// checks at once; without it, attest's own default decides.
24//
25// The evidence is about the head's tree, so it stays true if the change
26// moves on while the batch runs. The pass does not read the change's
27// record again before it publishes.
28//
29// The attestation namespace admits creations only, so the worker never
30// builds what it could not publish. When origin already holds this
31// worker's ref for a tree and the ref lacks a required check, the pass
32// reports it and builds nothing. approve --build-here builds the rest
33// under the operator's key (bd-7b7d58f). When the worker's ref is stored
34// here but not on origin, an earlier pass built it and its push was lost,
35// so the pass pushes that same ref again rather than building it again.
36//
37// A batch that fails is not run again at once, and neither is a push that
38// fails. The pass records each failure in failures.json in the state
39// directory, under its project: a batch by the tree and the checks it
40// runs, and a push by the object it publishes. A failed batch waits
41// firstBuildWait before it runs again, and a failed push waits
42// firstPushWait. Each wait doubles with every failure in a row, up to
43// longestWait. The clock is read when the pass asks whether a wait is
44// over, and again when an attempt ends, so a long build does not use up
45// its own wait. A new version is a new batch, and runs at once. VALLEY_NOW,
46// when set, is the time the pass reads as now (main.go's clock). Deleting
47// the record lets everything run again at once.
48//
49// A pass forgets the failures it did not meet in a project, but only for
50// a project it read whole: every ready change's checks derived and its
51// evidence read. A pass over other projects, or one that could not read
52// this one, leaves this one's record as it is.
53//
54// Passes that share a state directory take turns: each holds the lock
55// file there while it runs, and a pass that finds it held waits for it.
56// attest is handed the lock too, so it stays held while a batch runs even
57// when the pass that started the batch is killed.
58//
59// A read of origin that fails stops the pass, because a read that did not
60// happen must not read as no changes or no evidence. Anything else that
61// goes wrong with one change is reported, and the pass goes on to the
62// next. The pass exits 1 when anything went wrong.
63//
64// Given --wake, a pass claims that wake directory's due mark before it
65// reads anything, and acknowledges the claim when it has handled what it
66// read (wake.go). A pass has handled it when it read every project whole
67// and everything that went wrong was a failed batch or push whose wait it
68// recorded: those are retried when their wait is over, by a pass the
69// timer starts, and a new mark for the same refs would only find them
70// still waiting. Anything else that went wrong (a policy that did not
71// read, checks that did not derive, a read that stopped the pass, a
72// record that was not written) leaves the claim unacknowledged. A pass
73// that could not claim due reads and builds all the same, and then exits
74// claimFailedStatus instead of 0 or 1.
75//
76// Given --telemetry, or VALLEY_TELEMETRY_DIR in its environment, which is
77// how the host module names it, a pass says what it is doing as it does it, and keeps
78// its recent attempts and the failures waiting out their backoff with
79// what each was about (workertelemetry.go). It hands attest the same
80// stream for each batch's progress.
81
82import (
83 "context"
84 "encoding/json"
85 "errors"
86 "fmt"
87 "io"
88 "os"
89 "os/exec"
90 "path/filepath"
91 "strconv"
92 "strings"
93 "syscall"
94 "time"
95
96 "the-valley/change"
97 "the-valley/composed"
98 "the-valley/telemetry"
99)
100
101const workUsage = "usage: valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>] [--wake <dir>] [--telemetry <dir>] [--slots <n>]"
102
103// projectLayer is the project's own policy layer, in main's tree.
104const projectLayer = "policy/project"
105
106// The waits after a failure before the same thing is tried again: the
107// first after a failed batch, the first after a failed push, and the
108// longest either grows to by doubling.
109const (
110 firstBuildWait = 15 * time.Minute
111 firstPushWait = time.Minute
112 longestWait = 24 * time.Hour
113)
114
115// worker is one pass: the signer it attests as, the lock it holds, what it
116// says, and what it has found going wrong.
117type worker struct {
118 key, name string
119 slots int // how many checks a batch builds at once, or 0 for attest's default
120 keyhash string // the key hash an attestation ref of this signer ends in
121 lock *os.File // the state directory's lock, held for the pass
122 wake *wake // the wake directory's claim, or nil without --wake
123 tel *workerTelemetry
124 failures *failureRecord
125 stdout io.Writer
126 stderr io.Writer
127 troubles int // things that went wrong that did not stop the pass
128 waits int // of the troubles, the failures whose wait was recorded
129}
130
131func runWork(g git, args []string, stdout, stderr io.Writer) (err error) {
132 var repos []string
133 var key, name, state, wakeDir, telemetryDir string
134 slots := 0
135 for i := 0; i < len(args); i++ {
136 opt, value, inline := strings.Cut(args[i], "=")
137 if opt != "--repo" && opt != "--key" && opt != "--name" && opt != "--state" && opt != "--wake" && opt != "--telemetry" && opt != "--slots" {
138 return failure(workUsage)
139 }
140 if !inline {
141 if i+1 == len(args) {
142 return failure(workUsage)
143 }
144 i++
145 value = args[i]
146 }
147 switch opt {
148 case "--repo":
149 if !change.ValidPrincipal(value) {
150 return failure(fmt.Sprintf("--repo %s: not a project name", value))
151 }
152 repos = append(repos, value)
153 case "--key":
154 key = value
155 case "--name":
156 name = value
157 case "--state":
158 state = value
159 case "--wake":
160 wakeDir = value
161 case "--telemetry":
162 telemetryDir = value
163 case "--slots":
164 n, err := strconv.Atoi(value)
165 if err != nil || n < 1 {
166 return failure(fmt.Sprintf("--slots %s: not a whole number of at least 1", value))
167 }
168 slots = n
169 }
170 }
171 if len(repos) == 0 || key == "" {
172 return failure(workUsage)
173 }
174 if telemetryDir == "" {
175 telemetryDir = os.Getenv("VALLEY_TELEMETRY_DIR")
176 }
177 // From here on, a pass given --wake that ends without having claimed
178 // due exits claimFailedStatus, however it ends, so whatever started
179 // it for that due holds off before it starts another.
180 var claim *wake
181 if wakeDir != "" {
182 defer func() {
183 if claim != nil && claim.err == nil {
184 return
185 }
186 why := "due was not claimed"
187 if claim != nil {
188 why = claim.err.Error()
189 }
190 if err != nil {
191 fmt.Fprintf(stderr, "valley: %s\n", err)
192 }
193 err = claimFailure{fmt.Sprintf("%s, so the pass exits %d", why, claimFailedStatus)}
194 }()
195 }
196 // attest runs in the repository a project is read through, which may
197 // be a cache clone, so a key named relative to here is made absolute.
198 abs, err := filepath.Abs(key)
199 if err != nil {
200 return failure(fmt.Sprintf("--key %s: %v", key, err))
201 }
202 key = abs
203 if state == "" {
204 if state, err = stateDirectory(); err != nil {
205 return failure("no state directory: name one with --state")
206 }
207 }
208 if err := os.MkdirAll(state, 0o700); err != nil {
209 return failure(fmt.Sprintf("could not make the state directory %s", state))
210 }
211
212 lock, err := lockState(filepath.Join(state, "lock"), stderr)
213 if err != nil {
214 return failure(fmt.Sprintf("could not take the lock in %s: %v", state, err))
215 }
216 defer lock.Close() // close drops the flock; every attest handed it has ended by then
217
218 // The claim comes before any read, so a move marked after it is
219 // either read by this pass or left marked for the next.
220 if wakeDir != "" {
221 claim = claimWake(wakeDir, stderr)
222 defer claim.close()
223 if claim.err != nil {
224 fmt.Fprintf(stderr, "valley: %v; the pass reads everything all the same\n", claim.err)
225 }
226 }
227
228 // The signer is read before anything else is done, so a pass that
229 // could only end in "no key" says so before it reads anything.
230 keyArgs := []string{"key", "--key", key}
231 if name != "" {
232 keyArgs = append(keyArgs, "--name", name)
233 }
234 out, err := attestTool(g, keyArgs...)
235 fields := strings.SplitN(strings.TrimSpace(out), "+", 3)
236 if err != nil || len(fields) != 3 || len(fields[1]) != 8 {
237 return failure(fmt.Sprintf("could not read the signing key at %s: %s", key, refusalOf(out)))
238 }
239
240 w := &worker{key: key, name: name, slots: slots, keyhash: fields[1], lock: lock, wake: claim, stdout: stdout, stderr: stderr}
241 w.tel = openWorkerTelemetry(telemetryDir)
242 defer func() { w.tel.finish(w.failures, w.troubles, err) }()
243 w.failures = readFailures(filepath.Join(state, "failures.json"), stderr)
244 for _, repo := range repos {
245 if err := w.project(g, repo); err != nil {
246 return err
247 }
248 }
249 w.save()
250 if claim != nil && w.troubles == w.waits {
251 if err := claim.ack(); err != nil {
252 fmt.Fprintf(stderr, "valley: could not acknowledge %s: %v\n", filepath.Join(wakeDir, "claimed"), err)
253 w.troubles++
254 }
255 }
256 if w.troubles > 0 {
257 return failure(fmt.Sprintf("the pass finished, but %s went wrong in it; each is said above", counted(w.troubles, "thing")))
258 }
259 return nil
260}
261
262// stateDirectory is where the worker keeps its lock and its record of
263// failed batches by default: $XDG_STATE_HOME/valley/worker, or
264// ~/.local/state/valley/worker, beside attest's timing log.
265func stateDirectory() (string, error) {
266 state := os.Getenv("XDG_STATE_HOME")
267 if !filepath.IsAbs(state) {
268 home, err := os.UserHomeDir()
269 if err != nil {
270 return "", err
271 }
272 state = filepath.Join(home, ".local", "state")
273 }
274 return filepath.Join(state, "valley", "worker"), nil
275}
276
277// lockState takes the lock file at path, waiting for whoever holds it, and
278// returns the open file, whose closing releases it. The lock is flock's,
279// as self-update's is. It belongs to the open file, so it is released when
280// every process holding that file has closed it or ended, however each
281// ends.
282func lockState(path string, stderr io.Writer) (*os.File, error) {
283 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
284 if err != nil {
285 return nil, err
286 }
287 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
288 if errors.Is(err, syscall.EWOULDBLOCK) {
289 fmt.Fprintf(stderr, "valley: another pass holds %s; waiting for it to end\n", path)
290 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
291 }
292 if err != nil {
293 f.Close()
294 return nil, err
295 }
296 return f, nil
297}
298
299// project works through one project's ready changes. It returns an error
300// only when a read of origin failed, which stops the pass. When it has
301// read the project whole, it forgets the project's failures it did not
302// meet.
303func (w *worker) project(g git, name string) error {
304 list, _, err := sources(g, listing{repo: name}, w.stderr)
305 if err != nil {
306 return failure(fmt.Sprintf("%s: %v; the pass stops here", name, err))
307 }
308 repos := readSources(list, newVerifier())
309 r := repos[0]
310 if r.err != nil {
311 return failure(fmt.Sprintf("%s: %v; the pass stops here", name, r.err))
312 }
313 view := r.pendingView(handles(repos))
314 met := map[string]bool{} // the failures this pass met, by key
315 if len(view.Changes) == 0 {
316 w.failures.keep(name, met)
317 return nil
318 }
319 if r.snap.tip == "" {
320 fmt.Fprintf(w.stdout, "%s: origin has no main to read the policy at, so nothing is built\n", name)
321 w.troubles++
322 return nil
323 }
324 instance, project, done, err := policyLayers(r.g, r.snap.tip)
325 defer done()
326 if err != nil {
327 fmt.Fprintf(w.stdout, "%s: the policy at main did not read, so nothing is built: %v\n", name, err)
328 w.troubles++
329 return nil
330 }
331 whole := true
332 for _, c := range view.Changes {
333 read, err := w.change(r, instance, project, c, met)
334 if err != nil {
335 return err
336 }
337 whole = whole && read
338 }
339 if whole {
340 w.failures.keep(name, met)
341 }
342 return nil
343}
344
345// change builds and publishes what one ready change's head lacks. read
346// says whether it read the change through: derived its checks, and read
347// the evidence origin holds for them.
348func (w *worker) change(r listed, instance, project string, c jsonChange, met map[string]bool) (read bool, err error) {
349 v := c.Versions[c.Active-1]
350 head := v.Head
351 w.tel.change(r.name, c, v)
352 say := func(format string, args ...any) {
353 fmt.Fprintf(w.stdout, "%s: %s v%d at %s: %s\n", r.name, c.Handle, v.N, head[:min(7, len(head))], fmt.Sprintf(format, args...))
354 }
355 base, err := r.g.output(true, "merge-base", r.snap.tip, head)
356 if err != nil {
357 say("shares no history with main, so nothing is built")
358 w.troubles++
359 return false, nil
360 }
361 doc, err := derivedChecks(r.g, "", instance, project, base, head)
362 if err != nil {
363 say("its checks did not derive, so nothing is built: %v", err)
364 w.troubles++
365 return false, nil
366 }
367 var asked []nixCheck
368 for _, q := range doc.Required {
369 if q.Runner == "nix" {
370 asked = append(asked, nixCheck{q.Name, q.Attribute})
371 }
372 }
373 if len(asked) == 0 {
374 say("requires no nix check")
375 return true, nil
376 }
377
378 e, err := coverageOf(r.g, head, asked, w.stderr)
379 if err != nil {
380 return false, failure(fmt.Sprintf("%s: %s v%d: %v; the pass stops here", r.name, c.Handle, v.N, err))
381 }
382 var missing []nixCheck
383 var names []string
384 for _, q := range asked {
385 if _, ok := e.covered[q.name]; !ok {
386 missing = append(missing, q)
387 names = append(names, q.name)
388 }
389 }
390 if len(missing) == 0 {
391 say("origin holds evidence for every nix check it requires")
392 return true, nil
393 }
394
395 own := attestationRefs + e.digest + "/" + w.keyhash
396 if _, ok := e.listed[own]; ok {
397 say("origin already holds %s, this worker's evidence for its tree, and it does not cover %s. "+
398 "That namespace admits creations only, so approve --build-here builds the rest (bd-7b7d58f)", own, strings.Join(names, ", "))
399 return true, nil
400 }
401 if stored, found, err := r.g.ref(own); err == nil && found {
402 say("an earlier pass stored %s, and origin does not hold it", own)
403 w.publish(r, own, stored, met, say)
404 return true, nil
405 }
406
407 batch := "build " + e.digest + " " + strings.Join(names, ",")
408 met[batch] = true
409 if f, waiting := w.failures.waiting(r.name, batch, clock()); waiting {
410 say("its batch %s failed %s in a row, so it is not built again before %s", strings.Join(names, ", "), counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
411 return true, nil
412 }
413 say("building %s", strings.Join(names, ", "))
414 mark := w.tel.streamEnd()
415 attestRun := telemetry.NewRunID()
416 a := w.tel.begin("build", e.digest, names, map[string]any{"attest_run": attestRun})
417 if err := w.attest(r.g, head, missing, attestRun, r.name, c, v); err != nil {
418 // The wait runs from when the batch ended, not from when it began.
419 f := w.failures.failed(r.name, batch, clock(), firstBuildWait)
420 reason := fmt.Sprintf("attest run %s: %v", attestRun, err)
421 if failed := w.tel.failedChecks(attestRun, mark); len(failed) > 0 {
422 reason += "; " + strings.Join(failed, ", ")
423 }
424 w.tel.end(a, err, reason, r.name, batch, &f)
425 say("the batch did not pass (%v); it is not built again before %s", err, f.Retry.Format(time.RFC3339))
426 w.troubles++
427 w.waits++
428 w.save()
429 return true, nil
430 }
431 w.failures.passed(r.name, batch)
432 w.tel.end(a, nil, "", r.name, batch, nil)
433 stored, found, err := r.g.ref(own)
434 if err != nil || !found {
435 say("attest stored no %s, so nothing is published", own)
436 w.troubles++
437 return true, nil
438 }
439 w.publish(r, own, stored, met, say)
440 return true, nil
441}
442
443// attest runs one batch with attest run, which stores the notes at the
444// worker's attestation ref for the head's tree and publishes nothing.
445// What attest prints is passed on.
446//
447// attest is handed the lock file as well, and holds it until it ends, and
448// the wake directory's lock with it. The
449// flock belongs to the open file, so the lock stays held while attest
450// runs, and while anything it started that inherited the file runs, even
451// when this pass is killed. A later pass waits for all of it, and then
452// finds the ref attest stored.
453func (w *worker) attest(g git, head string, checks []nixCheck, run, project string, c jsonChange, v jsonVersion) error {
454 repo := g.dir
455 if repo == "" {
456 repo = "."
457 }
458 args := []string{"run", "--repo", repo, "--rev", head, "--key", w.key}
459 if w.name != "" {
460 args = append(args, "--name", w.name)
461 }
462 if w.slots > 0 {
463 args = append(args, "--slots", strconv.Itoa(w.slots))
464 }
465 for _, q := range checks {
466 args = append(args, "--check", q.name+"="+q.attribute)
467 }
468 if w.tel != nil {
469 args = append(args, "--telemetry", w.tel.stream(), "--telemetry-run", run, "--project", project,
470 "--change", c.ChangeID, "--change-version", strconv.Itoa(v.N))
471 }
472 cmd := exec.Command("attest", args...)
473 cmd.Env = g.env
474 cmd.Dir = g.dir
475 cmd.Stdout, cmd.Stderr = w.stdout, w.stderr
476 cmd.ExtraFiles = []*os.File{w.lock}
477 if w.wake != nil && w.wake.lock != nil {
478 cmd.ExtraFiles = append(cmd.ExtraFiles, w.wake.lock)
479 }
480 return cmd.Run()
481}
482
483// publish pushes one attestation ref to origin, and nothing else. The hook
484// verifies the notes against the tree and the signer whoever pushes them.
485// A push that fails leaves the ref stored here, and the same object is not
486// pushed again until its wait is over: by any pass, and for any change
487// whose tree it is about.
488func (w *worker) publish(r listed, ref, object string, met map[string]bool, say func(string, ...any)) {
489 key := "push " + object
490 met[key] = true
491 if f, waiting := w.failures.waiting(r.name, key, clock()); waiting {
492 say("publishing %s failed %s in a row, so it is not pushed again before %s", ref, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
493 return
494 }
495 a := w.tel.begin("push", "", nil, map[string]any{"ref": ref, "object": object})
496 if _, err := r.g.output(false, "push", "--quiet", "origin", object+":"+ref); err != nil {
497 f := w.failures.failed(r.name, key, clock(), firstPushWait)
498 w.tel.end(a, err, fmt.Sprintf("pushing %s to origin: %v", ref, err), r.name, key, &f)
499 say("could not publish %s; it is not pushed again before %s", ref, f.Retry.Format(time.RFC3339))
500 w.troubles++
501 w.waits++
502 w.save()
503 return
504 }
505 w.failures.passed(r.name, key)
506 w.tel.end(a, nil, "", r.name, key, nil)
507 say("published %s", ref)
508}
509
510// save writes the failure record, and counts a write that fails as
511// something that went wrong.
512func (w *worker) save() {
513 if err := w.failures.save(); err != nil {
514 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.failures.path, err)
515 w.troubles++
516 }
517}
518
519// policyLayers resolves the two policy layers a project's changes are
520// derived under, as approve resolves them (bin/valley's
521// resolve_instance_layer and resolve_project_layer), and returns what
522// removes them. Both are read at main's tip on origin. The floor is that
523// tip's own policy/instance when it carries one, and otherwise
524// policy/instance at the tip of main in the owning valley that
525// policy/valley names. A tip with no policy/project is derived under the
526// floor alone.
527func policyLayers(g git, tip string) (instance, project string, done func(), err error) {
528 ctx := context.Background()
529 var ends []func()
530 done = func() {
531 for _, end := range ends {
532 end()
533 }
534 }
535 repo := g.dir
536 if repo == "" {
537 repo = "."
538 }
539 floor := composed.Floor{Repo: repo, Ref: tip, Dir: instanceLayer}
540 if !g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
541 pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer)
542 if err != nil {
543 return "", "", done, fmt.Errorf("main names no owning valley at %s", valleyPointer)
544 }
545 url := pointerURL(pointer)
546 if url == "" {
547 return "", "", done, fmt.Errorf("%s on main names no repository", valleyPointer)
548 }
549 if err := checkURL(url); err != nil {
550 return "", "", done, err
551 }
552 scratch, err := os.MkdirTemp("", "valley-work-valley-")
553 if err != nil {
554 return "", "", done, err
555 }
556 ends = append(ends, func() { _ = os.RemoveAll(scratch) })
557 v := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: scratch}
558 if _, err := v.output(true, "init", "--quiet", "--bare"); err != nil {
559 return "", "", done, errors.New("no scratch repository to fetch the floor into")
560 }
561 // The valley's main is read by its exact name, and fetched by the
562 // object it names: given a ref name the valley lacks, fetch takes
563 // another ref whose name ends in it, such as
564 // refs/heads/refs/heads/main.
565 at, err := remoteRef(v, url, "refs/heads/main")
566 if err != nil {
567 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
568 } else if at == "" {
569 return "", "", done, fmt.Errorf("the owning valley %s has no refs/heads/main", url)
570 }
571 if _, err := v.output(true, "fetch", "--quiet", "--depth", "1", "--no-tags", "--end-of-options", url, at); err != nil {
572 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
573 }
574 floor = composed.Floor{Repo: scratch, Ref: at, Dir: instanceLayer}
575 }
576 instance, end, err := floor.Open(ctx, "valley-work-floor")
577 ends = append(ends, end)
578 if err != nil {
579 return "", "", done, err
580 }
581 project, _, end, err = composed.Project(ctx, repo, tip, projectLayer, "valley-work-project")
582 ends = append(ends, end)
583 return instance, project, done, err
584}
585
586// failureRecord is the worker's record of what failed, project by
587// project: each batch, keyed "build <tree digest> <check>,<check>", and
588// each push, keyed "push <object ID>". For each it holds how many times in
589// a row it failed, and the time before which it is not tried again. It is
590// kept as JSON at path.
591type failureRecord struct {
592 path string
593 Projects map[string]map[string]backoff `json:"projects"`
594}
595
596type backoff struct {
597 Failures int `json:"failures"`
598 Retry time.Time `json:"retry"`
599}
600
601// readFailures reads the record at path. A record that is not there is
602// empty. One that does not read is said, and started again empty: the
603// worst it costs is one more try of each thing it held.
604func readFailures(path string, stderr io.Writer) *failureRecord {
605 r := &failureRecord{path: path}
606 data, err := os.ReadFile(path)
607 if err == nil {
608 err = json.Unmarshal(data, r)
609 }
610 if err != nil && !errors.Is(err, os.ErrNotExist) {
611 fmt.Fprintf(stderr, "valley: %s does not read, so everything it held is tried again\n", path)
612 r.Projects = nil
613 }
614 if r.Projects == nil {
615 r.Projects = map[string]map[string]backoff{}
616 }
617 return r
618}
619
620// waiting reports whether something failed and its wait is not over.
621func (r *failureRecord) waiting(project, key string, now time.Time) (backoff, bool) {
622 f, ok := r.Projects[project][key]
623 return f, ok && now.Before(f.Retry)
624}
625
626// failed records one more failure in a row, and the time it may be tried
627// again: first after the first failure, doubled for each one after it, and
628// never more than longestWait.
629func (r *failureRecord) failed(project, key string, now time.Time, first time.Duration) backoff {
630 if r.Projects[project] == nil {
631 r.Projects[project] = map[string]backoff{}
632 }
633 f := r.Projects[project][key]
634 f.Failures++
635 wait := first
636 for i := 1; i < f.Failures && wait < longestWait; i++ {
637 wait *= 2
638 }
639 f.Retry = now.Add(min(wait, longestWait))
640 r.Projects[project][key] = f
641 return f
642}
643
644func (r *failureRecord) passed(project, key string) { delete(r.Projects[project], key) }
645
646// keep forgets every failure of the project that is not in met. Other
647// projects' failures are kept.
648func (r *failureRecord) keep(project string, met map[string]bool) {
649 for key := range r.Projects[project] {
650 if !met[key] {
651 delete(r.Projects[project], key)
652 }
653 }
654 if len(r.Projects[project]) == 0 {
655 delete(r.Projects, project)
656 }
657}
658
659// save writes the record whole, through a file renamed into place, so a
660// pass that is killed leaves the last record or the new one. An empty
661// record is no file.
662func (r *failureRecord) save() error {
663 for project, failures := range r.Projects {
664 if len(failures) == 0 {
665 delete(r.Projects, project)
666 }
667 }
668 if len(r.Projects) == 0 {
669 if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) {
670 return err
671 }
672 return nil
673 }
674 data, err := json.MarshalIndent(r, "", " ") // in key order
675 if err != nil {
676 return err
677 }
678 tmp, err := os.CreateTemp(filepath.Dir(r.path), ".failures-*")
679 if err != nil {
680 return err
681 }
682 _, err = tmp.Write(append(data, '\n'))
683 if cerr := tmp.Close(); err == nil {
684 err = cerr
685 }
686 if err == nil {
687 err = os.Rename(tmp.Name(), r.path)
688 }
689 if err != nil {
690 os.Remove(tmp.Name())
691 }
692 return err
693}