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