gunk-dev/the-valley

worker.go

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