gunk-dev/the-valley

refs.go

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