gunk-dev/the-valley

records.go

source88a5a486b52fmain's published tip history
17.5 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 // observed is the commit each ref under the namespace held when the
93 // index read it, a record that does not read included.
94 observed map[string]string
95
96 // unreadable is each ref under the namespace that holds no record the
97 // shared parser accepts. A record that does not read names no head the
98 // integrator can see, so it refuses nothing, and a head it names can
99 // land. The hook refuses such a record, so only corrupt storage holds
100 // one, and the pass reports it wherever it may matter.
101 unreadable []unreadable
102}
103
104// unreadable is a ref under the namespace whose record does not read.
105type unreadable struct {
106 ref, commit, why string
107}
108
109// readRecords builds the index from every ref under
110// refs/the-valley/changes/.
111func (in *integrator) readRecords() (*recordIndex, error) {
112 out, err := git(in.repo, "for-each-ref", fmt.Sprintf("--count=%d", recordLimit+1),
113 "--format=%(refname) %(objectname)", change.RefPrefix)
114 if err != nil {
115 return nil, err
116 }
117 var refs, commits []string
118 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
119 if ref, oid, ok := strings.Cut(line, " "); ok {
120 refs = append(refs, ref)
121 commits = append(commits, oid)
122 }
123 }
124 if len(refs) > recordLimit {
125 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)
126 }
127 records, errs, err := in.records(refs, commits)
128 if err != nil {
129 return nil, err
130 }
131 idx := &recordIndex{byHead: map[string][]indexed{}, byRef: map[string]*change.Record{}, observed: map[string]string{}}
132 for i, ref := range refs {
133 idx.observed[ref] = commits[i]
134 if errs[i] != nil {
135 idx.unreadable = append(idx.unreadable, unreadable{ref: ref, commit: commits[i], why: errs[i].Error()})
136 continue
137 }
138 idx.byRef[ref] = records[i]
139 for _, v := range records[i].Versions {
140 head := strings.TrimPrefix(v.Head, change.HeadPrefix)
141 idx.byHead[head] = append(idx.byHead[head], indexed{ref: ref, record: records[i]})
142 }
143 }
144 return idx, nil
145}
146
147// errNoRecord is a record ref that does not exist.
148var errNoRecord = errors.New("no such record")
149
150// readRecord reads the one record at ref, fresh. The ref is read by its
151// exact name, so a branch named like a missing record is no record.
152func (in *integrator) readRecord(ref string) (*change.Record, error) {
153 oid, ok, err := resolveRef(in.repo, ref)
154 if err != nil {
155 return nil, err
156 } else if !ok {
157 return nil, errNoRecord
158 }
159 records, errs, err := in.records([]string{ref}, []string{oid})
160 if err != nil {
161 return nil, err
162 }
163 return records[0], errs[0]
164}
165
166// records reads the record each ref points at, under the bounds the hook
167// admits a record under (change.MaxRecordCommit and the rest), each
168// checked before anything past it is read. The record must be the one
169// its ref names: its change ID and its target are the ref's. errs holds
170// why each record that does not read does not; err is for git itself
171// failing.
172func (in *integrator) records(refs, commits []string) (records []*change.Record, errs []error, err error) {
173 records = make([]*change.Record, len(refs))
174 errs = make([]error, len(refs))
175 if len(refs) == 0 {
176 return records, errs, nil
177 }
178 // First the sizes and types: the commit, its tree, and its
179 // record.json, one line each.
180 var query bytes.Buffer
181 for _, c := range commits {
182 fmt.Fprintf(&query, "%s\n%s^{tree}\n%s:record.json\n", c, c, c)
183 }
184 checked, err := gitInput(in.repo, query.Bytes(), "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
185 if err != nil {
186 return nil, nil, err
187 }
188 lines := strings.Split(strings.TrimRight(string(checked), "\n"), "\n")
189 if len(lines) != 3*len(refs) {
190 return nil, nil, fmt.Errorf("git cat-file answered %d lines for %d records", len(lines), len(refs))
191 }
192 var blobs []string
193 var wanted []int
194 for i := range refs {
195 blob, why := withinBounds(lines[3*i : 3*i+3])
196 if why != "" {
197 errs[i] = errors.New(why)
198 continue
199 }
200 blobs = append(blobs, blob)
201 wanted = append(wanted, i)
202 }
203 // Then the contents, of the record.json blobs within bounds alone.
204 contents, err := in.blobs(blobs)
205 if err != nil {
206 return nil, nil, err
207 }
208 for k, i := range wanted {
209 target, id, ok := change.ParseRef(refs[i])
210 if !ok {
211 errs[i] = fmt.Errorf("not a record ref; one is %s<target>/<change ID>", change.RefPrefix)
212 continue
213 }
214 r, err := change.Parse(contents[k])
215 switch {
216 case err != nil:
217 errs[i] = fmt.Errorf("its record.json does not read: %v", err)
218 case r.ChangeID != id || r.Target != target:
219 errs[i] = fmt.Errorf("it records change %s for %s, and its ref names change %s for %s", r.ChangeID, r.Target, id, target)
220 default:
221 records[i] = r
222 }
223 }
224 return records, errs, nil
225}
226
227// withinBounds reads cat-file's three lines about one record — its commit,
228// its tree and its record.json — and returns the blob, or why the record
229// is not one to read.
230func withinBounds(lines []string) (blob, why string) {
231 for k, want := range []struct {
232 what, kind string
233 max int
234 }{
235 {"the record", "commit", change.MaxRecordCommit},
236 {"its tree", "tree", change.MaxRecordTree},
237 {"its record.json", "blob", change.MaxRecordBlob},
238 } {
239 fields := strings.Fields(lines[k])
240 if len(fields) != 3 {
241 return "", fmt.Sprintf("%s is missing", want.what)
242 }
243 size, err := strconv.Atoi(fields[2])
244 switch {
245 case fields[1] != want.kind:
246 return "", fmt.Sprintf("%s is a %s, where a %s is expected", want.what, fields[1], want.kind)
247 case err != nil || size > want.max:
248 return "", fmt.Sprintf("%s is %s bytes, more than the %d a record may hold", want.what, fields[2], want.max)
249 }
250 blob = fields[0]
251 }
252 return blob, ""
253}
254
255// blobs reads each blob's contents with one cat-file.
256func (in *integrator) blobs(oids []string) ([][]byte, error) {
257 if len(oids) == 0 {
258 return nil, nil
259 }
260 out, err := gitInput(in.repo, []byte(strings.Join(oids, "\n")+"\n"), "cat-file", "--batch")
261 if err != nil {
262 return nil, err
263 }
264 rd := bufio.NewReader(bytes.NewReader(out))
265 contents := make([][]byte, len(oids))
266 for i := range oids {
267 header, err := rd.ReadString('\n')
268 if err != nil {
269 return nil, fmt.Errorf("git cat-file --batch: %w", err)
270 }
271 fields := strings.Fields(header)
272 if len(fields) != 3 {
273 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
274 }
275 size, err := strconv.Atoi(fields[2])
276 if err != nil {
277 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
278 }
279 contents[i] = make([]byte, size)
280 if _, err := io.ReadFull(rd, contents[i]); err != nil {
281 return nil, fmt.Errorf("git cat-file --batch: %w", err)
282 }
283 if _, err := rd.Discard(1); err != nil {
284 return nil, fmt.Errorf("git cat-file --batch: %w", err)
285 }
286 }
287 return contents, nil
288}
289
290// recordRefusal applies the two rules that read records, and returns the
291// refusal and why, or "" when neither refuses. The request's own record,
292// for a request named c-<change ID>, is read fresh; every other record is
293// read from idx.
294func (in *integrator) recordRefusal(r request, idx *recordIndex, tip string) (verdict.Outcome, string, error) {
295 target := strings.TrimPrefix(r.target, "refs/heads/")
296 if id, ok := change.RequestID(r.change); ok {
297 ref := change.Ref(target, id)
298 rec, err := in.readRecord(ref)
299 switch {
300 case errors.Is(err, errNoRecord):
301 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and %s holds no record of it", id, ref), nil
302 case err != nil:
303 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and its record %s does not read: %v", id, ref, err), nil
304 case rec.State != change.Ready:
305 return refusedNotReady, fmt.Sprintf("change %s is %s, not ready", id, rec.State), nil
306 }
307 if _, found := versionAt(rec, r.head); !found {
308 return refusedNotReady, fmt.Sprintf("its head %s is no version of change %s", verdict.Short(r.head), id), nil
309 }
310 }
311 commits, err := in.introduced(r, tip)
312 if err != nil {
313 return "", "", err
314 }
315 for _, c := range commits {
316 for _, n := range idx.byHead[c] {
317 v, found := versionAt(n.record, c)
318 if !found || n.record.State == change.Ready {
319 continue
320 }
321 what := "the commit " + verdict.Short(c) + " it brings"
322 if c == r.head {
323 what = "its head " + verdict.Short(c)
324 }
325 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
326 }
327 }
328 return "", "", nil
329}
330
331// introduced is every commit a request would bring to the target, newest
332// first: those reachable from its head and not from the tip, and the head
333// itself whatever the tip holds.
334func (in *integrator) introduced(r request, tip string) ([]string, error) {
335 out, err := gitLine(in.repo, "rev-list", r.head, "^"+tip)
336 if err != nil {
337 return nil, fmt.Errorf("cannot read the commits from %s to %s: %w", r.target, verdict.Short(r.head), err)
338 }
339 commits := strings.Fields(out)
340 if len(commits) == 0 || commits[0] != r.head {
341 commits = append([]string{r.head}, commits...)
342 }
343 return commits, nil
344}
345
346// finalRefusal applies the record rules once more, immediately before the
347// target moves, with every record read again into a fresh index. A record
348// that came to name one of the request's commits since the pass began is
349// seen here. Only a record written after this read and before the target
350// moves is missed.
351func (in *integrator) finalRefusal(r request, tip string) (verdict.Outcome, string, error) {
352 idx, err := in.readRecords()
353 if err != nil {
354 return "", "", err
355 }
356 return in.recordRefusal(r, idx, tip)
357}
358
359// uncheckable is each record that does not read and may name one of the
360// commits the request brings. A record names its version heads as parents
361// of its record commits, so it can name only a commit its record commit
362// reaches. That is true of some commit the request brings exactly when a
363// merge base of the record commit and the head is not on the tip. A record
364// git cannot compare at all may name anything.
365func (in *integrator) uncheckable(r request, idx *recordIndex, tip string) []unreadable {
366 var found []unreadable
367 for _, u := range idx.unreadable {
368 out, ok := gitTry(in.repo, "merge-base", "--all", u.commit, r.head)
369 may := !ok && out != ""
370 for _, base := range strings.Fields(out) {
371 if !ok {
372 break
373 }
374 if _, onTip := gitTry(in.repo, "merge-base", "--is-ancestor", base, tip); !onTip {
375 may = true
376 }
377 }
378 if may {
379 found = append(found, u)
380 }
381 }
382 return found
383}
384
385// voidWithdrawn deletes the requests a withdrawn change voids, and returns
386// the requests left to judge. A request is voided when it is named for a
387// withdrawn change, or when its head is a version head of one. Before each
388// deletion the record is read again, and the request is deleted only if
389// the change is still withdrawn. The deletion is leased on the head the
390// pass found the request at, so an approval filed since stands. A
391// withdrawal followed by a ready within one pass is not seen, and leaves
392// the request in place.
393func (in *integrator) voidWithdrawn(requests []request, idx *recordIndex) []request {
394 var kept []request
395 for _, r := range requests {
396 if ref := withdrawnFor(r, idx); ref == "" || !in.void(r, ref) {
397 kept = append(kept, r)
398 }
399 }
400 return kept
401}
402
403// withdrawnFor is the ref of a withdrawn change's record that voids the
404// request, as idx read it, or "".
405func withdrawnFor(r request, idx *recordIndex) string {
406 if id, ok := change.RequestID(r.change); ok {
407 ref := change.Ref(strings.TrimPrefix(r.target, "refs/heads/"), id)
408 if rec := idx.byRef[ref]; rec != nil && rec.State == change.Withdrawn {
409 return ref
410 }
411 }
412 for _, n := range idx.byHead[r.head] {
413 if n.record.State == change.Withdrawn {
414 return n.ref
415 }
416 }
417 return ""
418}
419
420// void deletes one request a withdrawn change voids, if the change is
421// still withdrawn and the request still at the head the pass found, and
422// records the outcome voided-withdrawn. It reports whether it deleted it.
423func (in *integrator) void(r request, ref string) bool {
424 watch := newStopwatch()
425 done := watch.stage(stageRefusal)
426 rec, err := in.readRecord(ref)
427 done()
428 if err != nil || rec.State != change.Withdrawn {
429 return false
430 }
431 if id, named := change.RequestID(r.change); !(named && id == rec.ChangeID) {
432 if _, found := versionAt(rec, r.head); !found {
433 return false
434 }
435 }
436 tip, ok, err := resolveRef(in.repo, r.target)
437 if err != nil || !ok {
438 return false
439 }
440 evidence, err := in.evidenceState()
441 if err != nil {
442 return false
443 }
444 if _, err := git(in.repo, "update-ref", "-d", r.ref, r.head); err != nil {
445 return false
446 }
447 fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), voidedWithdrawn)
448 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)
449 printTiming := in.timing(r, tip, string(voidedWithdrawn), watch)
450 if err := in.writeMemo(r, fmt.Sprintf("%s %s %s %s", r.head, tip, evidence, voidedWithdrawn)); err != nil {
451 fmt.Fprintf(in.out, " the outcome was not recorded: %v\n", err)
452 }
453 printTiming()
454 return true
455}
456
457// versionAt is the version of a record whose head is oid.
458func versionAt(r *change.Record, oid string) (change.Version, bool) {
459 for _, v := range r.Versions {
460 if v.Head == change.HeadPrefix+oid {
461 return v, true
462 }
463 }
464 return change.Version{}, false
465}
466
467// mergeRefusal refuses a request whose commits from its merge base with
468// the tip to its head include a merge. Those are the commits the head
469// would bring to the target: tip..head.
470func (in *integrator) mergeRefusal(r request, tip string) (verdict.Outcome, string, error) {
471 merge, err := gitLine(in.repo, "rev-list", "--min-parents=2", "--max-count=1", r.head, "^"+tip)
472 if err != nil {
473 return "", "", fmt.Errorf("cannot read the commits from %s to %s: %w", r.target, verdict.Short(r.head), err)
474 }
475 if merge != "" {
476 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
477 }
478 return "", "", nil
479}