gunk-dev/the-valley

refs.go

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