gunk-dev/the-valley

refs.go

source0644a9643af0main's published tip history
13.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.
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 last, _ := in.readMemo(r); last != "" && strings.HasPrefix(last, memo+" ") {
126 return nil
127 }
128
129 ch, snap, landed, err := in.materialize(r, tip)
130 if err != nil {
131 return err
132 }
133 v := verdict.Decide(ch, snap)
134 in.report(r, tip, v)
135
136 switch v.Outcome {
137 case verdict.Land:
138 if err := in.land(ch, v, r, tip, landed); err != nil {
139 return err
140 }
141 case verdict.Stale:
142 in.publishStale(ch, v, tip)
143 case verdict.Reject:
144 // There is no rejection event. The failure model is unified on
145 // staleness (architecture.md), and a change whose evidence is
146 // forged is not stale — so rather than stretch either event to
147 // cover it, the vocabulary stays as it is and the refusal is the
148 // integrator's own output. The request stays put; nothing about
149 // it will change on its own.
150 fmt.Fprintf(in.out, " no event: a forged attestation is not staleness, and the vocabulary has no other word\n")
151 }
152 return in.writeMemo(r, memo+" "+string(v.Outcome))
153}
154
155// landing is the commit a verdict would move the target to, and what the
156// verdict was computed under.
157type landing struct {
158 commit string // the commit that would be the target's new tip
159 digest string // the valley-tree-v1 digest of the resulting tree
160 policy string // a digest of the composed policy the verdict used
161
162 // notes are the contributor's attestations as stored, by check name.
163 // The verdict does not read them; what lands countersigns them.
164 notes map[string][]byte
165}
166
167// materialize gathers everything the verdict is a function of: the applied
168// delta, the required checks, the recomputed closures, and what intervening
169// landings touched.
170func (in *integrator) materialize(r request, tip string) (verdict.Change, verdict.Snapshot, landing, error) {
171 var land landing
172 wt, err := addWorktree(in.repo, tip)
173 if err != nil {
174 return verdict.Change{}, verdict.Snapshot{}, land, err
175 }
176 defer wt.remove()
177
178 base, err := gitLine(in.repo, "merge-base", tip, r.head)
179 if err != nil {
180 return verdict.Change{}, verdict.Snapshot{}, land, fmt.Errorf("%s and %s share no history", verdict.Short(r.head), r.target)
181 }
182 attested, err := in.treeDigest(wt, r.head)
183 if err != nil {
184 return verdict.Change{}, verdict.Snapshot{}, land, err
185 }
186 ch := verdict.Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested}
187 if ch.Evidence, land.notes, err = in.collectEvidence(wt, r.head, attested); err != nil {
188 return ch, verdict.Snapshot{}, land, err
189 }
190
191 // The policy is read at the target tip, from the integrator's own
192 // checkout — never from the tree being gated.
193 cat, policyDigest, err := in.policy.catalogue(wt)
194 if err != nil {
195 return ch, verdict.Snapshot{}, land, err
196 }
197 land.policy = policyDigest
198 owed, err := in.policy.derive(wt, base, r.head)
199 if err != nil {
200 return ch, verdict.Snapshot{}, land, err
201 }
202 required, err := in.policy.required(owed, cat)
203 if err != nil {
204 return ch, verdict.Snapshot{}, land, err
205 }
206
207 snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
208
209 // Apply the delta. A base that is already the tip is a fast-forward:
210 // the head lands as it stands and its tree is the tree that was
211 // attested.
212 if base == tip {
213 land.commit = r.head
214 land.digest = attested
215 snap.Apply = verdict.Applied{Clean: true, Tree: attested}
216 } else {
217 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
218 if err != nil {
219 return ch, snap, land, err
220 }
221 if conflict != "" {
222 snap.Apply = verdict.Applied{Clean: false, Conflict: conflict}
223 return ch, snap, land, nil
224 }
225 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
226 return ch, snap, land, err
227 }
228 if land.digest, err = in.treeDigest(wt, tree); err != nil {
229 return ch, snap, land, err
230 }
231 snap.Apply = verdict.Applied{Clean: true, Tree: land.digest}
232
233 // What intervening landings touched, in the policy's own terms:
234 // the classes the deriver matches over base..tip. Asking the
235 // deriver rather than matching globs here keeps one implementation
236 // of what a class covers.
237 intervening, err := in.policy.derive(wt, base, tip)
238 if err != nil {
239 return ch, snap, land, err
240 }
241 snap.Touched = intervening.classes
242 }
243
244 // The closures only have to be recomputed when the tree moved: an
245 // unmoved tree presents the identical computation by construction.
246 if land.digest != attested {
247 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
248 }
249 return ch, snap, land, nil
250}
251
252// commitTree turns the merged tree into the commit that would become the
253// target's new tip. The tip is its only parent, so the ref write is a
254// fast-forward; the change's authorship is carried over from its head.
255func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
256 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
257 if err != nil {
258 return "", err
259 }
260 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
261 if err != nil {
262 return "", err
263 }
264 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
265 if len(fields) != 3 {
266 return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head))
267 }
268 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
269 out, err := in.gitEnv(map[string]string{
270 "GIT_AUTHOR_NAME": fields[0],
271 "GIT_AUTHOR_EMAIL": fields[1],
272 "GIT_AUTHOR_DATE": fields[2],
273 }, cmd...)
274 return strings.TrimSpace(out), err
275}
276
277// land moves the protected ref, stores the evidence, and says so on the
278// bus. The ref write is a compare-and-swap against the tip the verdict was
279// computed over, so a request that lost a race to another lands nothing and
280// is judged again next pass against the tip that won.
281func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing) error {
282 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
283 if err != nil {
284 return err
285 }
286 evidence, err := in.countersign(ch, v, l, transfer)
287 if err != nil {
288 return err
289 }
290 if _, err := git(in.repo, "update-ref", ch.Target, l.commit, tip); err != nil {
291 return fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
292 }
293 refs, err := in.store(evidence)
294 if err != nil {
295 return err
296 }
297 for _, ref := range refs {
298 fmt.Fprintf(in.out, " evidence %s\n", ref)
299 }
300 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit))
301 if _, err := git(in.repo, "update-ref", "-d", r.ref); err != nil {
302 return err
303 }
304 in.publishLanded(ch, v, tip, l.commit)
305 return nil
306}
307
308// report prints the verdict, per check, in the order it was judged.
309func (in *integrator) report(r request, tip string, v verdict.Verdict) {
310 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome)
311 fmt.Fprintf(in.out, " %s\n", v.Reason)
312 for _, cv := range v.Checks {
313 if cv.Transferred {
314 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
315 continue
316 }
317 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
318 }
319}
320
321// The memo is the level-trigger's memory: what this integrator last decided
322// about a request, keyed by the request. It is durable in git like
323// everything else the transport reads, so a restarted controller does not
324// re-announce a judgement it has already made.
325func (in *integrator) memoRef(r request) string {
326 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
327}
328
329func (in *integrator) readMemo(r request) (string, error) {
330 out, ok := gitTry(in.repo, "cat-file", "blob", in.memoRef(r))
331 if !ok {
332 return "", nil
333 }
334 return strings.TrimSpace(out), nil
335}
336
337func (in *integrator) writeMemo(r request, value string) error {
338 blob, err := in.writeBlob([]byte(value + "\n"))
339 if err != nil {
340 return err
341 }
342 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
343 return err
344}
345
346// evidenceState digests the attestation namespace: every ref under it and
347// the object it points at. Attestation refs are create-only, so this moves
348// exactly when evidence arrives.
349//
350// It is deliberately the whole namespace rather than the refs for one
351// change's subject digest, which would take a checkout to compute and would
352// have to be recomputed before the memo could rule the work out. So an
353// attestation for one change re-judges every pending request. That is the
354// conservative direction — a pass that runs and changes nothing costs a
355// pass; a verdict never revisited strands a change — and it is bounded by
356// the number of requests pending.
357func (in *integrator) evidenceState() (string, error) {
358 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix)
359 if err != nil {
360 return "", err
361 }
362 return sha256hex([]byte(out))[:16], nil
363}
364
365func (in *integrator) now() time.Time {
366 if !in.clock.IsZero() {
367 return in.clock
368 }
369 return time.Now().UTC()
370}