gunk-dev/the-valley

refs.go

source71e69b2e4721main's published tip history
22.0 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/integrator/verdict"
34
35 "fmt"
36 "sort"
37 "strings"
38 "time"
39)
40
41const (
42 requestPrefix = "refs/the-valley/integration-requests"
43 outcomePrefix = "refs/the-valley/integration-outcomes"
44)
45
46// request is one integration request as the refs transport found it.
47type request struct {
48 ref string
49 change string
50 target string
51 head string
52}
53
54// requests lists the pending requests, in ref order so a pass is
55// deterministic, along with the refs under the namespace that are not
56// requests at all.
57//
58// Any holder of the request grant can write this namespace, and anyone at all
59// where a repository is served without the pre-receive hook, so a name that
60// does not parse is an ordinary thing to find there and not a reason to stop: one
61// unreadable ref must not hold up every readable one. It is reported and
62// skipped.
63func (in *integrator) requests() ([]request, []string, error) {
64 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", requestPrefix)
65 if err != nil {
66 return nil, nil, err
67 }
68 var found []request
69 var malformed []string
70 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
71 if line == "" {
72 continue
73 }
74 ref, head, ok := strings.Cut(line, " ")
75 if !ok {
76 continue
77 }
78 rest := strings.TrimPrefix(ref, requestPrefix+"/")
79 target, change, ok := strings.Cut(rest, "/")
80 if !ok || strings.Contains(change, "/") || target == "" || change == "" {
81 malformed = append(malformed, ref)
82 continue
83 }
84 found = append(found, request{ref: ref, change: change, target: "refs/heads/" + target, head: head})
85 }
86 sort.Slice(found, func(i, j int) bool { return found[i].ref < found[j].ref })
87 sort.Strings(malformed)
88 return found, malformed, nil
89}
90
91// reconcile is one pass: judge every request against the current tip of its
92// target, and act where the answer has changed.
93//
94// The change records are read once, before any request is judged. A pass
95// that cannot read them judges nothing: which heads are versions of
96// changes that are not ready is what keeps those heads from landing.
97func (in *integrator) reconcile() error {
98 requests, malformed, err := in.requests()
99 if err != nil {
100 return err
101 }
102 for _, ref := range malformed {
103 fmt.Fprintf(in.out, "%s: not a request ref; one is %s/<target>/<change>. Skipped.\n", ref, requestPrefix)
104 }
105 if len(requests) == 0 {
106 return nil
107 }
108 idx, err := in.readRecords()
109 if err != nil {
110 return err
111 }
112 for _, why := range idx.unreadable {
113 fmt.Fprintf(in.out, "%s. It refuses nothing.\n", why)
114 }
115 for _, r := range requests {
116 if err := in.handle(r, idx); err != nil {
117 // One bad request must not stop the pass: the integrator is a
118 // controller, and a request it cannot judge is one request's
119 // problem.
120 fmt.Fprintf(in.out, "%s: %v\n", r.change, err)
121 }
122 }
123 return nil
124}
125
126// handle judges one request and acts on the verdict.
127func (in *integrator) handle(r request, idx *recordIndex) error {
128 tip, err := gitLine(in.repo, "rev-parse", "--verify", "--quiet", r.target)
129 if err != nil {
130 return fmt.Errorf("no target %s to integrate onto", r.target)
131 }
132 // Level-triggering: the verdict is a function of the request's head,
133 // the target's tip, and the evidence stored for the change, so an
134 // unchanged answer is one where none of the three has moved.
135 // Re-announcing an unchanged answer would be a retry storm; missing a
136 // moved one would strand a contributor who pushed the attestation a
137 // previous pass said was absent.
138 evidence, err := in.evidenceState()
139 if err != nil {
140 return err
141 }
142 memo := fmt.Sprintf("%s %s %s", r.head, tip, evidence)
143 last, err := in.readMemo(r)
144 if err != nil {
145 return err
146 }
147 if in.answered(last, memo) {
148 return nil
149 }
150 // From here on the request has been taken up, so whatever happens is
151 // this pass's answer to it — including a failure. Recording that is
152 // what keeps the next tick from asking the identical question.
153 outcome, err := in.refuse(r, idx, tip, last, memo)
154 if err == nil && outcome == "" {
155 outcome, err = in.act(r, idx, tip)
156 }
157 if err != nil {
158 if memoErr := in.writeMemo(r, memo+" "+failedMemo+" "+in.now().Format(time.RFC3339)); memoErr != nil {
159 return fmt.Errorf("%v (and the failure could not be recorded: %v)", err, memoErr)
160 }
161 return err
162 }
163 if last == memo+" "+string(outcome) {
164 return nil
165 }
166 return in.writeMemo(r, memo+" "+string(outcome))
167}
168
169// refuse applies the rules that refuse a request before it is judged
170// (records.go), and reports a refusal. It reports one only when it is new:
171// a refusal is decided again on every pass, and saying the same one every
172// tick would bury it.
173func (in *integrator) refuse(r request, idx *recordIndex, tip, last, memo string) (verdict.Outcome, error) {
174 outcome, why, err := in.recordRefusal(r, idx, false)
175 if err == nil && outcome == "" {
176 outcome, why, err = in.mergeRefusal(r, tip)
177 }
178 if err != nil || outcome == "" {
179 return "", err
180 }
181 if last != memo+" "+string(outcome) {
182 in.reportRefusal(r, tip, outcome, why)
183 }
184 return outcome, nil
185}
186
187// reportRefusal prints a refusal the way report prints a verdict.
188func (in *integrator) reportRefusal(r request, tip string, outcome verdict.Outcome, why string) {
189 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), outcome)
190 fmt.Fprintf(in.out, " %s\n", why)
191 fmt.Fprintf(in.out, " no event: a refusal is not staleness, and the request stays where it is\n")
192}
193
194// failedMemo marks a memo written for a pass that could not act on its own
195// verdict, and retryAfter is how long that answer stands.
196//
197// A failure here is a function of the same three things the verdict is, so
198// the identical attempt fails identically until one of them moves — and
199// moving any of them already re-judges the request, whatever the memo says.
200// The window exists for the other kind of failure: a bus, a disk, a lock,
201// something outside the three that will be different later. Minutes rather
202// than ticks, because a controller that reports the same refusal every
203// fifteen seconds has buried the report it was making.
204const (
205 failedMemo = "failed"
206 retryAfter = 10 * time.Minute
207)
208
209// answered says whether this pass already has this request's answer, given
210// the last memo written for it. An outcome stands until the request, the
211// tip, or the evidence moves; a recorded failure stands the same way, and
212// additionally expires, so a transient one is retried without being
213// retried at tick rate. A refusal never stands: what refused it can change
214// while the three stay where they are, as when a draft is readied again,
215// so it is decided again on every pass.
216func (in *integrator) answered(last, memo string) bool {
217 rest, ok := strings.CutPrefix(last, memo+" ")
218 if !ok {
219 return false
220 }
221 switch verdict.Outcome(rest) {
222 case refusedNotReady, refusedMerge:
223 return false
224 }
225 when, failed := strings.CutPrefix(rest, failedMemo+" ")
226 if !failed {
227 return true
228 }
229 at, err := time.Parse(time.RFC3339, when)
230 if err != nil {
231 return false
232 }
233 return in.now().Sub(at) < retryAfter
234}
235
236// act judges one request and does what the verdict says, returning the
237// outcome so the memo can record it.
238func (in *integrator) act(r request, idx *recordIndex, tip string) (verdict.Outcome, error) {
239 ch, snap, landed, err := in.materialize(r, tip)
240 if err != nil {
241 return "", err
242 }
243 v := verdict.Decide(ch, snap)
244 in.report(r, tip, v)
245 if landed.composition != "" {
246 fmt.Fprintf(in.out, " policy %s\n", landed.composition)
247 }
248
249 switch v.Outcome {
250 case verdict.Land:
251 // Judging can take minutes, and a change can be unreadied or
252 // withdrawn meanwhile. So the records are read once more just
253 // before the commit point, and a change no longer ready lands
254 // nothing.
255 if outcome, why, err := in.recordRefusal(r, idx, true); err != nil || outcome != "" {
256 if outcome != "" {
257 in.reportRefusal(r, tip, outcome, why)
258 }
259 return outcome, err
260 }
261 if err := in.land(ch, v, r, tip, landed); err != nil {
262 return v.Outcome, err
263 }
264 case verdict.Stale:
265 in.publishStale(ch, v, tip)
266 case verdict.Reject:
267 // There is no rejection event. The failure model is unified on
268 // staleness (architecture.md), and a change whose evidence is
269 // forged is not stale — so rather than stretch either event to
270 // cover it, the vocabulary stays as it is and the refusal is the
271 // integrator's own output. The request stays put; nothing about
272 // it will change on its own.
273 fmt.Fprintf(in.out, " no event: a forged attestation is not staleness, and the vocabulary has no other word\n")
274 }
275 return v.Outcome, nil
276}
277
278// landing is the commit a verdict would move the target to, and what the
279// verdict was computed under.
280type landing struct {
281 commit string // the commit that would be the target's new tip
282 digest string // the valley-tree-v1 digest of the resulting tree
283 policy string // a digest of the composed policy the verdict used
284
285 // composition is what the pass has to say about how the policy layers
286 // resolved, or empty when both were where they are configured to be.
287 composition string
288
289 // notes are the contributor's attestations as stored, by check name.
290 // The verdict does not read them; what lands countersigns them.
291 notes map[string][]byte
292}
293
294// materialize gathers everything the verdict is a function of: the applied
295// delta, the required checks, the recomputed closures, and what intervening
296// landings touched.
297func (in *integrator) materialize(r request, tip string) (verdict.Change, verdict.Snapshot, landing, error) {
298 var land landing
299 wt, err := addWorktree(in.repo, tip)
300 if err != nil {
301 return verdict.Change{}, verdict.Snapshot{}, land, err
302 }
303 defer wt.remove()
304
305 base, err := gitLine(in.repo, "merge-base", tip, r.head)
306 if err != nil {
307 return verdict.Change{}, verdict.Snapshot{}, land, fmt.Errorf("%s and %s share no history", verdict.Short(r.head), r.target)
308 }
309 attested, err := in.treeDigest(wt, r.head)
310 if err != nil {
311 return verdict.Change{}, verdict.Snapshot{}, land, err
312 }
313 ch := verdict.Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested}
314 if ch.Evidence, land.notes, err = in.collectEvidence(wt, r.head, attested); err != nil {
315 return ch, verdict.Snapshot{}, land, err
316 }
317
318 // The policy is read from the integrator's own side and never from the
319 // tree being gated: the project layer from this checkout of the target
320 // tip, the floor from the instance repository's integrated tip. Both
321 // are resolved once and held for the whole pass.
322 pol, closePolicy, err := in.policy.open(wt)
323 if err != nil {
324 return ch, verdict.Snapshot{}, land, err
325 }
326 defer closePolicy()
327 land.composition = pol.note
328 cat, policyDigest, err := pol.catalogue()
329 if err != nil {
330 return ch, verdict.Snapshot{}, land, err
331 }
332 land.policy = policyDigest
333 owed, err := pol.derive(wt, base, r.head)
334 if err != nil {
335 return ch, verdict.Snapshot{}, land, err
336 }
337 required, err := pol.required(owed, cat)
338 if err != nil {
339 return ch, verdict.Snapshot{}, land, err
340 }
341
342 snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
343
344 // Apply the delta. A base that is already the tip is a fast-forward:
345 // the head lands as it stands and its tree is the tree that was
346 // attested.
347 if base == tip {
348 land.commit = r.head
349 land.digest = attested
350 snap.Apply = verdict.Applied{Clean: true, Tree: attested}
351 } else {
352 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
353 if err != nil {
354 return ch, snap, land, err
355 }
356 if conflict != "" {
357 snap.Apply = verdict.Applied{Clean: false, Conflict: conflict}
358 return ch, snap, land, nil
359 }
360 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
361 return ch, snap, land, err
362 }
363 if land.digest, err = in.treeDigest(wt, tree); err != nil {
364 return ch, snap, land, err
365 }
366 snap.Apply = verdict.Applied{Clean: true, Tree: land.digest}
367
368 // What intervening landings touched, in the policy's own terms:
369 // the classes the deriver matches over base..tip. Asking the
370 // deriver rather than matching globs here keeps one implementation
371 // of what a class covers.
372 intervening, err := pol.derive(wt, base, tip)
373 if err != nil {
374 return ch, snap, land, err
375 }
376 snap.Touched = intervening.classes
377 }
378
379 // The closures only have to be recomputed when the tree moved: an
380 // unmoved tree presents the identical computation by construction.
381 if land.digest != attested {
382 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
383 }
384 return ch, snap, land, nil
385}
386
387// committerEmail is the address on the commits the integrator makes. git
388// wants an address and there is none to give: the integrator is a service,
389// not a correspondent. .invalid never resolves, which says so in the address
390// itself. Which integrator committed is carried by the name beside it.
391const committerEmail = "integrator@the-valley.invalid"
392
393// commitTree turns the merged tree into the commit that would become the
394// target's new tip. The tip is its only parent, so the ref write is a
395// fast-forward; the change's authorship is carried over from its head.
396//
397// Both identities are stated here rather than left to git. The author is the
398// asker's, because re-parenting a delta is not authoring it. The committer is
399// the integrator, under the name it signs its transfer statement with: the
400// commit and the statement about it then name the same actor. Leaving either
401// to git would ask git to guess an identity from the environment, and under
402// the unit there is nothing to guess from — which is a landing that fails for
403// a reason that has nothing to do with the change.
404func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
405 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
406 if err != nil {
407 return "", err
408 }
409 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
410 if err != nil {
411 return "", err
412 }
413 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
414 if len(fields) != 3 {
415 return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head))
416 }
417 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
418 // The committer date is the author's, so that the commit id is a function
419 // of what the pass decided from — the tree, the tip, the message and the
420 // authorship — and of nothing else. A pass that dies between here and the
421 // ref write recomputes the identical commit next time round instead of
422 // leaving another unreferenced one behind. Nothing reads this date: when
423 // the landing happened is recorded, signed, in the transfer statement.
424 out, err := in.gitEnv(map[string]string{
425 "GIT_AUTHOR_NAME": fields[0],
426 "GIT_AUTHOR_EMAIL": fields[1],
427 "GIT_AUTHOR_DATE": fields[2],
428 "GIT_COMMITTER_NAME": in.signerName,
429 "GIT_COMMITTER_EMAIL": committerEmail,
430 "GIT_COMMITTER_DATE": fields[2],
431 }, cmd...)
432 return strings.TrimSpace(out), err
433}
434
435// land moves the protected ref, stores the evidence, and says so on the
436// bus. The ref write is a compare-and-swap against the tip the verdict was
437// computed over, so a request that lost a race to another lands nothing and
438// is judged again next pass against the tip that won.
439//
440// The order is the commit point's. Everything that can fail while the
441// integrator is still deciding happens first, and the ref write is the
442// commit. Composing the transfer statement — vetting it, writing it down,
443// signing it — is part of deciding: a claim the integrator cannot write
444// down is a claim it has not made, and a stream moved on a decision that
445// cannot be stated is a landing nothing records. A failure before the
446// commit point leaves the stream where it was and the request where it was,
447// which is a transaction abandoned before it committed and costs one pass
448// to redo.
449//
450// Past the commit point the landing is a fact in the stream, and what is
451// left is recording it: handing the ref move to the host to publish,
452// storing the evidence, consuming the request, and saying so on the bus.
453// None of those may be skipped because an earlier one failed, and
454// consuming the request in particular may not be reachable only through
455// something that can fail — a request left pending for a change
456// already in the stream is re-judged against an empty delta on every pass,
457// forever. So each step runs, each failure is reported, and the landing is
458// reported as having happened, because it did.
459func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing) error {
460 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
461 if err != nil {
462 return err
463 }
464 evidence, err := in.countersign(ch, v, l, transfer)
465 if err != nil {
466 return err
467 }
468
469 // The commit point.
470 if _, err := git(in.repo, "update-ref", ch.Target, l.commit, tip); err != nil {
471 return fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
472 }
473 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit))
474 in.queueRefUpdate(ch.Target, tip, l.commit)
475
476 var unrecorded []string
477 refs, err := in.store(evidence)
478 if err != nil {
479 unrecorded = append(unrecorded, fmt.Sprintf("the evidence was not stored (%v)", err))
480 }
481 for _, ref := range refs {
482 fmt.Fprintf(in.out, " evidence %s\n", ref)
483 }
484 // The request is consumed only if it still names the head that landed.
485 // A second approval can replace it while this pass works — the asker's
486 // write is leased against what it read, and nothing stops it reading
487 // the request this pass is about to land — and a delete that did not
488 // compare would take the new request with the old one. A request that
489 // moved is a new request, and it stands for the next pass.
490 if _, err := git(in.repo, "update-ref", "-d", r.ref, r.head); err != nil {
491 if now, found := gitTry(in.repo, "rev-parse", "--verify", "--quiet", r.ref); found && now != r.head {
492 fmt.Fprintf(in.out, " request %s moved to %s while %s landed; it stands for the next pass\n",
493 r.ref, verdict.Short(now), verdict.Short(r.head))
494 } else {
495 unrecorded = append(unrecorded, fmt.Sprintf("the request ref %s was not consumed (%v)", r.ref, err))
496 }
497 }
498 // The bus comes last. Everything above is the landing's own record; an
499 // event is a best-effort notice of it, and a bus that fails or hangs
500 // must not leave any of that record undone.
501 in.publishRefUpdated(ch.Target, tip, l.commit)
502 in.publishLanded(ch, v, tip, l.commit)
503 if len(unrecorded) > 0 {
504 return fmt.Errorf("%s landed as %s and the landing is not fully recorded: %s",
505 ch.ID, verdict.Short(l.commit), strings.Join(unrecorded, "; "))
506 }
507 return nil
508}
509
510// report prints the verdict, per check, in the order it was judged.
511func (in *integrator) report(r request, tip string, v verdict.Verdict) {
512 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome)
513 fmt.Fprintf(in.out, " %s\n", v.Reason)
514 for _, cv := range v.Checks {
515 if cv.Transferred {
516 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
517 continue
518 }
519 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
520 }
521}
522
523// The memo is the level-trigger's memory: what this integrator last decided
524// about a request, keyed by the request. It is durable in git like
525// everything else the transport reads, so a restarted controller does not
526// re-announce a judgement it has already made.
527func (in *integrator) memoRef(r request) string {
528 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
529}
530
531func (in *integrator) readMemo(r request) (string, error) {
532 out, ok := gitTry(in.repo, "cat-file", "blob", in.memoRef(r))
533 if !ok {
534 return "", nil
535 }
536 return strings.TrimSpace(out), nil
537}
538
539func (in *integrator) writeMemo(r request, value string) error {
540 blob, err := in.writeBlob([]byte(value + "\n"))
541 if err != nil {
542 return err
543 }
544 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
545 return err
546}
547
548// evidenceState digests the attestation namespace: every ref under it and
549// the object it points at. Attestation refs are create-only, so this moves
550// exactly when evidence arrives.
551//
552// It is deliberately the whole namespace rather than the refs for one
553// change's subject digest, which would take a checkout to compute and would
554// have to be recomputed before the memo could rule the work out. So an
555// attestation for one change re-judges every pending request. That is the
556// conservative direction — a pass that runs and changes nothing costs a
557// pass; a verdict never revisited strands a change — and it is bounded by
558// the number of requests pending.
559func (in *integrator) evidenceState() (string, error) {
560 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix)
561 if err != nil {
562 return "", err
563 }
564 return sha256hex([]byte(out))[:16], nil
565}
566
567func (in *integrator) now() time.Time {
568 if !in.clock.IsZero() {
569 return in.clock
570 }
571 return time.Now().UTC()
572}