gunk-dev/the-valley

refs.go

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