gunk-dev/the-valley

records.go

source09393407add1main's published tip history
11.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 its head is a version head of
20// any record that is not ready. The integrator finds those records by
21// head, through an index it builds once per pass from every ref under
22// refs/the-valley/changes/.
23//
24// A third rule reads the request's commits rather than records. A request
25// is refused when the commits from its merge base with the target to its
26// head include a merge. The integrator lands a line of commits, and a
27// merge could make other work look landed by ancestry.
28//
29// A request no record knows, and whose commits hold no merge, is judged as
30// it always was.
31
32import (
33 "the-valley/change"
34 "the-valley/integrator/verdict"
35
36 "bufio"
37 "bytes"
38 "errors"
39 "fmt"
40 "io"
41 "strconv"
42 "strings"
43)
44
45// The outcomes a request is refused with before the commit rule is
46// applied. Like a rejection, a refusal leaves the request where it is. A
47// refusal for a record's state stands only while the record says so: it
48// is decided again on every pass, so a change readied again is judged on
49// the next one.
50const (
51 refusedNotReady verdict.Outcome = "refused-not-ready"
52 refusedMerge verdict.Outcome = "refused-merge"
53)
54
55// recordLimit is the most records the index reads. The hook refuses to
56// create a record past change.MaxRecords, and pushes that run at once can
57// pass that bound only by the records each had in flight. A repository
58// holding more than twice the bound is refused whole: the index could not
59// say which heads are versions of changes that are not ready, so no
60// request lands until records are deleted.
61const recordLimit = 2 * change.MaxRecords
62
63// indexed is one record the index read, and the ref it was read from.
64type indexed struct {
65 ref string
66 record *change.Record
67}
68
69// recordIndex is every record the served repository holds, by the heads
70// its versions name. It is read once per pass.
71type recordIndex struct {
72 byHead map[string][]indexed
73
74 // unreadable is each ref under the namespace that holds no record the
75 // shared parser accepts, with why. A record that does not read names
76 // no head the integrator can see, so it refuses nothing.
77 unreadable []string
78}
79
80// readRecords builds the index from every ref under
81// refs/the-valley/changes/.
82func (in *integrator) readRecords() (*recordIndex, error) {
83 out, err := git(in.repo, "for-each-ref", fmt.Sprintf("--count=%d", recordLimit+1),
84 "--format=%(refname) %(objectname)", change.RefPrefix)
85 if err != nil {
86 return nil, err
87 }
88 var refs, commits []string
89 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
90 if ref, oid, ok := strings.Cut(line, " "); ok {
91 refs = append(refs, ref)
92 commits = append(commits, oid)
93 }
94 }
95 if len(refs) > recordLimit {
96 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)
97 }
98 records, errs, err := in.records(refs, commits)
99 if err != nil {
100 return nil, err
101 }
102 idx := &recordIndex{byHead: map[string][]indexed{}}
103 for i, ref := range refs {
104 if errs[i] != nil {
105 idx.unreadable = append(idx.unreadable, fmt.Sprintf("%s: %v", ref, errs[i]))
106 continue
107 }
108 for _, v := range records[i].Versions {
109 head := strings.TrimPrefix(v.Head, change.HeadPrefix)
110 idx.byHead[head] = append(idx.byHead[head], indexed{ref: ref, record: records[i]})
111 }
112 }
113 return idx, nil
114}
115
116// errNoRecord is a record ref that does not exist.
117var errNoRecord = errors.New("no such record")
118
119// readRecord reads the one record at ref, fresh.
120func (in *integrator) readRecord(ref string) (*change.Record, error) {
121 oid, ok := gitTry(in.repo, "rev-parse", "--verify", "--quiet", ref)
122 if !ok {
123 return nil, errNoRecord
124 }
125 records, errs, err := in.records([]string{ref}, []string{oid})
126 if err != nil {
127 return nil, err
128 }
129 return records[0], errs[0]
130}
131
132// records reads the record each ref points at, under the bounds the hook
133// admits a record under (change.MaxRecordCommit and the rest), each
134// checked before anything past it is read. The record must be the one
135// its ref names: its change ID and its target are the ref's. errs holds
136// why each record that does not read does not; err is for git itself
137// failing.
138func (in *integrator) records(refs, commits []string) (records []*change.Record, errs []error, err error) {
139 records = make([]*change.Record, len(refs))
140 errs = make([]error, len(refs))
141 if len(refs) == 0 {
142 return records, errs, nil
143 }
144 // First the sizes and types: the commit, its tree, and its
145 // record.json, one line each.
146 var query bytes.Buffer
147 for _, c := range commits {
148 fmt.Fprintf(&query, "%s\n%s^{tree}\n%s:record.json\n", c, c, c)
149 }
150 checked, err := gitInput(in.repo, query.Bytes(), "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
151 if err != nil {
152 return nil, nil, err
153 }
154 lines := strings.Split(strings.TrimRight(string(checked), "\n"), "\n")
155 if len(lines) != 3*len(refs) {
156 return nil, nil, fmt.Errorf("git cat-file answered %d lines for %d records", len(lines), len(refs))
157 }
158 var blobs []string
159 var wanted []int
160 for i := range refs {
161 blob, why := withinBounds(lines[3*i : 3*i+3])
162 if why != "" {
163 errs[i] = errors.New(why)
164 continue
165 }
166 blobs = append(blobs, blob)
167 wanted = append(wanted, i)
168 }
169 // Then the contents, of the record.json blobs within bounds alone.
170 contents, err := in.blobs(blobs)
171 if err != nil {
172 return nil, nil, err
173 }
174 for k, i := range wanted {
175 target, id, ok := change.ParseRef(refs[i])
176 if !ok {
177 errs[i] = fmt.Errorf("not a record ref; one is %s<target>/<change ID>", change.RefPrefix)
178 continue
179 }
180 r, err := change.Parse(contents[k])
181 switch {
182 case err != nil:
183 errs[i] = fmt.Errorf("its record.json does not read: %v", err)
184 case r.ChangeID != id || r.Target != target:
185 errs[i] = fmt.Errorf("it records change %s for %s, and its ref names change %s for %s", r.ChangeID, r.Target, id, target)
186 default:
187 records[i] = r
188 }
189 }
190 return records, errs, nil
191}
192
193// withinBounds reads cat-file's three lines about one record — its commit,
194// its tree and its record.json — and returns the blob, or why the record
195// is not one to read.
196func withinBounds(lines []string) (blob, why string) {
197 for k, want := range []struct {
198 what, kind string
199 max int
200 }{
201 {"the record", "commit", change.MaxRecordCommit},
202 {"its tree", "tree", change.MaxRecordTree},
203 {"its record.json", "blob", change.MaxRecordBlob},
204 } {
205 fields := strings.Fields(lines[k])
206 if len(fields) != 3 {
207 return "", fmt.Sprintf("%s is missing", want.what)
208 }
209 size, err := strconv.Atoi(fields[2])
210 switch {
211 case fields[1] != want.kind:
212 return "", fmt.Sprintf("%s is a %s, where a %s is expected", want.what, fields[1], want.kind)
213 case err != nil || size > want.max:
214 return "", fmt.Sprintf("%s is %s bytes, more than the %d a record may hold", want.what, fields[2], want.max)
215 }
216 blob = fields[0]
217 }
218 return blob, ""
219}
220
221// blobs reads each blob's contents with one cat-file.
222func (in *integrator) blobs(oids []string) ([][]byte, error) {
223 if len(oids) == 0 {
224 return nil, nil
225 }
226 out, err := gitInput(in.repo, []byte(strings.Join(oids, "\n")+"\n"), "cat-file", "--batch")
227 if err != nil {
228 return nil, err
229 }
230 rd := bufio.NewReader(bytes.NewReader(out))
231 contents := make([][]byte, len(oids))
232 for i := range oids {
233 header, err := rd.ReadString('\n')
234 if err != nil {
235 return nil, fmt.Errorf("git cat-file --batch: %w", err)
236 }
237 fields := strings.Fields(header)
238 if len(fields) != 3 {
239 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
240 }
241 size, err := strconv.Atoi(fields[2])
242 if err != nil {
243 return nil, fmt.Errorf("git cat-file --batch answered %q", strings.TrimSpace(header))
244 }
245 contents[i] = make([]byte, size)
246 if _, err := io.ReadFull(rd, contents[i]); err != nil {
247 return nil, fmt.Errorf("git cat-file --batch: %w", err)
248 }
249 if _, err := rd.Discard(1); err != nil {
250 return nil, fmt.Errorf("git cat-file --batch: %w", err)
251 }
252 }
253 return contents, nil
254}
255
256// recordRefusal applies the two rules that read records, and returns the
257// refusal and why, or "" when neither refuses. reread reads every record
258// the index found for the head again, as well as the change's own; the
259// pass does that just before it lands, since the checks that come between
260// can take minutes.
261func (in *integrator) recordRefusal(r request, idx *recordIndex, reread bool) (verdict.Outcome, string, error) {
262 target := strings.TrimPrefix(r.target, "refs/heads/")
263 if id, ok := change.RequestID(r.change); ok {
264 ref := change.Ref(target, id)
265 rec, err := in.readRecord(ref)
266 switch {
267 case errors.Is(err, errNoRecord):
268 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and %s holds no record of it", id, ref), nil
269 case err != nil:
270 return refusedNotReady, fmt.Sprintf("the request is named for change %s, and its record %s does not read: %v", id, ref, err), nil
271 case rec.State != change.Ready:
272 return refusedNotReady, fmt.Sprintf("change %s is %s, not ready", id, rec.State), nil
273 }
274 if _, found := versionAt(rec, r.head); !found {
275 return refusedNotReady, fmt.Sprintf("its head %s is no version of change %s", verdict.Short(r.head), id), nil
276 }
277 }
278 for _, n := range idx.byHead[r.head] {
279 rec := n.record
280 if reread {
281 var err error
282 if rec, err = in.readRecord(n.ref); errors.Is(err, errNoRecord) {
283 continue
284 } else if err != nil {
285 return refusedNotReady, fmt.Sprintf("the record %s, which named its head, does not read now: %v", n.ref, err), nil
286 }
287 }
288 v, found := versionAt(rec, r.head)
289 if found && rec.State != change.Ready {
290 return refusedNotReady, fmt.Sprintf("its head %s is v%d of change %s, which is %s, not ready", verdict.Short(r.head), v.N, rec.ChangeID, rec.State), nil
291 }
292 }
293 return "", "", nil
294}
295
296// versionAt is the version of a record whose head is oid.
297func versionAt(r *change.Record, oid string) (change.Version, bool) {
298 for _, v := range r.Versions {
299 if v.Head == change.HeadPrefix+oid {
300 return v, true
301 }
302 }
303 return change.Version{}, false
304}
305
306// mergeRefusal refuses a request whose commits from its merge base with
307// the tip to its head include a merge. Those are the commits the head
308// would bring to the target: tip..head.
309func (in *integrator) mergeRefusal(r request, tip string) (verdict.Outcome, string, error) {
310 merge, err := gitLine(in.repo, "rev-list", "--min-parents=2", "--max-count=1", r.head, "^"+tip)
311 if err != nil {
312 return "", "", fmt.Errorf("cannot read the commits from %s to %s: %w", r.target, verdict.Short(r.head), err)
313 }
314 if merge != "" {
315 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
316 }
317 return "", "", nil
318}