gunk-dev/the-valley

refs.go

sourceb8e46aa6aaccmain's published tip history
31.8 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 // direct are the attestations stored for the landing tree itself, by
344 // check name, read only when that tree is not the attested tree.
345 direct map[string][]byte
346}
347
348// materialize gathers everything the verdict is a function of: the applied
349// delta, the required checks, the recomputed closures, and what intervening
350// landings touched. The floor is read from floor, the directory the pass
351// took its inputs digest over.
352func (in *integrator) materialize(r request, tip, floor string, watch *stopwatch) (verdict.Change, verdict.Snapshot, landing, error) {
353 var land landing
354 done := watch.stage(stageCheckout)
355 wt, err := addWorktree(in.repo, tip)
356 done()
357 if err != nil {
358 return verdict.Change{}, verdict.Snapshot{}, land, err
359 }
360 defer wt.remove()
361
362 base, err := gitLine(in.repo, "merge-base", tip, r.head)
363 if err != nil {
364 return verdict.Change{}, verdict.Snapshot{}, land, fmt.Errorf("%s and %s share no history", verdict.Short(r.head), r.target)
365 }
366 done = watch.stage(stageEvidence)
367 attested, err := in.treeDigest(wt, r.head)
368 if err != nil {
369 done()
370 return verdict.Change{}, verdict.Snapshot{}, land, err
371 }
372 ch := verdict.Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested}
373 ch.Evidence, land.notes, err = in.collectEvidence(wt, r.head, attested)
374 done()
375 if err != nil {
376 return ch, verdict.Snapshot{}, land, err
377 }
378
379 // The policy is read from the integrator's own side and never from the
380 // tree being gated: the project layer from the target tip, the floor
381 // from the instance repository's integrated tip. Both are resolved
382 // and composed once for this request, and the one model is what every
383 // derivation below and the landing's policy digest are of.
384 done = watch.stage(stagePolicy)
385 source := in.policy
386 source.layer = composed.Floor{Path: floor}
387 pol, closePolicy, err := source.open(wt)
388 if err != nil {
389 done()
390 return ch, verdict.Snapshot{}, land, err
391 }
392 defer closePolicy()
393 land.composition = pol.note
394 land.policy = pol.model.Digest
395 derived, err := pol.derive(wt, base, r.head)
396 if err != nil {
397 done()
398 return ch, verdict.Snapshot{}, land, err
399 }
400 required, err := pol.required(derived)
401 done()
402 if err != nil {
403 return ch, verdict.Snapshot{}, land, err
404 }
405
406 snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
407
408 // Apply the delta. Every change lands as one commit that the integrator
409 // writes on the tip, whatever its base. None of the head's own commits
410 // reaches the target, so nothing lands that review did not show. When
411 // the base is already the tip, the candidate's tree is the head's tree,
412 // which is the attested tree.
413 if base == tip {
414 done = watch.stage(stageApply)
415 tree, err := gitLine(in.repo, "rev-parse", "--verify", r.head+"^{tree}")
416 if err == nil {
417 land.commit, err = in.commitTree(tree, tip, r)
418 }
419 done()
420 if err != nil {
421 return ch, snap, land, err
422 }
423 land.digest = attested
424 snap.Apply = verdict.Applied{Clean: true, Tree: attested}
425 } else {
426 done = watch.stage(stageApply)
427 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
428 if err != nil {
429 done()
430 return ch, snap, land, err
431 }
432 if conflict != "" {
433 done()
434 snap.Apply = verdict.Applied{Clean: false, Conflict: conflict}
435 return ch, snap, land, nil
436 }
437 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
438 done()
439 return ch, snap, land, err
440 }
441 land.digest, err = in.treeDigest(wt, tree)
442 done()
443 if err != nil {
444 return ch, snap, land, err
445 }
446 snap.Apply = verdict.Applied{Clean: true, Tree: land.digest}
447
448 // What intervening landings touched, in the policy's own terms:
449 // the classes the deriver matches over base..tip under the same
450 // model. Asking the deriver rather than matching globs here keeps
451 // one implementation of what a class covers.
452 done = watch.stage(stagePolicy)
453 intervening, err := pol.derive(wt, base, tip)
454 done()
455 if err != nil {
456 return ch, snap, land, err
457 }
458 snap.Touched = intervening.classes
459 }
460
461 // The closures only have to be recomputed when the tree moved: an
462 // unmoved tree presents the identical computation by construction.
463 // A moved tree may also carry evidence of its own, as when a worker
464 // has built the change rebased onto this tip. It is read the way the
465 // change's own is, under the same signers and rules, with the landing
466 // commit as the revision its subject must name.
467 if land.digest != attested {
468 done = watch.stage(stageEvidence)
469 ch.Landed, land.direct, err = in.collectEvidence(wt, land.commit, land.digest)
470 done()
471 if err != nil {
472 return ch, snap, land, err
473 }
474 done = watch.stage(stageClosures)
475 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
476 done()
477 }
478 return ch, snap, land, nil
479}
480
481// committerEmail is the address on the commits the integrator makes. git
482// wants an address and there is none to give: the integrator is a service,
483// not a correspondent. .invalid never resolves, which says so in the address
484// itself. Which integrator committed is carried by the name beside it.
485const committerEmail = "integrator@the-valley.invalid"
486
487// commitTree writes the candidate commit for the change's tree with the tip
488// as its only parent. The ref write is then a fast-forward, and the change's
489// authorship comes from its head.
490//
491// Both identities are stated here rather than left to git. The author is the
492// asker's, because re-parenting a delta is not authoring it. The committer is
493// the integrator, under the name it signs its transfer statement with: the
494// commit and the statement about it then name the same actor. Leaving either
495// to git would ask git to guess an identity from the environment, and under
496// the unit there is nothing to guess from — which is a landing that fails for
497// a reason that has nothing to do with the change.
498func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
499 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
500 if err != nil {
501 return "", err
502 }
503 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
504 if err != nil {
505 return "", err
506 }
507 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
508 if len(fields) != 3 {
509 return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head))
510 }
511 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
512 // The committer date is the author's, so that the commit id is a function
513 // of what the pass decided from — the tree, the tip, the message and the
514 // authorship — and of nothing else. A pass that dies between here and the
515 // ref write recomputes the identical commit next time round instead of
516 // leaving another unreferenced one behind. Nothing reads this date: when
517 // the landing happened is recorded, signed, in the transfer statement.
518 out, err := in.gitEnv(map[string]string{
519 "GIT_AUTHOR_NAME": fields[0],
520 "GIT_AUTHOR_EMAIL": fields[1],
521 "GIT_AUTHOR_DATE": fields[2],
522 "GIT_COMMITTER_NAME": in.signerName,
523 "GIT_COMMITTER_EMAIL": committerEmail,
524 "GIT_COMMITTER_DATE": fields[2],
525 }, cmd...)
526 return strings.TrimSpace(out), err
527}
528
529// land moves the protected ref and records the landing, in one ref
530// transaction, and then says so on the bus. The transaction compares the
531// target against the tip the verdict was computed over, so a request that
532// lost a race to another lands nothing and is judged again next pass
533// against the tip that won.
534//
535// Everything that can fail happens before the transaction. Composing the
536// transfer statement — vetting it, writing it down, signing it — is part
537// of deciding: a claim the integrator cannot write down is a claim it has
538// not made. Then every object the landing records is built: the evidence
539// trees with the transfer statement, the landing record and the outcome
540// record. The transaction is the commit point. It moves the target, moves
541// every evidence and record ref from the value it was read at, and deletes
542// the request, all or nothing. So no landing exists that its records do
543// not name, and a failure before the commit point leaves the stream and
544// the request where they were, which costs one pass to redo.
545//
546// When the transaction fails because a ref moved since it was read,
547// nothing changed. A target that moved means nothing lands. A record ref
548// that moved is read again, the objects are built again from what it
549// holds, and the transaction is tried again, landingTries times in all.
550//
551// Past the commit point what is left is handing the ref move to the host
552// to publish, and the bus events. Both are notices of what the
553// transaction recorded, and a failure of either is reported and changes
554// nothing.
555func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing, memo string, watch *stopwatch) (verdict.Outcome, error) {
556 done := watch.stage(stageSign)
557 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
558 if err != nil {
559 done()
560 return "", err
561 }
562 evidence, err := in.countersign(ch, v, l, transfer)
563 done()
564 if err != nil {
565 return "", err
566 }
567
568 // Judging and signing can take minutes, and a change can be unreadied
569 // or withdrawn meanwhile, or a record can come to name a commit this
570 // request brings. So every record is read again here, as the last
571 // thing before the commit point, and a refusal lands nothing. A record
572 // written between this read and the transaction is still missed: a
573 // transaction can compare refs it knows of, and a record created since
574 // is one it does not. What lands then is still the head the operator
575 // approved.
576 done = watch.stage(stageRefusal)
577 outcome, why, err := in.finalRefusal(r, tip)
578 done()
579 if err != nil || outcome != "" {
580 if outcome != "" {
581 in.reportRefusal(r, tip, outcome, why)
582 }
583 return outcome, err
584 }
585
586 var tx transaction
587 for try := 1; ; try++ {
588 done = watch.stage(stageRecord)
589 tx, err = in.prepareLanding(ch, r, tip, l, evidence, memo)
590 done()
591 if err != nil {
592 return "", fmt.Errorf("nothing landed: %w", err)
593 }
594 // The commit point.
595 done = watch.stage(stageLand)
596 err = in.apply(tx.updates)
597 done()
598 if err == nil {
599 break
600 }
601 if now, found, rerr := resolveRef(in.repo, ch.Target); rerr == nil && (!found || now != tip) {
602 return "", fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
603 }
604 if try == landingTries {
605 return "", fmt.Errorf("nothing landed: a ref the landing records moved under each of %d tries: %w", landingTries, err)
606 }
607 }
608 in.landings++
609 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit))
610 for _, ref := range tx.evidence {
611 fmt.Fprintf(in.out, " evidence %s\n", ref)
612 }
613 fmt.Fprintf(in.out, " record %s\n", tx.landing)
614 if tx.requestNow != "" {
615 fmt.Fprintf(in.out, " request %s moved to %s while %s landed; it stands for the next pass\n",
616 r.ref, verdict.Short(tx.requestNow), verdict.Short(r.head))
617 }
618
619 // The notices come last, as best effort: a queue or a bus that fails
620 // or hangs changes nothing the transaction recorded. The local marks
621 // come first of them, the worker's and then the floor readers': each
622 // is one local file, and a mirror or a bus that hangs must not hold
623 // them back.
624 done = watch.stage(stagePublish)
625 in.markDue()
626 in.markFloorReaders(ch.Target)
627 in.queueRefUpdate(ch.Target, tip, l.commit)
628 in.publishRefUpdated(ch.Target, tip, l.commit)
629 in.publishLanded(ch, v, tip, l.commit)
630 done()
631 return "", nil
632}
633
634// refUpdate is one ref a transaction moves: from old to new, where old is
635// the zero object ID for a ref that must not exist yet, and new is "" for
636// a ref the transaction deletes.
637type refUpdate struct {
638 ref, new, old string
639}
640
641// transaction is a landing's ref transaction, and what it records.
642type transaction struct {
643 updates []refUpdate
644 evidence []string // the evidence refs it moves, in order
645 landing string // the landing record's ref
646
647 // requestNow is the head the request names, when it no longer names
648 // the head that lands: a second approval replaced it while this pass
649 // worked. It is a new request, and it stands for the next pass.
650 requestNow string
651}
652
653// prepareLanding builds every object a landing records and the ref
654// transaction that applies them: the target moved from the tip to the
655// landed commit; each evidence ref moved to its new tree; the landing
656// record for the head; the outcome record, which says land after memo;
657// and the request deleted. Every ref but the target is read here, and the
658// transaction compares it against the value read.
659//
660// The request is deleted only while it names the head that lands. A
661// delete that did not compare would take a second approval, filed while
662// this pass worked, with the first. A request that is gone is not
663// deleted, and a request that moved is left standing.
664func (in *integrator) prepareLanding(ch verdict.Change, r request, tip string, l landing, e landedEvidence, memo string) (transaction, error) {
665 zero := strings.Repeat("0", len(tip))
666 read := func(ref string) (string, error) {
667 oid, found, err := resolveRef(in.repo, ref)
668 if !found && err == nil {
669 oid = zero
670 }
671 return oid, err
672 }
673 tx := transaction{updates: []refUpdate{{ref: ch.Target, new: l.commit, old: tip}}}
674 evidence, err := in.evidenceUpdates(e, zero)
675 if err != nil {
676 return tx, err
677 }
678 for _, u := range evidence {
679 tx.updates = append(tx.updates, u)
680 tx.evidence = append(tx.evidence, u.ref)
681 }
682
683 record, err := in.landingRecord(r, l.commit)
684 if err != nil {
685 return tx, err
686 }
687 tx.landing = change.LandingRef(strings.TrimPrefix(r.target, "refs/heads/"), r.head)
688 old, err := read(tx.landing)
689 if err != nil {
690 return tx, err
691 }
692 tx.updates = append(tx.updates, refUpdate{ref: tx.landing, new: record, old: old})
693
694 outcome, err := in.writeBlob([]byte(memo + " " + string(verdict.Land) + "\n"))
695 if err != nil {
696 return tx, err
697 }
698 if old, err = read(in.memoRef(r)); err != nil {
699 return tx, err
700 }
701 tx.updates = append(tx.updates, refUpdate{ref: in.memoRef(r), new: outcome, old: old})
702
703 now, found, err := resolveRef(in.repo, r.ref)
704 switch {
705 case err != nil:
706 return tx, err
707 case found && now == r.head:
708 tx.updates = append(tx.updates, refUpdate{ref: r.ref, old: r.head})
709 case found:
710 tx.requestNow = now
711 }
712 return tx, nil
713}
714
715// landingRecord writes the commit of the landing record for r's head
716// landing as commit (change.Landing): a commit with no parent whose tree
717// holds the one file change.LandingFile. Its author and committer are the
718// integrator, at the landed commit's committer date, so a pass that builds
719// the record again builds the identical commit.
720func (in *integrator) landingRecord(r request, commit string) (string, error) {
721 file := change.Landing{Landed: commit, Request: r.change, Head: r.head}.Format()
722 blob, err := in.writeBlob(file)
723 if err != nil {
724 return "", err
725 }
726 tree, err := in.writeTree(map[string]string{change.LandingFile: blob})
727 if err != nil {
728 return "", err
729 }
730 date, err := gitLine(in.repo, "log", "-1", "--format=%cI", commit)
731 if err != nil {
732 return "", err
733 }
734 out, err := in.gitEnv(map[string]string{
735 "GIT_AUTHOR_NAME": in.signerName,
736 "GIT_AUTHOR_EMAIL": committerEmail,
737 "GIT_AUTHOR_DATE": date,
738 "GIT_COMMITTER_NAME": in.signerName,
739 "GIT_COMMITTER_EMAIL": committerEmail,
740 "GIT_COMMITTER_DATE": date,
741 }, "commit-tree", tree, "-m", fmt.Sprintf("%s landed as %s", r.change, commit))
742 return strings.TrimSpace(out), err
743}
744
745// apply makes the ref updates as one transaction, with git update-ref
746// --stdin: every ref is locked and compared against its old value first,
747// and then all of them move, or, when any old value does not match, none.
748func (in *integrator) apply(updates []refUpdate) error {
749 var stdin strings.Builder
750 stdin.WriteString("start\n")
751 for _, u := range updates {
752 if u.new == "" {
753 fmt.Fprintf(&stdin, "delete %s %s\n", u.ref, u.old)
754 continue
755 }
756 fmt.Fprintf(&stdin, "update %s %s %s\n", u.ref, u.new, u.old)
757 }
758 stdin.WriteString("prepare\ncommit\n")
759 _, err := gitInput(in.repo, []byte(stdin.String()), "update-ref", "--stdin")
760 return err
761}
762
763// report prints the verdict, per check, in the order it was judged.
764func (in *integrator) report(r request, tip string, v verdict.Verdict) {
765 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome)
766 fmt.Fprintf(in.out, " %s\n", v.Reason)
767 for _, cv := range v.Checks {
768 if cv.Transferred {
769 if cv.Direct {
770 fmt.Fprintf(in.out, " check %-24s transferred (%s, the landing tree's own evidence)\n", cv.Name, cv.Rule)
771 continue
772 }
773 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
774 continue
775 }
776 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
777 }
778}
779
780// The memo is the level-trigger's memory: what this integrator last decided
781// about a request, keyed by the request. It is durable in git like
782// everything else the transport reads, so a restarted controller does not
783// re-announce a judgement it has already made.
784func (in *integrator) memoRef(r request) string {
785 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
786}
787
788// readMemo reads the memo of a request, or "" when it has none. The memo
789// ref is read by its exact name, so a tag or branch named like a missing
790// memo is no memo.
791func (in *integrator) readMemo(r request) (string, error) {
792 oid, ok, err := resolveRef(in.repo, in.memoRef(r))
793 if err != nil || !ok {
794 return "", err
795 }
796 out, ok := gitTry(in.repo, "cat-file", "blob", oid)
797 if !ok {
798 return "", nil
799 }
800 return strings.TrimSpace(out), nil
801}
802
803func (in *integrator) writeMemo(r request, value string) error {
804 blob, err := in.writeBlob([]byte(value + "\n"))
805 if err != nil {
806 return err
807 }
808 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
809 return err
810}
811
812// evidenceState digests the attestation namespace: every ref under it and
813// the object it points at, as change.EvidenceFingerprint reads them.
814// An attestation ref only ever takes added notes, and each one moves its
815// object, so this moves exactly when evidence arrives.
816//
817// It is deliberately the whole namespace rather than the refs for one
818// change's subject digest, which would take a checkout to compute and would
819// have to be recomputed before the memo could rule the work out. So an
820// attestation for one change re-judges every pending request. That is the
821// conservative direction — a pass that runs and changes nothing costs a
822// pass; a verdict never revisited strands a change — and it is bounded by
823// the number of requests pending.
824func (in *integrator) evidenceState() (string, error) {
825 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix)
826 if err != nil {
827 return "", err
828 }
829 var lines []string
830 if out = strings.TrimSuffix(out, "\n"); out != "" {
831 lines = strings.Split(out, "\n")
832 }
833 return change.EvidenceFingerprint(lines), nil
834}
835
836func (in *integrator) now() time.Time {
837 if !in.clock.IsZero() {
838 return in.clock
839 }
840 return time.Now().UTC()
841}