gunk-dev/the-valley

refs.go

source1dfbf0f24992main's published tip history
31.9 KiB
1package main
2
3// The refs transport: a reconciliation loop over the integration requests
4// durable in the served repository.
5//
6// The bus is unauthenticated (bd-d853d9c), which gates automated
7// consumers, and the requests are durable in git with the bus as a
8// projection over them (architecture.md). So the controller level-triggers
9// over the request refs themselves and converges: each pass recomputes the
10// verdict for every request against the current tip, acts only where the
11// answer has changed since the last pass, and needs no subscription at
12// all. It publishes outcomes to the bus exactly as the post-receive hook
13// publishes ref updates. What starts a pass is the controller's start, its
14// interval, and a mark in its own wake directory (wake.go); a mark carries
15// nothing, so a pass decides from the refs alone.
16//
17// # The request ref
18//
19// A request is a ref:
20//
21// refs/the-valley/integration-requests/<target>/<change> -> commit
22//
23// The target segment names the protected branch, so the change's target
24// stream is refs/heads/<target>; the last segment names the change. The
25// commit is the change's head, its tree is what the attestations are over,
26// and the delta is the merge base with the target's tip to that head.
27// Nothing else is encoded: a change is a diff targeting a stream
28// (ida-93e4f91), and every part of that is already in git. A request
29// whose last segment is c-<change ID> is the request of the change with a
30// record under that ID, and the records decide whether it may land at all
31// (records.go).
32
33import (
34 "the-valley/change"
35 "the-valley/composed"
36 "the-valley/integrator/verdict"
37
38 "fmt"
39 "sort"
40 "strings"
41 "time"
42)
43
44const (
45 requestPrefix = "refs/the-valley/integration-requests"
46 outcomePrefix = "refs/the-valley/integration-outcomes"
47)
48
49// landingTries is how many times a landing builds its ref transaction and
50// applies it, while what fails it is a record ref that moved since it was
51// read. A record ref moves under a landing only when something other than
52// this pass writes it, such as a push creating an attestation ref the
53// landing adds to.
54const landingTries = 3
55
56// request is one integration request as the refs transport found it.
57type request struct {
58 ref string
59 change string
60 target string
61 head string
62}
63
64// requests lists the pending requests, in ref order so a pass is
65// deterministic, along with the refs under the namespace that are not
66// requests at all.
67//
68// Any holder of the approve grant can write this namespace, and anyone at all
69// where a repository is served without the pre-receive hook, so a name that
70// does not parse is an ordinary thing to find there and not a reason to stop: one
71// unreadable ref must not hold up every readable one. It is reported and
72// skipped.
73func (in *integrator) requests() ([]request, []string, error) {
74 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", requestPrefix)
75 if err != nil {
76 return nil, nil, err
77 }
78 var found []request
79 var malformed []string
80 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
81 if line == "" {
82 continue
83 }
84 ref, head, ok := strings.Cut(line, " ")
85 if !ok {
86 continue
87 }
88 rest := strings.TrimPrefix(ref, requestPrefix+"/")
89 target, change, ok := strings.Cut(rest, "/")
90 if !ok || strings.Contains(change, "/") || target == "" || change == "" {
91 malformed = append(malformed, ref)
92 continue
93 }
94 found = append(found, request{ref: ref, change: change, target: "refs/heads/" + target, head: head})
95 }
96 sort.Slice(found, func(i, j int) bool { return found[i].ref < found[j].ref })
97 sort.Strings(malformed)
98 return found, malformed, nil
99}
100
101// reconcile is one pass: judge every request against the current tip of its
102// target, and act where the answer has changed.
103//
104// The change records are read once, before any request is judged. A pass
105// that cannot read them judges nothing: which heads are versions of
106// changes that are not ready is what keeps those heads from landing. The
107// requests a withdrawn change voids are deleted before the rest are
108// judged. 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 this checkout of the target
381 // tip, the floor from the instance repository's integrated tip. Both
382 // are resolved once and held for the whole pass: the floor as the
383 // copy the pass's inputs were read from.
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 cat, policyDigest, err := pol.catalogue()
395 if err != nil {
396 done()
397 return ch, verdict.Snapshot{}, land, err
398 }
399 land.policy = policyDigest
400 derived, err := pol.derive(wt, base, r.head)
401 if err != nil {
402 done()
403 return ch, verdict.Snapshot{}, land, err
404 }
405 required, err := pol.required(derived, cat)
406 done()
407 if err != nil {
408 return ch, verdict.Snapshot{}, land, err
409 }
410
411 snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
412
413 // Apply the delta. Every change lands as one commit that the integrator
414 // writes on the tip, whatever its base. None of the head's own commits
415 // reaches the target, so nothing lands that review did not show. When
416 // the base is already the tip, the candidate's tree is the head's tree,
417 // which is the attested tree.
418 if base == tip {
419 done = watch.stage(stageApply)
420 tree, err := gitLine(in.repo, "rev-parse", "--verify", r.head+"^{tree}")
421 if err == nil {
422 land.commit, err = in.commitTree(tree, tip, r)
423 }
424 done()
425 if err != nil {
426 return ch, snap, land, err
427 }
428 land.digest = attested
429 snap.Apply = verdict.Applied{Clean: true, Tree: attested}
430 } else {
431 done = watch.stage(stageApply)
432 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
433 if err != nil {
434 done()
435 return ch, snap, land, err
436 }
437 if conflict != "" {
438 done()
439 snap.Apply = verdict.Applied{Clean: false, Conflict: conflict}
440 return ch, snap, land, nil
441 }
442 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
443 done()
444 return ch, snap, land, err
445 }
446 land.digest, err = in.treeDigest(wt, tree)
447 done()
448 if err != nil {
449 return ch, snap, land, err
450 }
451 snap.Apply = verdict.Applied{Clean: true, Tree: land.digest}
452
453 // What intervening landings touched, in the policy's own terms:
454 // the classes the deriver matches over base..tip. Asking the
455 // deriver rather than matching globs here keeps one implementation
456 // of what a class covers.
457 done = watch.stage(stagePolicy)
458 intervening, err := pol.derive(wt, base, tip)
459 done()
460 if err != nil {
461 return ch, snap, land, err
462 }
463 snap.Touched = intervening.classes
464 }
465
466 // The closures only have to be recomputed when the tree moved: an
467 // unmoved tree presents the identical computation by construction.
468 // A moved tree may also carry evidence of its own, as when a worker
469 // has built the change rebased onto this tip. It is read the way the
470 // change's own is, under the same signers and rules, with the landing
471 // commit as the revision its subject must name.
472 if land.digest != attested {
473 done = watch.stage(stageEvidence)
474 ch.Landed, land.direct, err = in.collectEvidence(wt, land.commit, land.digest)
475 done()
476 if err != nil {
477 return ch, snap, land, err
478 }
479 done = watch.stage(stageClosures)
480 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
481 done()
482 }
483 return ch, snap, land, nil
484}
485
486// committerEmail is the address on the commits the integrator makes. git
487// wants an address and there is none to give: the integrator is a service,
488// not a correspondent. .invalid never resolves, which says so in the address
489// itself. Which integrator committed is carried by the name beside it.
490const committerEmail = "integrator@the-valley.invalid"
491
492// commitTree writes the candidate commit for the change's tree with the tip
493// as its only parent. The ref write is then a fast-forward, and the change's
494// authorship comes from its head.
495//
496// Both identities are stated here rather than left to git. The author is the
497// asker's, because re-parenting a delta is not authoring it. The committer is
498// the integrator, under the name it signs its transfer statement with: the
499// commit and the statement about it then name the same actor. Leaving either
500// to git would ask git to guess an identity from the environment, and under
501// the unit there is nothing to guess from — which is a landing that fails for
502// a reason that has nothing to do with the change.
503func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
504 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
505 if err != nil {
506 return "", err
507 }
508 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
509 if err != nil {
510 return "", err
511 }
512 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
513 if len(fields) != 3 {
514 return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head))
515 }
516 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
517 // The committer date is the author's, so that the commit id is a function
518 // of what the pass decided from — the tree, the tip, the message and the
519 // authorship — and of nothing else. A pass that dies between here and the
520 // ref write recomputes the identical commit next time round instead of
521 // leaving another unreferenced one behind. Nothing reads this date: when
522 // the landing happened is recorded, signed, in the transfer statement.
523 out, err := in.gitEnv(map[string]string{
524 "GIT_AUTHOR_NAME": fields[0],
525 "GIT_AUTHOR_EMAIL": fields[1],
526 "GIT_AUTHOR_DATE": fields[2],
527 "GIT_COMMITTER_NAME": in.signerName,
528 "GIT_COMMITTER_EMAIL": committerEmail,
529 "GIT_COMMITTER_DATE": fields[2],
530 }, cmd...)
531 return strings.TrimSpace(out), err
532}
533
534// land moves the protected ref and records the landing, in one ref
535// transaction, and then says so on the bus. The transaction compares the
536// target against the tip the verdict was computed over, so a request that
537// lost a race to another lands nothing and is judged again next pass
538// against the tip that won.
539//
540// Everything that can fail happens before the transaction. Composing the
541// transfer statement — vetting it, writing it down, signing it — is part
542// of deciding: a claim the integrator cannot write down is a claim it has
543// not made. Then every object the landing records is built: the evidence
544// trees with the transfer statement, the landing record and the outcome
545// record. The transaction is the commit point. It moves the target, moves
546// every evidence and record ref from the value it was read at, and deletes
547// the request, all or nothing. So no landing exists that its records do
548// not name, and a failure before the commit point leaves the stream and
549// the request where they were, which costs one pass to redo.
550//
551// When the transaction fails because a ref moved since it was read,
552// nothing changed. A target that moved means nothing lands. A record ref
553// that moved is read again, the objects are built again from what it
554// holds, and the transaction is tried again, landingTries times in all.
555//
556// Past the commit point what is left is handing the ref move to the host
557// to publish, and the bus events. Both are notices of what the
558// transaction recorded, and a failure of either is reported and changes
559// nothing.
560func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing, memo string, watch *stopwatch) (verdict.Outcome, error) {
561 done := watch.stage(stageSign)
562 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
563 if err != nil {
564 done()
565 return "", err
566 }
567 evidence, err := in.countersign(ch, v, l, transfer)
568 done()
569 if err != nil {
570 return "", err
571 }
572
573 // Judging and signing can take minutes, and a change can be unreadied
574 // or withdrawn meanwhile, or a record can come to name a commit this
575 // request brings. So every record is read again here, as the last
576 // thing before the commit point, and a refusal lands nothing. A record
577 // written between this read and the transaction is still missed: a
578 // transaction can compare refs it knows of, and a record created since
579 // is one it does not. What lands then is still the head the operator
580 // approved.
581 done = watch.stage(stageRefusal)
582 outcome, why, err := in.finalRefusal(r, tip)
583 done()
584 if err != nil || outcome != "" {
585 if outcome != "" {
586 in.reportRefusal(r, tip, outcome, why)
587 }
588 return outcome, err
589 }
590
591 var tx transaction
592 for try := 1; ; try++ {
593 done = watch.stage(stageRecord)
594 tx, err = in.prepareLanding(ch, r, tip, l, evidence, memo)
595 done()
596 if err != nil {
597 return "", fmt.Errorf("nothing landed: %w", err)
598 }
599 // The commit point.
600 done = watch.stage(stageLand)
601 err = in.apply(tx.updates)
602 done()
603 if err == nil {
604 break
605 }
606 if now, found, rerr := resolveRef(in.repo, ch.Target); rerr == nil && (!found || now != tip) {
607 return "", fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
608 }
609 if try == landingTries {
610 return "", fmt.Errorf("nothing landed: a ref the landing records moved under each of %d tries: %w", landingTries, err)
611 }
612 }
613 in.landings++
614 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit))
615 for _, ref := range tx.evidence {
616 fmt.Fprintf(in.out, " evidence %s\n", ref)
617 }
618 fmt.Fprintf(in.out, " record %s\n", tx.landing)
619 if tx.requestNow != "" {
620 fmt.Fprintf(in.out, " request %s moved to %s while %s landed; it stands for the next pass\n",
621 r.ref, verdict.Short(tx.requestNow), verdict.Short(r.head))
622 }
623
624 // The notices come last, as best effort: a queue or a bus that fails
625 // or hangs changes nothing the transaction recorded. The local marks
626 // come first of them, the worker's and then the floor readers': each
627 // is one local file, and a mirror or a bus that hangs must not hold
628 // them back.
629 done = watch.stage(stagePublish)
630 in.markDue()
631 in.markFloorReaders(ch.Target)
632 in.queueRefUpdate(ch.Target, tip, l.commit)
633 in.publishRefUpdated(ch.Target, tip, l.commit)
634 in.publishLanded(ch, v, tip, l.commit)
635 done()
636 return "", nil
637}
638
639// refUpdate is one ref a transaction moves: from old to new, where old is
640// the zero object ID for a ref that must not exist yet, and new is "" for
641// a ref the transaction deletes.
642type refUpdate struct {
643 ref, new, old string
644}
645
646// transaction is a landing's ref transaction, and what it records.
647type transaction struct {
648 updates []refUpdate
649 evidence []string // the evidence refs it moves, in order
650 landing string // the landing record's ref
651
652 // requestNow is the head the request names, when it no longer names
653 // the head that lands: a second approval replaced it while this pass
654 // worked. It is a new request, and it stands for the next pass.
655 requestNow string
656}
657
658// prepareLanding builds every object a landing records and the ref
659// transaction that applies them: the target moved from the tip to the
660// landed commit; each evidence ref moved to its new tree; the landing
661// record for the head; the outcome record, which says land after memo;
662// and the request deleted. Every ref but the target is read here, and the
663// transaction compares it against the value read.
664//
665// The request is deleted only while it names the head that lands. A
666// delete that did not compare would take a second approval, filed while
667// this pass worked, with the first. A request that is gone is not
668// deleted, and a request that moved is left standing.
669func (in *integrator) prepareLanding(ch verdict.Change, r request, tip string, l landing, e landedEvidence, memo string) (transaction, error) {
670 zero := strings.Repeat("0", len(tip))
671 read := func(ref string) (string, error) {
672 oid, found, err := resolveRef(in.repo, ref)
673 if !found && err == nil {
674 oid = zero
675 }
676 return oid, err
677 }
678 tx := transaction{updates: []refUpdate{{ref: ch.Target, new: l.commit, old: tip}}}
679 evidence, err := in.evidenceUpdates(e, zero)
680 if err != nil {
681 return tx, err
682 }
683 for _, u := range evidence {
684 tx.updates = append(tx.updates, u)
685 tx.evidence = append(tx.evidence, u.ref)
686 }
687
688 record, err := in.landingRecord(r, l.commit)
689 if err != nil {
690 return tx, err
691 }
692 tx.landing = change.LandingRef(strings.TrimPrefix(r.target, "refs/heads/"), r.head)
693 old, err := read(tx.landing)
694 if err != nil {
695 return tx, err
696 }
697 tx.updates = append(tx.updates, refUpdate{ref: tx.landing, new: record, old: old})
698
699 outcome, err := in.writeBlob([]byte(memo + " " + string(verdict.Land) + "\n"))
700 if err != nil {
701 return tx, err
702 }
703 if old, err = read(in.memoRef(r)); err != nil {
704 return tx, err
705 }
706 tx.updates = append(tx.updates, refUpdate{ref: in.memoRef(r), new: outcome, old: old})
707
708 now, found, err := resolveRef(in.repo, r.ref)
709 switch {
710 case err != nil:
711 return tx, err
712 case found && now == r.head:
713 tx.updates = append(tx.updates, refUpdate{ref: r.ref, old: r.head})
714 case found:
715 tx.requestNow = now
716 }
717 return tx, nil
718}
719
720// landingRecord writes the commit of the landing record for r's head
721// landing as commit (change.Landing): a commit with no parent whose tree
722// holds the one file change.LandingFile. Its author and committer are the
723// integrator, at the landed commit's committer date, so a pass that builds
724// the record again builds the identical commit.
725func (in *integrator) landingRecord(r request, commit string) (string, error) {
726 file := change.Landing{Landed: commit, Request: r.change, Head: r.head}.Format()
727 blob, err := in.writeBlob(file)
728 if err != nil {
729 return "", err
730 }
731 tree, err := in.writeTree(map[string]string{change.LandingFile: blob})
732 if err != nil {
733 return "", err
734 }
735 date, err := gitLine(in.repo, "log", "-1", "--format=%cI", commit)
736 if err != nil {
737 return "", err
738 }
739 out, err := in.gitEnv(map[string]string{
740 "GIT_AUTHOR_NAME": in.signerName,
741 "GIT_AUTHOR_EMAIL": committerEmail,
742 "GIT_AUTHOR_DATE": date,
743 "GIT_COMMITTER_NAME": in.signerName,
744 "GIT_COMMITTER_EMAIL": committerEmail,
745 "GIT_COMMITTER_DATE": date,
746 }, "commit-tree", tree, "-m", fmt.Sprintf("%s landed as %s", r.change, commit))
747 return strings.TrimSpace(out), err
748}
749
750// apply makes the ref updates as one transaction, with git update-ref
751// --stdin: every ref is locked and compared against its old value first,
752// and then all of them move, or, when any old value does not match, none.
753func (in *integrator) apply(updates []refUpdate) error {
754 var stdin strings.Builder
755 stdin.WriteString("start\n")
756 for _, u := range updates {
757 if u.new == "" {
758 fmt.Fprintf(&stdin, "delete %s %s\n", u.ref, u.old)
759 continue
760 }
761 fmt.Fprintf(&stdin, "update %s %s %s\n", u.ref, u.new, u.old)
762 }
763 stdin.WriteString("prepare\ncommit\n")
764 _, err := gitInput(in.repo, []byte(stdin.String()), "update-ref", "--stdin")
765 return err
766}
767
768// report prints the verdict, per check, in the order it was judged.
769func (in *integrator) report(r request, tip string, v verdict.Verdict) {
770 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome)
771 fmt.Fprintf(in.out, " %s\n", v.Reason)
772 for _, cv := range v.Checks {
773 if cv.Transferred {
774 if cv.Direct {
775 fmt.Fprintf(in.out, " check %-24s transferred (%s, the landing tree's own evidence)\n", cv.Name, cv.Rule)
776 continue
777 }
778 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
779 continue
780 }
781 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
782 }
783}
784
785// The memo is the level-trigger's memory: what this integrator last decided
786// about a request, keyed by the request. It is durable in git like
787// everything else the transport reads, so a restarted controller does not
788// re-announce a judgement it has already made.
789func (in *integrator) memoRef(r request) string {
790 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
791}
792
793// readMemo reads the memo of a request, or "" when it has none. The memo
794// ref is read by its exact name, so a tag or branch named like a missing
795// memo is no memo.
796func (in *integrator) readMemo(r request) (string, error) {
797 oid, ok, err := resolveRef(in.repo, in.memoRef(r))
798 if err != nil || !ok {
799 return "", err
800 }
801 out, ok := gitTry(in.repo, "cat-file", "blob", oid)
802 if !ok {
803 return "", nil
804 }
805 return strings.TrimSpace(out), nil
806}
807
808func (in *integrator) writeMemo(r request, value string) error {
809 blob, err := in.writeBlob([]byte(value + "\n"))
810 if err != nil {
811 return err
812 }
813 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
814 return err
815}
816
817// evidenceState digests the attestation namespace: every ref under it and
818// the object it points at, as change.EvidenceFingerprint reads them.
819// Attestation refs are create-only, so this moves exactly when evidence
820// arrives.
821//
822// It is deliberately the whole namespace rather than the refs for one
823// change's subject digest, which would take a checkout to compute and would
824// have to be recomputed before the memo could rule the work out. So an
825// attestation for one change re-judges every pending request. That is the
826// conservative direction — a pass that runs and changes nothing costs a
827// pass; a verdict never revisited strands a change — and it is bounded by
828// the number of requests pending.
829func (in *integrator) evidenceState() (string, error) {
830 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix)
831 if err != nil {
832 return "", err
833 }
834 var lines []string
835 if out = strings.TrimSuffix(out, "\n"); out != "" {
836 lines = strings.Split(out, "\n")
837 }
838 return change.EvidenceFingerprint(lines), nil
839}
840
841func (in *integrator) now() time.Time {
842 if !in.clock.IsZero() {
843 return in.clock
844 }
845 return time.Now().UTC()
846}