gunk-dev/the-valley

refs.go

sourced472c3909b6fmain's published tip history
30.9 KiB
1package main
2
3// The refs transport: a reconciliation loop over the integration requests
4// durable in the served repository.
5//
6// The bus is unauthenticated (bd-d853d9c), which gates automated
7// consumers, and the requests are durable in git with the bus as a
8// projection over them (architecture.md). So the controller level-triggers
9// over the request refs themselves and converges: each pass recomputes the
10// verdict for every request against the current tip, acts only where the
11// answer has changed since the last pass, and needs no subscription at
12// all. It publishes outcomes to the bus exactly as the post-receive hook
13// publishes ref updates. What starts a pass is the controller's start, its
14// interval, and a mark in its own wake directory (wake.go); a mark carries
15// nothing, so a pass decides from the refs alone.
16//
17// # The request ref
18//
19// A request is a ref:
20//
21// refs/the-valley/integration-requests/<target>/<change> -> commit
22//
23// The target segment names the protected branch, so the change's target
24// stream is refs/heads/<target>; the last segment names the change. The
25// commit is the change's head, its tree is what the attestations are over,
26// and the delta is the merge base with the target's tip to that head.
27// Nothing else is encoded: a change is a diff targeting a stream
28// (ida-93e4f91), and every part of that is already in git. A request
29// whose last segment is c-<change ID> is the request of the change with a
30// record under that ID, and the records decide whether it may land at all
31// (records.go).
32
33import (
34 "the-valley/change"
35 "the-valley/composed"
36 "the-valley/integrator/verdict"
37
38 "fmt"
39 "sort"
40 "strings"
41 "time"
42)
43
44const (
45 requestPrefix = "refs/the-valley/integration-requests"
46 outcomePrefix = "refs/the-valley/integration-outcomes"
47)
48
49// landingTries is how many times a landing builds its ref transaction and
50// applies it, while what fails it is a record ref that moved since it was
51// read. A record ref moves under a landing only when something other than
52// this pass writes it, such as a push creating an attestation ref the
53// landing adds to.
54const landingTries = 3
55
56// request is one integration request as the refs transport found it.
57type request struct {
58 ref string
59 change string
60 target string
61 head string
62}
63
64// requests lists the pending requests, in ref order so a pass is
65// deterministic, along with the refs under the namespace that are not
66// requests at all.
67//
68// Any holder of the approve grant can write this namespace, and anyone at all
69// where a repository is served without the pre-receive hook, so a name that
70// does not parse is an ordinary thing to find there and not a reason to stop: one
71// unreadable ref must not hold up every readable one. It is reported and
72// skipped.
73func (in *integrator) requests() ([]request, []string, error) {
74 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", requestPrefix)
75 if err != nil {
76 return nil, nil, err
77 }
78 var found []request
79 var malformed []string
80 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
81 if line == "" {
82 continue
83 }
84 ref, head, ok := strings.Cut(line, " ")
85 if !ok {
86 continue
87 }
88 rest := strings.TrimPrefix(ref, requestPrefix+"/")
89 target, change, ok := strings.Cut(rest, "/")
90 if !ok || strings.Contains(change, "/") || target == "" || change == "" {
91 malformed = append(malformed, ref)
92 continue
93 }
94 found = append(found, request{ref: ref, change: change, target: "refs/heads/" + target, head: head})
95 }
96 sort.Slice(found, func(i, j int) bool { return found[i].ref < found[j].ref })
97 sort.Strings(malformed)
98 return found, malformed, nil
99}
100
101// reconcile is one pass: judge every request against the current tip of its
102// target, and act where the answer has changed.
103//
104// The change records are read once, before any request is judged. A pass
105// that cannot read them judges nothing: which heads are versions of
106// changes that are not ready is what keeps those heads from landing. The
107// requests a withdrawn change voids are deleted before the rest are
108// judged.
109func (in *integrator) reconcile() error {
110 requests, malformed, err := in.requests()
111 if err != nil {
112 return err
113 }
114 for _, ref := range malformed {
115 fmt.Fprintf(in.out, "%s: not a request ref; one is %s/<target>/<change>. Skipped.\n", ref, requestPrefix)
116 }
117 if len(requests) == 0 {
118 return nil
119 }
120 idx, err := in.readRecords()
121 if err != nil {
122 return err
123 }
124 for _, u := range idx.unreadable {
125 fmt.Fprintf(in.out, "WARNING: %s is a change record that does not read: %s. Requests are judged as though it did not exist, so a head it names is not held back by it. The hook refuses such a record, so the repository's storage is corrupt; restore the record or delete it.\n", u.ref, u.why)
126 }
127 requests = in.voidWithdrawn(requests, idx)
128 inputs, done := in.inputState()
129 defer done()
130 for _, r := range requests {
131 if err := in.handle(r, idx, inputs); err != nil {
132 // One bad request must not stop the pass: the integrator is a
133 // controller, and a request it cannot judge is one request's
134 // problem.
135 fmt.Fprintf(in.out, "%s: %v\n", r.change, err)
136 }
137 }
138 return nil
139}
140
141// handle judges one request under the pass's inputs, and acts on the
142// verdict. A decision it reports is timed, and its timing line follows the report and the
143// recorded outcome; a refusal said before, and so not said again, is not
144// timed again either.
145func (in *integrator) handle(r request, idx *recordIndex, inputs inputs) error {
146 watch := newStopwatch()
147 tip, ok, err := resolveRef(in.repo, r.target)
148 if err != nil {
149 return err
150 } else if !ok {
151 return fmt.Errorf("no target %s to integrate onto", r.target)
152 }
153 // Level-triggering: the verdict is a function of the request's head,
154 // the target's tip, the evidence stored for the change, and the
155 // inputs (inputs.go), so an unchanged answer is one where none of the
156 // four has moved.
157 // Re-announcing an unchanged answer would be a retry storm; missing a
158 // moved one would strand a contributor who pushed the attestation a
159 // previous pass said was absent.
160 evidence, err := in.evidenceState()
161 if err != nil {
162 return err
163 }
164 memo := fmt.Sprintf("%s %s %s", r.head, tip, evidence)
165 last, err := in.readMemo(r)
166 if err != nil {
167 return err
168 }
169 lastInputs := in.readInputs(r)
170 if in.answered(last, memo, lastInputs, inputs.digest) {
171 return nil
172 }
173 // From here on the request has been taken up, so whatever happens is
174 // this pass's answer to it — including a failure. Recording that is
175 // what keeps the next tick from asking the identical question.
176 done := watch.stage(stageRefusal)
177 outcome, err := in.refuse(r, idx, tip, last, memo)
178 done()
179 // A request no rule refuses is judged only when every input read.
180 if err == nil && outcome == "" {
181 if err = inputs.err; err == nil {
182 outcome, err = in.act(r, tip, memo, inputs.floor, watch)
183 }
184 }
185 if err != nil {
186 printTiming := in.timing(r, tip, failedMemo, watch)
187 memoErr := in.writeAnswer(r, memo+" "+failedMemo+" "+in.now().Format(time.RFC3339), inputs.digest)
188 printTiming()
189 if memoErr != nil {
190 return fmt.Errorf("%v (and the failure could not be recorded: %v)", err, memoErr)
191 }
192 return err
193 }
194 if last == memo+" "+string(outcome) && lastInputs == inputs.digest {
195 return nil
196 }
197 printTiming := in.timing(r, tip, string(outcome), watch)
198 // A landing wrote its outcome record in the transaction that moved
199 // the target, and no inputs record: the landing consumed the request,
200 // and moved the tip any later request at that name is judged against.
201 if outcome != verdict.Land {
202 err = in.writeAnswer(r, memo+" "+string(outcome), inputs.digest)
203 }
204 printTiming()
205 return err
206}
207
208// refuse applies the rules that refuse a request before it is judged
209// (records.go), and reports a refusal. It reports one only when it is new:
210// a refusal is decided again on every pass, and saying the same one every
211// tick would bury it.
212func (in *integrator) refuse(r request, idx *recordIndex, tip, last, memo string) (verdict.Outcome, error) {
213 outcome, why, err := in.recordRefusal(r, idx, tip)
214 if err == nil && outcome == "" {
215 outcome, why, err = in.mergeRefusal(r, tip)
216 }
217 if err != nil {
218 return "", err
219 }
220 if outcome != "" && last != memo+" "+string(outcome) {
221 in.reportRefusal(r, tip, outcome, why)
222 }
223 // A record that does not read may name a commit this request brings,
224 // and whether it holds that commit back cannot be told. That is said
225 // with the request, whatever is decided about it.
226 if outcome == "" || last != memo+" "+string(outcome) {
227 for _, u := range in.uncheckable(r, idx, tip) {
228 fmt.Fprintf(in.out, "WARNING: %s may name a commit %s brings, and does not read, so whether it holds that commit back cannot be checked\n", u.ref, r.change)
229 }
230 }
231 return outcome, nil
232}
233
234// reportRefusal prints a refusal the way report prints a verdict.
235func (in *integrator) reportRefusal(r request, tip string, outcome verdict.Outcome, why string) {
236 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), outcome)
237 fmt.Fprintf(in.out, " %s\n", why)
238 fmt.Fprintf(in.out, " no event: a refusal is not staleness, and the request stays where it is\n")
239}
240
241// failedMemo marks a memo written for a pass that could not act on its own
242// verdict, and retryAfter is how long that answer stands.
243//
244// A failure here is a function of the same four things the verdict is, so
245// the identical attempt fails identically until one of them moves — and
246// moving any of them already re-judges the request, whatever the memo says.
247// The window exists for the other kind of failure: a bus, a disk, a lock,
248// something outside the four that will be different later. Minutes rather
249// than ticks, because a controller that reports the same refusal every
250// fifteen seconds has buried the report it was making.
251const (
252 failedMemo = "failed"
253 retryAfter = 10 * time.Minute
254)
255
256// answered says whether this pass already has this request's answer, given
257// the last memo written for it and the inputs it was written under
258// (inputs.go). An outcome stands until the request, the tip, the evidence
259// or the inputs move; a recorded failure stands the same way, and
260// additionally expires, so a transient one is retried without being
261// retried at tick rate. When an input did not read, only a failure
262// stands: no verdict was reached under it. A refusal never stands: what refused it can change
263// while the three stay where they are, as when a draft is readied again,
264// so it is decided again on every pass. Nor does a voiding: a request
265// filed again at the same head is a fresh approval.
266func (in *integrator) answered(last, memo, lastInputs, inputs string) bool {
267 rest, ok := strings.CutPrefix(last, memo+" ")
268 if !ok || lastInputs != inputs {
269 return false
270 }
271 switch verdict.Outcome(rest) {
272 case refusedNotReady, refusedMerge, voidedWithdrawn:
273 return false
274 }
275 when, failed := strings.CutPrefix(rest, failedMemo+" ")
276 if !failed {
277 return inputs != unreadInputs
278 }
279 at, err := time.Parse(time.RFC3339, when)
280 if err != nil {
281 return false
282 }
283 return in.now().Sub(at) < retryAfter
284}
285
286// act judges one request and does what the verdict says, returning the
287// outcome so the memo can record it. A landing records its own: memo is
288// what it records it after. floor is the pass's copy of the floor.
289func (in *integrator) act(r request, tip, memo, floor string, watch *stopwatch) (verdict.Outcome, error) {
290 ch, snap, landed, err := in.materialize(r, tip, floor, watch)
291 if err != nil {
292 return "", err
293 }
294 v := verdict.Decide(ch, snap)
295 in.report(r, tip, v)
296 if landed.composition != "" {
297 fmt.Fprintf(in.out, " policy %s\n", landed.composition)
298 }
299
300 switch v.Outcome {
301 case verdict.Land:
302 outcome, err := in.land(ch, v, r, tip, landed, memo, watch)
303 if outcome != "" || err != nil {
304 if outcome == "" {
305 outcome = v.Outcome
306 }
307 return outcome, err
308 }
309 case verdict.Stale:
310 done := watch.stage(stagePublish)
311 in.publishStale(ch, v, tip)
312 done()
313 case verdict.Reject:
314 // There is no rejection event. The failure model is unified on
315 // staleness (architecture.md), and a change whose evidence is
316 // forged is not stale — so rather than stretch either event to
317 // cover it, the vocabulary stays as it is and the refusal is the
318 // integrator's own output. The request stays put; nothing about
319 // it will change on its own.
320 fmt.Fprintf(in.out, " no event: a forged attestation is not staleness, and the vocabulary has no other word\n")
321 }
322 return v.Outcome, nil
323}
324
325// landing is the commit a verdict would move the target to, and what the
326// verdict was computed under.
327type landing struct {
328 commit string // the commit that would be the target's new tip
329 digest string // the valley-tree-v1 digest of the resulting tree
330 policy string // a digest of the composed policy the verdict used
331
332 // composition is what the pass has to say about how the policy layers
333 // resolved, or empty when both were where they are configured to be.
334 composition string
335
336 // notes are the contributor's attestations as stored, by check name.
337 // The verdict does not read them; what lands countersigns them.
338 notes map[string][]byte
339}
340
341// materialize gathers everything the verdict is a function of: the applied
342// delta, the required checks, the recomputed closures, and what intervening
343// landings touched. The floor is read from floor, the directory the pass
344// took its inputs digest over.
345func (in *integrator) materialize(r request, tip, floor string, watch *stopwatch) (verdict.Change, verdict.Snapshot, landing, error) {
346 var land landing
347 done := watch.stage(stageCheckout)
348 wt, err := addWorktree(in.repo, tip)
349 done()
350 if err != nil {
351 return verdict.Change{}, verdict.Snapshot{}, land, err
352 }
353 defer wt.remove()
354
355 base, err := gitLine(in.repo, "merge-base", tip, r.head)
356 if err != nil {
357 return verdict.Change{}, verdict.Snapshot{}, land, fmt.Errorf("%s and %s share no history", verdict.Short(r.head), r.target)
358 }
359 done = watch.stage(stageEvidence)
360 attested, err := in.treeDigest(wt, r.head)
361 if err != nil {
362 done()
363 return verdict.Change{}, verdict.Snapshot{}, land, err
364 }
365 ch := verdict.Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested}
366 ch.Evidence, land.notes, err = in.collectEvidence(wt, r.head, attested)
367 done()
368 if err != nil {
369 return ch, verdict.Snapshot{}, land, err
370 }
371
372 // The policy is read from the integrator's own side and never from the
373 // tree being gated: the project layer from this checkout of the target
374 // tip, the floor from the instance repository's integrated tip. Both
375 // are resolved once and held for the whole pass: the floor as the
376 // copy the pass's inputs were read from.
377 done = watch.stage(stagePolicy)
378 source := in.policy
379 source.layer = composed.Floor{Path: floor}
380 pol, closePolicy, err := source.open(wt)
381 if err != nil {
382 done()
383 return ch, verdict.Snapshot{}, land, err
384 }
385 defer closePolicy()
386 land.composition = pol.note
387 cat, policyDigest, err := pol.catalogue()
388 if err != nil {
389 done()
390 return ch, verdict.Snapshot{}, land, err
391 }
392 land.policy = policyDigest
393 derived, err := pol.derive(wt, base, r.head)
394 if err != nil {
395 done()
396 return ch, verdict.Snapshot{}, land, err
397 }
398 required, err := pol.required(derived, cat)
399 done()
400 if err != nil {
401 return ch, verdict.Snapshot{}, land, err
402 }
403
404 snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
405
406 // Apply the delta. Every change lands as one commit that the integrator
407 // writes on the tip, whatever its base. None of the head's own commits
408 // reaches the target, so nothing lands that review did not show. When
409 // the base is already the tip, the candidate's tree is the head's tree,
410 // which is the attested tree.
411 if base == tip {
412 done = watch.stage(stageApply)
413 tree, err := gitLine(in.repo, "rev-parse", "--verify", r.head+"^{tree}")
414 if err == nil {
415 land.commit, err = in.commitTree(tree, tip, r)
416 }
417 done()
418 if err != nil {
419 return ch, snap, land, err
420 }
421 land.digest = attested
422 snap.Apply = verdict.Applied{Clean: true, Tree: attested}
423 } else {
424 done = watch.stage(stageApply)
425 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
426 if err != nil {
427 done()
428 return ch, snap, land, err
429 }
430 if conflict != "" {
431 done()
432 snap.Apply = verdict.Applied{Clean: false, Conflict: conflict}
433 return ch, snap, land, nil
434 }
435 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
436 done()
437 return ch, snap, land, err
438 }
439 land.digest, err = in.treeDigest(wt, tree)
440 done()
441 if err != nil {
442 return ch, snap, land, err
443 }
444 snap.Apply = verdict.Applied{Clean: true, Tree: land.digest}
445
446 // What intervening landings touched, in the policy's own terms:
447 // the classes the deriver matches over base..tip. Asking the
448 // deriver rather than matching globs here keeps one implementation
449 // of what a class covers.
450 done = watch.stage(stagePolicy)
451 intervening, err := pol.derive(wt, base, tip)
452 done()
453 if err != nil {
454 return ch, snap, land, err
455 }
456 snap.Touched = intervening.classes
457 }
458
459 // The closures only have to be recomputed when the tree moved: an
460 // unmoved tree presents the identical computation by construction.
461 if land.digest != attested {
462 done = watch.stage(stageClosures)
463 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
464 done()
465 }
466 return ch, snap, land, nil
467}
468
469// committerEmail is the address on the commits the integrator makes. git
470// wants an address and there is none to give: the integrator is a service,
471// not a correspondent. .invalid never resolves, which says so in the address
472// itself. Which integrator committed is carried by the name beside it.
473const committerEmail = "integrator@the-valley.invalid"
474
475// commitTree writes the candidate commit for the change's tree with the tip
476// as its only parent. The ref write is then a fast-forward, and the change's
477// authorship comes from its head.
478//
479// Both identities are stated here rather than left to git. The author is the
480// asker's, because re-parenting a delta is not authoring it. The committer is
481// the integrator, under the name it signs its transfer statement with: the
482// commit and the statement about it then name the same actor. Leaving either
483// to git would ask git to guess an identity from the environment, and under
484// the unit there is nothing to guess from — which is a landing that fails for
485// a reason that has nothing to do with the change.
486func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
487 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
488 if err != nil {
489 return "", err
490 }
491 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
492 if err != nil {
493 return "", err
494 }
495 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
496 if len(fields) != 3 {
497 return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head))
498 }
499 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
500 // The committer date is the author's, so that the commit id is a function
501 // of what the pass decided from — the tree, the tip, the message and the
502 // authorship — and of nothing else. A pass that dies between here and the
503 // ref write recomputes the identical commit next time round instead of
504 // leaving another unreferenced one behind. Nothing reads this date: when
505 // the landing happened is recorded, signed, in the transfer statement.
506 out, err := in.gitEnv(map[string]string{
507 "GIT_AUTHOR_NAME": fields[0],
508 "GIT_AUTHOR_EMAIL": fields[1],
509 "GIT_AUTHOR_DATE": fields[2],
510 "GIT_COMMITTER_NAME": in.signerName,
511 "GIT_COMMITTER_EMAIL": committerEmail,
512 "GIT_COMMITTER_DATE": fields[2],
513 }, cmd...)
514 return strings.TrimSpace(out), err
515}
516
517// land moves the protected ref and records the landing, in one ref
518// transaction, and then says so on the bus. The transaction compares the
519// target against the tip the verdict was computed over, so a request that
520// lost a race to another lands nothing and is judged again next pass
521// against the tip that won.
522//
523// Everything that can fail happens before the transaction. Composing the
524// transfer statement — vetting it, writing it down, signing it — is part
525// of deciding: a claim the integrator cannot write down is a claim it has
526// not made. Then every object the landing records is built: the evidence
527// trees with the transfer statement, the landing record and the outcome
528// record. The transaction is the commit point. It moves the target, moves
529// every evidence and record ref from the value it was read at, and deletes
530// the request, all or nothing. So no landing exists that its records do
531// not name, and a failure before the commit point leaves the stream and
532// the request where they were, which costs one pass to redo.
533//
534// When the transaction fails because a ref moved since it was read,
535// nothing changed. A target that moved means nothing lands. A record ref
536// that moved is read again, the objects are built again from what it
537// holds, and the transaction is tried again, landingTries times in all.
538//
539// Past the commit point what is left is handing the ref move to the host
540// to publish, and the bus events. Both are notices of what the
541// transaction recorded, and a failure of either is reported and changes
542// nothing.
543func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing, memo string, watch *stopwatch) (verdict.Outcome, error) {
544 done := watch.stage(stageSign)
545 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
546 if err != nil {
547 done()
548 return "", err
549 }
550 evidence, err := in.countersign(ch, v, l, transfer)
551 done()
552 if err != nil {
553 return "", err
554 }
555
556 // Judging and signing can take minutes, and a change can be unreadied
557 // or withdrawn meanwhile, or a record can come to name a commit this
558 // request brings. So every record is read again here, as the last
559 // thing before the commit point, and a refusal lands nothing. A record
560 // written between this read and the transaction is still missed: a
561 // transaction can compare refs it knows of, and a record created since
562 // is one it does not. What lands then is still the head the operator
563 // approved.
564 done = watch.stage(stageRefusal)
565 outcome, why, err := in.finalRefusal(r, tip)
566 done()
567 if err != nil || outcome != "" {
568 if outcome != "" {
569 in.reportRefusal(r, tip, outcome, why)
570 }
571 return outcome, err
572 }
573
574 var tx transaction
575 for try := 1; ; try++ {
576 done = watch.stage(stageRecord)
577 tx, err = in.prepareLanding(ch, r, tip, l, evidence, memo)
578 done()
579 if err != nil {
580 return "", fmt.Errorf("nothing landed: %w", err)
581 }
582 // The commit point.
583 done = watch.stage(stageLand)
584 err = in.apply(tx.updates)
585 done()
586 if err == nil {
587 break
588 }
589 if now, found, rerr := resolveRef(in.repo, ch.Target); rerr == nil && (!found || now != tip) {
590 return "", fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
591 }
592 if try == landingTries {
593 return "", fmt.Errorf("nothing landed: a ref the landing records moved under each of %d tries: %w", landingTries, err)
594 }
595 }
596 in.landings++
597 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit))
598 for _, ref := range tx.evidence {
599 fmt.Fprintf(in.out, " evidence %s\n", ref)
600 }
601 fmt.Fprintf(in.out, " record %s\n", tx.landing)
602 if tx.requestNow != "" {
603 fmt.Fprintf(in.out, " request %s moved to %s while %s landed; it stands for the next pass\n",
604 r.ref, verdict.Short(tx.requestNow), verdict.Short(r.head))
605 }
606
607 // The notices come last, as best effort: a queue or a bus that fails
608 // or hangs changes nothing the transaction recorded. The local marks
609 // come first of them, the worker's and then the floor readers': each
610 // is one local file, and a mirror or a bus that hangs must not hold
611 // them back.
612 done = watch.stage(stagePublish)
613 in.markDue()
614 in.markFloorReaders(ch.Target)
615 in.queueRefUpdate(ch.Target, tip, l.commit)
616 in.publishRefUpdated(ch.Target, tip, l.commit)
617 in.publishLanded(ch, v, tip, l.commit)
618 done()
619 return "", nil
620}
621
622// refUpdate is one ref a transaction moves: from old to new, where old is
623// the zero object ID for a ref that must not exist yet, and new is "" for
624// a ref the transaction deletes.
625type refUpdate struct {
626 ref, new, old string
627}
628
629// transaction is a landing's ref transaction, and what it records.
630type transaction struct {
631 updates []refUpdate
632 evidence []string // the evidence refs it moves, in order
633 landing string // the landing record's ref
634
635 // requestNow is the head the request names, when it no longer names
636 // the head that lands: a second approval replaced it while this pass
637 // worked. It is a new request, and it stands for the next pass.
638 requestNow string
639}
640
641// prepareLanding builds every object a landing records and the ref
642// transaction that applies them: the target moved from the tip to the
643// landed commit; each evidence ref moved to its new tree; the landing
644// record for the head; the outcome record, which says land after memo;
645// and the request deleted. Every ref but the target is read here, and the
646// transaction compares it against the value read.
647//
648// The request is deleted only while it names the head that lands. A
649// delete that did not compare would take a second approval, filed while
650// this pass worked, with the first. A request that is gone is not
651// deleted, and a request that moved is left standing.
652func (in *integrator) prepareLanding(ch verdict.Change, r request, tip string, l landing, e landedEvidence, memo string) (transaction, error) {
653 zero := strings.Repeat("0", len(tip))
654 read := func(ref string) (string, error) {
655 oid, found, err := resolveRef(in.repo, ref)
656 if !found && err == nil {
657 oid = zero
658 }
659 return oid, err
660 }
661 tx := transaction{updates: []refUpdate{{ref: ch.Target, new: l.commit, old: tip}}}
662 evidence, err := in.evidenceUpdates(e, zero)
663 if err != nil {
664 return tx, err
665 }
666 for _, u := range evidence {
667 tx.updates = append(tx.updates, u)
668 tx.evidence = append(tx.evidence, u.ref)
669 }
670
671 record, err := in.landingRecord(r, l.commit)
672 if err != nil {
673 return tx, err
674 }
675 tx.landing = change.LandingRef(strings.TrimPrefix(r.target, "refs/heads/"), r.head)
676 old, err := read(tx.landing)
677 if err != nil {
678 return tx, err
679 }
680 tx.updates = append(tx.updates, refUpdate{ref: tx.landing, new: record, old: old})
681
682 outcome, err := in.writeBlob([]byte(memo + " " + string(verdict.Land) + "\n"))
683 if err != nil {
684 return tx, err
685 }
686 if old, err = read(in.memoRef(r)); err != nil {
687 return tx, err
688 }
689 tx.updates = append(tx.updates, refUpdate{ref: in.memoRef(r), new: outcome, old: old})
690
691 now, found, err := resolveRef(in.repo, r.ref)
692 switch {
693 case err != nil:
694 return tx, err
695 case found && now == r.head:
696 tx.updates = append(tx.updates, refUpdate{ref: r.ref, old: r.head})
697 case found:
698 tx.requestNow = now
699 }
700 return tx, nil
701}
702
703// landingRecord writes the commit of the landing record for r's head
704// landing as commit (change.Landing): a commit with no parent whose tree
705// holds the one file change.LandingFile. Its author and committer are the
706// integrator, at the landed commit's committer date, so a pass that builds
707// the record again builds the identical commit.
708func (in *integrator) landingRecord(r request, commit string) (string, error) {
709 file := change.Landing{Landed: commit, Request: r.change, Head: r.head}.Format()
710 blob, err := in.writeBlob(file)
711 if err != nil {
712 return "", err
713 }
714 tree, err := in.writeTree(map[string]string{change.LandingFile: blob})
715 if err != nil {
716 return "", err
717 }
718 date, err := gitLine(in.repo, "log", "-1", "--format=%cI", commit)
719 if err != nil {
720 return "", err
721 }
722 out, err := in.gitEnv(map[string]string{
723 "GIT_AUTHOR_NAME": in.signerName,
724 "GIT_AUTHOR_EMAIL": committerEmail,
725 "GIT_AUTHOR_DATE": date,
726 "GIT_COMMITTER_NAME": in.signerName,
727 "GIT_COMMITTER_EMAIL": committerEmail,
728 "GIT_COMMITTER_DATE": date,
729 }, "commit-tree", tree, "-m", fmt.Sprintf("%s landed as %s", r.change, commit))
730 return strings.TrimSpace(out), err
731}
732
733// apply makes the ref updates as one transaction, with git update-ref
734// --stdin: every ref is locked and compared against its old value first,
735// and then all of them move, or, when any old value does not match, none.
736func (in *integrator) apply(updates []refUpdate) error {
737 var stdin strings.Builder
738 stdin.WriteString("start\n")
739 for _, u := range updates {
740 if u.new == "" {
741 fmt.Fprintf(&stdin, "delete %s %s\n", u.ref, u.old)
742 continue
743 }
744 fmt.Fprintf(&stdin, "update %s %s %s\n", u.ref, u.new, u.old)
745 }
746 stdin.WriteString("prepare\ncommit\n")
747 _, err := gitInput(in.repo, []byte(stdin.String()), "update-ref", "--stdin")
748 return err
749}
750
751// report prints the verdict, per check, in the order it was judged.
752func (in *integrator) report(r request, tip string, v verdict.Verdict) {
753 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome)
754 fmt.Fprintf(in.out, " %s\n", v.Reason)
755 for _, cv := range v.Checks {
756 if cv.Transferred {
757 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
758 continue
759 }
760 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
761 }
762}
763
764// The memo is the level-trigger's memory: what this integrator last decided
765// about a request, keyed by the request. It is durable in git like
766// everything else the transport reads, so a restarted controller does not
767// re-announce a judgement it has already made.
768func (in *integrator) memoRef(r request) string {
769 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
770}
771
772// readMemo reads the memo of a request, or "" when it has none. The memo
773// ref is read by its exact name, so a tag or branch named like a missing
774// memo is no memo.
775func (in *integrator) readMemo(r request) (string, error) {
776 oid, ok, err := resolveRef(in.repo, in.memoRef(r))
777 if err != nil || !ok {
778 return "", err
779 }
780 out, ok := gitTry(in.repo, "cat-file", "blob", oid)
781 if !ok {
782 return "", nil
783 }
784 return strings.TrimSpace(out), nil
785}
786
787func (in *integrator) writeMemo(r request, value string) error {
788 blob, err := in.writeBlob([]byte(value + "\n"))
789 if err != nil {
790 return err
791 }
792 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
793 return err
794}
795
796// evidenceState digests the attestation namespace: every ref under it and
797// the object it points at, as change.EvidenceFingerprint reads them.
798// Attestation refs are create-only, so this moves exactly when evidence
799// arrives.
800//
801// It is deliberately the whole namespace rather than the refs for one
802// change's subject digest, which would take a checkout to compute and would
803// have to be recomputed before the memo could rule the work out. So an
804// attestation for one change re-judges every pending request. That is the
805// conservative direction — a pass that runs and changes nothing costs a
806// pass; a verdict never revisited strands a change — and it is bounded by
807// the number of requests pending.
808func (in *integrator) evidenceState() (string, error) {
809 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix)
810 if err != nil {
811 return "", err
812 }
813 var lines []string
814 if out = strings.TrimSuffix(out, "\n"); out != "" {
815 lines = strings.Split(out, "\n")
816 }
817 return change.EvidenceFingerprint(lines), nil
818}
819
820func (in *integrator) now() time.Time {
821 if !in.clock.IsZero() {
822 return in.clock
823 }
824 return time.Now().UTC()
825}