gunk-dev/the-valley

refs.go

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