gunk-dev/the-valley

refs.go

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