gunk-dev/the-valley

records.go

source9322091a28d0main's published tip history
17.3 KiB
1package main
2
3// What the change records say about a request.
4//
5// A change record (change/) lists the versions of one change and says
6// whether the change is ready, a draft or withdrawn. Records grant
7// nothing: no record ever makes a request land. The integrator reads them
8// only to refuse. A request lands only when every record that knows its
9// head says the change is ready, so unreadying or withdrawing a change
10// stops a request already filed for it, though the change's owner cannot
11// touch request refs.
12//
13// Two rules read records:
14//
15// - A request named c-<change ID> is that change's. It is refused unless
16// the change's record exists, says ready, and lists the request's head
17// as one of its versions' heads. This reads the one record, fresh,
18// each time the rule is applied.
19// - A request of any name is refused when any commit it would bring to
20// the target, its head or one below it, is a version head of a record
21// that is not ready. The integrator finds those records by head,
22// through an index it builds from every ref under
23// refs/the-valley/changes/: once per pass, and again just before it
24// moves the target.
25//
26// A withdrawn change's requests are voided. Each pass deletes every
27// request named for a withdrawn change, and every request whose head is
28// one of its version heads, so readying the change again needs a fresh
29// approval.
30//
31// None of this is atomic with landing. A record written after the
32// integrator's last read and before it moves the target is not seen, so
33// an approved head its author has just paused can still land. What lands
34// is always a head the operator approved: the request names it exactly.
35//
36// A third rule reads the request's commits rather than records. A request
37// is refused when the commits from its merge base with the target to its
38// head include a merge. The integrator lands a line of commits, and a
39// merge could make other work look landed by ancestry.
40//
41// A request no record knows, and whose commits hold no merge, is judged as
42// it always was.
43
44import (
45 "the-valley/change"
46 "the-valley/integrator/verdict"
47
48 "bufio"
49 "bytes"
50 "errors"
51 "fmt"
52 "io"
53 "strconv"
54 "strings"
55)
56
57// The outcomes a request is refused with before the commit rule is
58// applied. Like a rejection, a refusal leaves the request where it is. A
59// refusal for a record's state stands only while the record says so: it
60// is decided again on every pass, so a change readied again is judged on
61// the next one.
62const (
63 refusedNotReady verdict.Outcome = "refused-not-ready"
64 refusedMerge verdict.Outcome = "refused-merge"
65
66 // voidedWithdrawn is the outcome of a request deleted because its
67 // change was withdrawn.
68 voidedWithdrawn verdict.Outcome = "voided-withdrawn"
69)
70
71// recordLimit is the most records the index reads. The hook refuses to
72// create a record past change.MaxRecords, and pushes that run at once can
73// pass that bound only by the records each had in flight. A repository
74// holding more than twice the bound lands nothing: the index could not say
75// which heads are versions of changes that are not ready, so no request in
76// it lands until records are deleted. Each repository has its own
77// controller, so the others are not held up.
78const recordLimit = 2 * change.MaxRecords
79
80// indexed is one record the index read, and the ref it was read from.
81type indexed struct {
82 ref string
83 record *change.Record
84}
85
86// recordIndex is every record the served repository holds, by the heads
87// its versions name and by ref.
88type recordIndex struct {
89 byHead map[string][]indexed
90 byRef map[string]*change.Record
91
92 // unreadable is each ref under the namespace that holds no record the
93 // shared parser accepts. A record that does not read names no head the
94 // integrator can see, so it refuses nothing, and a head it names can
95 // land. The hook refuses such a record, so only corrupt storage holds
96 // one, and the pass reports it wherever it may matter.
97 unreadable []unreadable
98}
99
100// unreadable is a ref under the namespace whose record does not read.
101type unreadable struct {
102 ref, commit, why string
103}
104
105// readRecords builds the index from every ref under
106// refs/the-valley/changes/.
107func (in *integrator) readRecords() (*recordIndex, error) {
108 out, err := git(in.repo, "for-each-ref", fmt.Sprintf("--count=%d", recordLimit+1),
109 "--format=%(refname) %(objectname)", change.RefPrefix)
110 if err != nil {
111 return nil, err
112 }
113 var refs, commits []string
114 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
115 if ref, oid, ok := strings.Cut(line, " "); ok {
116 refs = append(refs, ref)
117 commits = append(commits, oid)
118 }
119 }
120 if len(refs) > recordLimit {
121 return nil, fmt.Errorf("%s holds more than %d change records, so which heads are versions of changes that are not ready cannot be read; no request is judged until records are deleted", change.RefPrefix, recordLimit)
122 }
123 records, errs, err := in.records(refs, commits)
124 if err != nil {
125 return nil, err
126 }
127 idx := &recordIndex{byHead: map[string][]indexed{}, byRef: map[string]*change.Record{}}
128 for i, ref := range refs {
129 if errs[i] != nil {
130 idx.unreadable = append(idx.unreadable, unreadable{ref: ref, commit: commits[i], why: errs[i].Error()})
131 continue
132 }
133 idx.byRef[ref] = records[i]
134 for _, v := range records[i].Versions {
135 head := strings.TrimPrefix(v.Head, change.HeadPrefix)
136 idx.byHead[head] = append(idx.byHead[head], indexed{ref: ref, record: records[i]})
137 }
138 }
139 return idx, nil
140}
141
142// errNoRecord is a record ref that does not exist.
143var errNoRecord = errors.New("no such record")
144
145// readRecord reads the one record at ref, fresh. The ref is read by its
146// exact name, so a branch named like a missing record is no record.
147func (in *integrator) readRecord(ref string) (*change.Record, error) {
148 oid, ok, err := resolveRef(in.repo, ref)
149 if err != nil {
150 return nil, err
151 } else if !ok {
152 return nil, errNoRecord
153 }
154 records, errs, err := in.records([]string{ref}, []string{oid})
155 if err != nil {
156 return nil, err
157 }
158 return records[0], errs[0]
159}
160
161// records reads the record each ref points at, under the bounds the hook
162// admits a record under (change.MaxRecordCommit and the rest), each
163// checked before anything past it is read. The record must be the one
164// its ref names: its change ID and its target are the ref's. errs holds
165// why each record that does not read does not; err is for git itself
166// failing.
167func (in *integrator) records(refs, commits []string) (records []*change.Record, errs []error, err error) {
168 records = make([]*change.Record, len(refs))
169 errs = make([]error, len(refs))
170 if len(refs) == 0 {
171 return records, errs, nil
172 }
173 // First the sizes and types: the commit, its tree, and its
174 // record.json, one line each.
175 var query bytes.Buffer
176 for _, c := range commits {
177 fmt.Fprintf(&query, "%s\n%s^{tree}\n%s:record.json\n", c, c, c)
178 }
179 checked, err := gitInput(in.repo, query.Bytes(), "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
180 if err != nil {
181 return nil, nil, err
182 }
183 lines := strings.Split(strings.TrimRight(string(checked), "\n"), "\n")
184 if len(lines) != 3*len(refs) {
185 return nil, nil, fmt.Errorf("git cat-file answered %d lines for %d records", len(lines), len(refs))
186 }
187 var blobs []string
188 var wanted []int
189 for i := range refs {
190 blob, why := withinBounds(lines[3*i : 3*i+3])
191 if why != "" {
192 errs[i] = errors.New(why)
193 continue
194 }
195 blobs = append(blobs, blob)
196 wanted = append(wanted, i)
197 }
198 // Then the contents, of the record.json blobs within bounds alone.
199 contents, err := in.blobs(blobs)
200 if err != nil {
201 return nil, nil, err
202 }
203 for k, i := range wanted {
204 target, id, ok := change.ParseRef(refs[i])
205 if !ok {
206 errs[i] = fmt.Errorf("not a record ref; one is %s<target>/<change ID>", change.RefPrefix)
207 continue
208 }
209 r, err := change.Parse(contents[k])
210 switch {
211 case err != nil:
212 errs[i] = fmt.Errorf("its record.json does not read: %v", err)
213 case r.ChangeID != id || r.Target != target:
214 errs[i] = fmt.Errorf("it records change %s for %s, and its ref names change %s for %s", r.ChangeID, r.Target, id, target)
215 default:
216 records[i] = r
217 }
218 }
219 return records, errs, nil
220}
221
222// withinBounds reads cat-file's three lines about one record — its commit,
223// its tree and its record.json — and returns the blob, or why the record
224// is not one to read.
225func withinBounds(lines []string) (blob, why string) {
226 for k, want := range []struct {
227 what, kind string
228 max int
229 }{
230 {"the record", "commit", change.MaxRecordCommit},
231 {"its tree", "tree", change.MaxRecordTree},
232 {"its record.json", "blob", change.MaxRecordBlob},
233 } {
234 fields := strings.Fields(lines[k])
235 if len(fields) != 3 {
236 return "", fmt.Sprintf("%s is missing", want.what)
237 }
238 size, err := strconv.Atoi(fields[2])
239 switch {
240 case fields[1] != want.kind:
241 return "", fmt.Sprintf("%s is a %s, where a %s is expected", want.what, fields[1], want.kind)
242 case err != nil || size > want.max:
243 return "", fmt.Sprintf("%s is %s bytes, more than the %d a record may hold", want.what, fields[2], want.max)
244 }
245 blob = fields[0]
246 }
247 return blob, ""
248}
249
250// blobs reads each blob's contents with one cat-file.
251func (in *integrator) blobs(oids []string) ([][]byte, error) {
252 if len(oids) == 0 {
253 return nil, nil
254 }
255 out, err := gitInput(in.repo, []byte(strings.Join(oids, "\n")+"\n"), "cat-file", "--batch")
256 if err != nil {
257 return nil, err
258 }
259 rd := bufio.NewReader(bytes.NewReader(out))
260 contents := make([][]byte, len(oids))
261 for i := range oids {
262 header, err := rd.ReadString('\n')
263 if err != nil {
264 return nil, fmt.Errorf("git cat-file --batch: %w", err)
265 }
266 fields := strings.Fields(header)
267 if len(fields) != 3 {
268 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
269 }
270 size, err := strconv.Atoi(fields[2])
271 if err != nil {
272 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
273 }
274 contents[i] = make([]byte, size)
275 if _, err := io.ReadFull(rd, contents[i]); err != nil {
276 return nil, fmt.Errorf("git cat-file --batch: %w", err)
277 }
278 if _, err := rd.Discard(1); err != nil {
279 return nil, fmt.Errorf("git cat-file --batch: %w", err)
280 }
281 }
282 return contents, nil
283}
284
285// recordRefusal applies the two rules that read records, and returns the
286// refusal and why, or "" when neither refuses. The request's own record,
287// for a request named c-<change ID>, is read fresh; every other record is
288// read from idx.
289func (in *integrator) recordRefusal(r request, idx *recordIndex, tip string) (verdict.Outcome, string, error) {
290 target := strings.TrimPrefix(r.target, "refs/heads/")
291 if id, ok := change.RequestID(r.change); ok {
292 ref := change.Ref(target, id)
293 rec, err := in.readRecord(ref)
294 switch {
295 case errors.Is(err, errNoRecord):
296 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and %s holds no record of it", id, ref), nil
297 case err != nil:
298 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and its record %s does not read: %v", id, ref, err), nil
299 case rec.State != change.Ready:
300 return refusedNotReady, fmt.Sprintf("change %s is %s, not ready", id, rec.State), nil
301 }
302 if _, found := versionAt(rec, r.head); !found {
303 return refusedNotReady, fmt.Sprintf("its head %s is no version of change %s", verdict.Short(r.head), id), nil
304 }
305 }
306 commits, err := in.introduced(r, tip)
307 if err != nil {
308 return "", "", err
309 }
310 for _, c := range commits {
311 for _, n := range idx.byHead[c] {
312 v, found := versionAt(n.record, c)
313 if !found || n.record.State == change.Ready {
314 continue
315 }
316 what := "the commit " + verdict.Short(c) + " it brings"
317 if c == r.head {
318 what = "its head " + verdict.Short(c)
319 }
320 return refusedNotReady, fmt.Sprintf("%s is v%d of change %s, which is %s, not ready", what, v.N, n.record.ChangeID, n.record.State), nil
321 }
322 }
323 return "", "", nil
324}
325
326// introduced is every commit a request would bring to the target, newest
327// first: those reachable from its head and not from the tip, and the head
328// itself whatever the tip holds.
329func (in *integrator) introduced(r request, tip string) ([]string, error) {
330 out, err := gitLine(in.repo, "rev-list", r.head, "^"+tip)
331 if err != nil {
332 return nil, fmt.Errorf("cannot read the commits from %s to %s: %w", r.target, verdict.Short(r.head), err)
333 }
334 commits := strings.Fields(out)
335 if len(commits) == 0 || commits[0] != r.head {
336 commits = append([]string{r.head}, commits...)
337 }
338 return commits, nil
339}
340
341// finalRefusal applies the record rules once more, immediately before the
342// target moves, with every record read again into a fresh index. A record
343// that came to name one of the request's commits since the pass began is
344// seen here. Only a record written after this read and before the target
345// moves is missed.
346func (in *integrator) finalRefusal(r request, tip string) (verdict.Outcome, string, error) {
347 idx, err := in.readRecords()
348 if err != nil {
349 return "", "", err
350 }
351 return in.recordRefusal(r, idx, tip)
352}
353
354// uncheckable is each record that does not read and may name one of the
355// commits the request brings. A record names its version heads as parents
356// of its record commits, so it can name only a commit its record commit
357// reaches. That is true of some commit the request brings exactly when a
358// merge base of the record commit and the head is not on the tip. A record
359// git cannot compare at all may name anything.
360func (in *integrator) uncheckable(r request, idx *recordIndex, tip string) []unreadable {
361 var found []unreadable
362 for _, u := range idx.unreadable {
363 out, ok := gitTry(in.repo, "merge-base", "--all", u.commit, r.head)
364 may := !ok && out != ""
365 for _, base := range strings.Fields(out) {
366 if !ok {
367 break
368 }
369 if _, onTip := gitTry(in.repo, "merge-base", "--is-ancestor", base, tip); !onTip {
370 may = true
371 }
372 }
373 if may {
374 found = append(found, u)
375 }
376 }
377 return found
378}
379
380// voidWithdrawn deletes the requests a withdrawn change voids, and returns
381// the requests left to judge. A request is voided when it is named for a
382// withdrawn change, or when its head is a version head of one. Before each
383// deletion the record is read again, and the request is deleted only if
384// the change is still withdrawn. The deletion is leased on the head the
385// pass found the request at, so an approval filed since stands. A
386// withdrawal followed by a ready within one pass is not seen, and leaves
387// the request in place.
388func (in *integrator) voidWithdrawn(requests []request, idx *recordIndex) []request {
389 var kept []request
390 for _, r := range requests {
391 if ref := withdrawnFor(r, idx); ref == "" || !in.void(r, ref) {
392 kept = append(kept, r)
393 }
394 }
395 return kept
396}
397
398// withdrawnFor is the ref of a withdrawn change's record that voids the
399// request, as idx read it, or "".
400func withdrawnFor(r request, idx *recordIndex) string {
401 if id, ok := change.RequestID(r.change); ok {
402 ref := change.Ref(strings.TrimPrefix(r.target, "refs/heads/"), id)
403 if rec := idx.byRef[ref]; rec != nil && rec.State == change.Withdrawn {
404 return ref
405 }
406 }
407 for _, n := range idx.byHead[r.head] {
408 if n.record.State == change.Withdrawn {
409 return n.ref
410 }
411 }
412 return ""
413}
414
415// void deletes one request a withdrawn change voids, if the change is
416// still withdrawn and the request still at the head the pass found, and
417// records the outcome voided-withdrawn. It reports whether it deleted it.
418func (in *integrator) void(r request, ref string) bool {
419 watch := newStopwatch()
420 done := watch.stage(stageRefusal)
421 rec, err := in.readRecord(ref)
422 done()
423 if err != nil || rec.State != change.Withdrawn {
424 return false
425 }
426 if id, named := change.RequestID(r.change); !(named && id == rec.ChangeID) {
427 if _, found := versionAt(rec, r.head); !found {
428 return false
429 }
430 }
431 tip, ok, err := resolveRef(in.repo, r.target)
432 if err != nil || !ok {
433 return false
434 }
435 evidence, err := in.evidenceState()
436 if err != nil {
437 return false
438 }
439 if _, err := git(in.repo, "update-ref", "-d", r.ref, r.head); err != nil {
440 return false
441 }
442 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), voidedWithdrawn)
443 fmt.Fprintf(in.out, " change %s is withdrawn, which voids its requests; the request is deleted, and the change needs a fresh approval once it is ready again\n", rec.ChangeID)
444 printTiming := in.timing(r, tip, string(voidedWithdrawn), watch)
445 if err := in.writeMemo(r, fmt.Sprintf("%s %s %s %s", r.head, tip, evidence, voidedWithdrawn)); err != nil {
446 fmt.Fprintf(in.out, " the outcome was not recorded: %v\n", err)
447 }
448 printTiming()
449 return true
450}
451
452// versionAt is the version of a record whose head is oid.
453func versionAt(r *change.Record, oid string) (change.Version, bool) {
454 for _, v := range r.Versions {
455 if v.Head == change.HeadPrefix+oid {
456 return v, true
457 }
458 }
459 return change.Version{}, false
460}
461
462// mergeRefusal refuses a request whose commits from its merge base with
463// the tip to its head include a merge. Those are the commits the head
464// would bring to the target: tip..head.
465func (in *integrator) mergeRefusal(r request, tip string) (verdict.Outcome, string, error) {
466 merge, err := gitLine(in.repo, "rev-list", "--min-parents=2", "--max-count=1", r.head, "^"+tip)
467 if err != nil {
468 return "", "", fmt.Errorf("cannot read the commits from %s to %s: %w", r.target, verdict.Short(r.head), err)
469 }
470 if merge != "" {
471 return refusedMerge, fmt.Sprintf("the commits from its merge base with %s to its head include the merge %s, and a change is a line of commits", r.target, verdict.Short(merge)), nil
472 }
473 return "", "", nil
474}