gunk-dev/the-valley

refs.go

source467cc727ded8main's published tip history
11.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 "fmt"
31 "sort"
32 "strings"
33 "time"
34)
35
36const (
37 requestPrefix = "refs/the-valley/integration-requests"
38 outcomePrefix = "refs/the-valley/integration-outcomes"
39)
40
41// request is one integration request as the refs transport found it.
42type request struct {
43 ref string
44 change string
45 target string
46 head string
47}
48
49// requests lists the pending requests, in ref order so a pass is
50// deterministic.
51func (in *integrator) requests() ([]request, error) {
52 out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", requestPrefix)
53 if err != nil {
54 return nil, err
55 }
56 var found []request
57 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
58 if line == "" {
59 continue
60 }
61 ref, head, ok := strings.Cut(line, " ")
62 if !ok {
63 continue
64 }
65 rest := strings.TrimPrefix(ref, requestPrefix+"/")
66 target, change, ok := strings.Cut(rest, "/")
67 if !ok || strings.Contains(change, "/") {
68 return nil, fmt.Errorf("%s is not a request ref: one is %s/<target>/<change>", ref, requestPrefix)
69 }
70 found = append(found, request{ref: ref, change: change, target: "refs/heads/" + target, head: head})
71 }
72 sort.Slice(found, func(i, j int) bool { return found[i].ref < found[j].ref })
73 return found, nil
74}
75
76// reconcile is one pass: judge every request against the current tip of its
77// target, and act where the answer has changed.
78func (in *integrator) reconcile() error {
79 requests, err := in.requests()
80 if err != nil {
81 return err
82 }
83 for _, r := range requests {
84 if err := in.handle(r); err != nil {
85 // One bad request must not stop the pass: the integrator is a
86 // controller, and a request it cannot judge is one request's
87 // problem.
88 fmt.Fprintf(in.out, "%s: %v\n", r.change, err)
89 }
90 }
91 return nil
92}
93
94// handle judges one request and acts on the verdict.
95func (in *integrator) handle(r request) error {
96 tip, err := gitLine(in.repo, "rev-parse", "--verify", "--quiet", r.target)
97 if err != nil {
98 return fmt.Errorf("no target %s to integrate onto", r.target)
99 }
100 // Level-triggering: the verdict is a function of the request's head
101 // and the target's tip, so an unchanged pair has an unchanged answer
102 // and re-announcing it would be a retry storm.
103 memo := fmt.Sprintf("%s %s", r.head, tip)
104 if last, _ := in.readMemo(r); last != "" && strings.HasPrefix(last, memo+" ") {
105 return nil
106 }
107
108 ch, snap, landed, err := in.materialize(r, tip)
109 if err != nil {
110 return err
111 }
112 v := Decide(ch, snap)
113 in.report(r, tip, v)
114
115 switch v.Outcome {
116 case Land:
117 if err := in.land(ch, v, r, tip, landed); err != nil {
118 return err
119 }
120 case Stale:
121 in.publishStale(ch, v, tip)
122 case Reject:
123 // There is no rejection event. The failure model is unified on
124 // staleness (architecture.md), and a change whose evidence is
125 // forged is not stale — so rather than stretch either event to
126 // cover it, the vocabulary stays as it is and the refusal is the
127 // integrator's own output. The request stays put; nothing about
128 // it will change on its own.
129 fmt.Fprintf(in.out, " no event: a forged attestation is not staleness, and the vocabulary has no other word\n")
130 }
131 return in.writeMemo(r, memo+" "+string(v.Outcome))
132}
133
134// materialized is what one pass computed about a request before deciding.
135type landing struct {
136 tree string // the resulting tree's object id
137 commit string // the commit that would be the target's new tip
138 digest string // the valley-tree-v1 digest of the resulting tree
139 policy string // a digest of the composed policy the verdict used
140}
141
142// materialize gathers everything the verdict is a function of: the applied
143// delta, the required checks, the recomputed closures, and what intervening
144// landings touched.
145func (in *integrator) materialize(r request, tip string) (Change, Snapshot, landing, error) {
146 var land landing
147 wt, err := addWorktree(in.repo, tip)
148 if err != nil {
149 return Change{}, Snapshot{}, land, err
150 }
151 defer wt.remove()
152
153 base, err := gitLine(in.repo, "merge-base", tip, r.head)
154 if err != nil {
155 return Change{}, Snapshot{}, land, fmt.Errorf("%s and %s share no history", short(r.head), r.target)
156 }
157 attested, err := in.treeDigest(wt, r.head)
158 if err != nil {
159 return Change{}, Snapshot{}, land, err
160 }
161 ch := Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested}
162 if ch.Evidence, err = in.collectEvidence(wt, r.head, attested); err != nil {
163 return ch, Snapshot{}, land, err
164 }
165
166 // The policy is read at the target tip, from the integrator's own
167 // checkout — never from the tree being gated.
168 cat, policyDigest, err := in.policy.catalogue(wt)
169 if err != nil {
170 return ch, Snapshot{}, land, err
171 }
172 land.policy = policyDigest
173 owed, err := in.policy.derive(wt, base, r.head)
174 if err != nil {
175 return ch, Snapshot{}, land, err
176 }
177 required, err := in.policy.required(owed, cat)
178 if err != nil {
179 return ch, Snapshot{}, land, err
180 }
181
182 snap := Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()}
183
184 // Apply the delta. A base that is already the tip is a fast-forward:
185 // the head lands as it stands and its tree is the tree that was
186 // attested.
187 if base == tip {
188 land.commit = r.head
189 if land.tree, err = gitLine(in.repo, "rev-parse", r.head+"^{tree}"); err != nil {
190 return ch, snap, land, err
191 }
192 land.digest = attested
193 snap.Apply = Applied{Clean: true, Tree: attested}
194 } else {
195 tree, conflict, err := mergeDelta(in.repo, base, tip, r.head)
196 if err != nil {
197 return ch, snap, land, err
198 }
199 if conflict != "" {
200 snap.Apply = Applied{Clean: false, Conflict: firstLine(conflict)}
201 return ch, snap, land, nil
202 }
203 land.tree = tree
204 if land.commit, err = in.commitTree(tree, tip, r); err != nil {
205 return ch, snap, land, err
206 }
207 if land.digest, err = in.treeDigest(wt, tree); err != nil {
208 return ch, snap, land, err
209 }
210 snap.Apply = Applied{Clean: true, Tree: land.digest}
211
212 // What intervening landings touched, in the policy's own terms:
213 // the classes the deriver matches over base..tip. Asking the
214 // deriver rather than matching globs here keeps one implementation
215 // of what a class covers.
216 intervening, err := in.policy.derive(wt, base, tip)
217 if err != nil {
218 return ch, snap, land, err
219 }
220 snap.Touched = intervening.classes
221 }
222
223 // The closures only have to be recomputed when the tree moved: an
224 // unmoved tree presents the identical computation by construction.
225 if land.digest != attested {
226 snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required)
227 }
228 return ch, snap, land, nil
229}
230
231// commitTree turns the merged tree into the commit that would become the
232// target's new tip. The tip is its only parent, so the ref write is a
233// fast-forward; the change's authorship is carried over from its head.
234func (in *integrator) commitTree(tree, tip string, r request) (string, error) {
235 message, err := git(in.repo, "log", "-1", "--format=%B", r.head)
236 if err != nil {
237 return "", err
238 }
239 author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head)
240 if err != nil {
241 return "", err
242 }
243 fields := strings.Split(strings.TrimRight(author, "\n"), "\n")
244 if len(fields) != 3 {
245 return "", fmt.Errorf("cannot read the authorship of %s", short(r.head))
246 }
247 cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")}
248 out, err := in.gitEnv(map[string]string{
249 "GIT_AUTHOR_NAME": fields[0],
250 "GIT_AUTHOR_EMAIL": fields[1],
251 "GIT_AUTHOR_DATE": fields[2],
252 }, cmd...)
253 return strings.TrimSpace(out), err
254}
255
256// land moves the protected ref, stores the evidence, and says so on the
257// bus. The ref write is a compare-and-swap against the tip the verdict was
258// computed over, so a request that lost a race to another lands nothing and
259// is judged again next pass against the tip that won.
260func (in *integrator) land(ch Change, v Verdict, r request, tip string, l landing) error {
261 transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy)
262 if err != nil {
263 return err
264 }
265 evidence, err := in.countersign(ch, v, transfer, l.digest)
266 if err != nil {
267 return err
268 }
269 if _, err := git(in.repo, "update-ref", ch.Target, l.commit, tip); err != nil {
270 return fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err)
271 }
272 refs, err := in.store(evidence)
273 if err != nil {
274 return err
275 }
276 for _, ref := range refs {
277 fmt.Fprintf(in.out, " evidence %s\n", ref)
278 }
279 fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, short(tip), short(l.commit))
280 if _, err := git(in.repo, "update-ref", "-d", r.ref); err != nil {
281 return err
282 }
283 in.publishLanded(ch, v, tip, l.commit)
284 return nil
285}
286
287// report prints the verdict, per check, in the order it was judged.
288func (in *integrator) report(r request, tip string, v Verdict) {
289 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, short(tip), v.Outcome)
290 fmt.Fprintf(in.out, " %s\n", v.Reason)
291 for _, cv := range v.Checks {
292 if cv.Transferred {
293 fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule)
294 continue
295 }
296 fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason)
297 }
298}
299
300// The memo is the level-trigger's memory: what this integrator last decided
301// about a request, keyed by the request. It is durable in git like
302// everything else the transport reads, so a restarted controller does not
303// re-announce a judgement it has already made.
304func (in *integrator) memoRef(r request) string {
305 return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/")
306}
307
308func (in *integrator) readMemo(r request) (string, error) {
309 out, ok := gitTry(in.repo, "cat-file", "blob", in.memoRef(r))
310 if !ok {
311 return "", nil
312 }
313 return strings.TrimSpace(out), nil
314}
315
316func (in *integrator) writeMemo(r request, value string) error {
317 blob, err := in.writeBlob([]byte(value + "\n"))
318 if err != nil {
319 return err
320 }
321 _, err = git(in.repo, "update-ref", in.memoRef(r), blob)
322 return err
323}
324
325func (in *integrator) now() time.Time {
326 if !in.clock.IsZero() {
327 return in.clock
328 }
329 return time.Now().UTC()
330}