| 1 | package 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 | |
| 29 | import ( |
| 30 | "the-valley/integrator/verdict" |
| 31 | |
| 32 | "fmt" |
| 33 | "sort" |
| 34 | "strings" |
| 35 | "time" |
| 36 | ) |
| 37 | |
| 38 | const ( |
| 39 | requestPrefix = "refs/the-valley/integration-requests" |
| 40 | outcomePrefix = "refs/the-valley/integration-outcomes" |
| 41 | ) |
| 42 | |
| 43 | // request is one integration request as the refs transport found it. |
| 44 | type request struct { |
| 45 | ref string |
| 46 | change string |
| 47 | target string |
| 48 | head string |
| 49 | } |
| 50 | |
| 51 | // requests lists the pending requests, in ref order so a pass is |
| 52 | // deterministic, along with the refs under the namespace that are not |
| 53 | // requests at all. |
| 54 | // |
| 55 | // Anyone with push access can write this namespace, so a name that does not |
| 56 | // parse is an ordinary thing to find there and not a reason to stop: one |
| 57 | // unreadable ref must not hold up every readable one. It is reported and |
| 58 | // skipped. |
| 59 | func (in *integrator) requests() ([]request, []string, error) { |
| 60 | out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", requestPrefix) |
| 61 | if err != nil { |
| 62 | return nil, nil, err |
| 63 | } |
| 64 | var found []request |
| 65 | var malformed []string |
| 66 | for _, line := range strings.Split(strings.TrimSpace(out), "\n") { |
| 67 | if line == "" { |
| 68 | continue |
| 69 | } |
| 70 | ref, head, ok := strings.Cut(line, " ") |
| 71 | if !ok { |
| 72 | continue |
| 73 | } |
| 74 | rest := strings.TrimPrefix(ref, requestPrefix+"/") |
| 75 | target, change, ok := strings.Cut(rest, "/") |
| 76 | if !ok || strings.Contains(change, "/") || target == "" || change == "" { |
| 77 | malformed = append(malformed, ref) |
| 78 | continue |
| 79 | } |
| 80 | found = append(found, request{ref: ref, change: change, target: "refs/heads/" + target, head: head}) |
| 81 | } |
| 82 | sort.Slice(found, func(i, j int) bool { return found[i].ref < found[j].ref }) |
| 83 | sort.Strings(malformed) |
| 84 | return found, malformed, nil |
| 85 | } |
| 86 | |
| 87 | // reconcile is one pass: judge every request against the current tip of its |
| 88 | // target, and act where the answer has changed. |
| 89 | func (in *integrator) reconcile() error { |
| 90 | requests, malformed, err := in.requests() |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | for _, ref := range malformed { |
| 95 | fmt.Fprintf(in.out, "%s: not a request ref; one is %s/<target>/<change>. Skipped.\n", ref, requestPrefix) |
| 96 | } |
| 97 | for _, r := range requests { |
| 98 | if err := in.handle(r); err != nil { |
| 99 | // One bad request must not stop the pass: the integrator is a |
| 100 | // controller, and a request it cannot judge is one request's |
| 101 | // problem. |
| 102 | fmt.Fprintf(in.out, "%s: %v\n", r.change, err) |
| 103 | } |
| 104 | } |
| 105 | return nil |
| 106 | } |
| 107 | |
| 108 | // handle judges one request and acts on the verdict. |
| 109 | func (in *integrator) handle(r request) error { |
| 110 | tip, err := gitLine(in.repo, "rev-parse", "--verify", "--quiet", r.target) |
| 111 | if err != nil { |
| 112 | return fmt.Errorf("no target %s to integrate onto", r.target) |
| 113 | } |
| 114 | // Level-triggering: the verdict is a function of the request's head, |
| 115 | // the target's tip, and the evidence stored for the change, so an |
| 116 | // unchanged answer is one where none of the three has moved. |
| 117 | // Re-announcing an unchanged answer would be a retry storm; missing a |
| 118 | // moved one would strand a contributor who pushed the attestation a |
| 119 | // previous pass said was absent. |
| 120 | evidence, err := in.evidenceState() |
| 121 | if err != nil { |
| 122 | return err |
| 123 | } |
| 124 | memo := fmt.Sprintf("%s %s %s", r.head, tip, evidence) |
| 125 | if done, err := in.answered(r, memo); err != nil { |
| 126 | return err |
| 127 | } else if done { |
| 128 | return nil |
| 129 | } |
| 130 | // From here on the request has been taken up, so whatever happens is |
| 131 | // this pass's answer to it — including a failure. Recording that is |
| 132 | // what keeps the next tick from asking the identical question. |
| 133 | outcome, err := in.act(r, tip) |
| 134 | if err != nil { |
| 135 | if memoErr := in.writeMemo(r, memo+" "+failedMemo+" "+in.now().Format(time.RFC3339)); memoErr != nil { |
| 136 | return fmt.Errorf("%v (and the failure could not be recorded: %v)", err, memoErr) |
| 137 | } |
| 138 | return err |
| 139 | } |
| 140 | return in.writeMemo(r, memo+" "+string(outcome)) |
| 141 | } |
| 142 | |
| 143 | // failedMemo marks a memo written for a pass that could not act on its own |
| 144 | // verdict, and retryAfter is how long that answer stands. |
| 145 | // |
| 146 | // A failure here is a function of the same three things the verdict is, so |
| 147 | // the identical attempt fails identically until one of them moves — and |
| 148 | // moving any of them already re-judges the request, whatever the memo says. |
| 149 | // The window exists for the other kind of failure: a bus, a disk, a lock, |
| 150 | // something outside the three that will be different later. Minutes rather |
| 151 | // than ticks, because a controller that reports the same refusal every |
| 152 | // fifteen seconds has buried the report it was making. |
| 153 | const ( |
| 154 | failedMemo = "failed" |
| 155 | retryAfter = 10 * time.Minute |
| 156 | ) |
| 157 | |
| 158 | // answered says whether this pass already has this request's answer. An |
| 159 | // outcome stands until the request, the tip, or the evidence moves; a |
| 160 | // recorded failure stands the same way, and additionally expires, so a |
| 161 | // transient one is retried without being retried at tick rate. |
| 162 | func (in *integrator) answered(r request, memo string) (bool, error) { |
| 163 | last, err := in.readMemo(r) |
| 164 | if err != nil || last == "" { |
| 165 | return false, err |
| 166 | } |
| 167 | rest, ok := strings.CutPrefix(last, memo+" ") |
| 168 | if !ok { |
| 169 | return false, nil |
| 170 | } |
| 171 | when, failed := strings.CutPrefix(rest, failedMemo+" ") |
| 172 | if !failed { |
| 173 | return true, nil |
| 174 | } |
| 175 | at, err := time.Parse(time.RFC3339, when) |
| 176 | if err != nil { |
| 177 | return false, nil |
| 178 | } |
| 179 | return in.now().Sub(at) < retryAfter, nil |
| 180 | } |
| 181 | |
| 182 | // act judges one request and does what the verdict says, returning the |
| 183 | // outcome so the memo can record it. |
| 184 | func (in *integrator) act(r request, tip string) (verdict.Outcome, error) { |
| 185 | ch, snap, landed, err := in.materialize(r, tip) |
| 186 | if err != nil { |
| 187 | return "", err |
| 188 | } |
| 189 | v := verdict.Decide(ch, snap) |
| 190 | in.report(r, tip, v) |
| 191 | if landed.composition != "" { |
| 192 | fmt.Fprintf(in.out, " policy %s\n", landed.composition) |
| 193 | } |
| 194 | |
| 195 | switch v.Outcome { |
| 196 | case verdict.Land: |
| 197 | if err := in.land(ch, v, r, tip, landed); err != nil { |
| 198 | return v.Outcome, err |
| 199 | } |
| 200 | case verdict.Stale: |
| 201 | in.publishStale(ch, v, tip) |
| 202 | case verdict.Reject: |
| 203 | // There is no rejection event. The failure model is unified on |
| 204 | // staleness (architecture.md), and a change whose evidence is |
| 205 | // forged is not stale — so rather than stretch either event to |
| 206 | // cover it, the vocabulary stays as it is and the refusal is the |
| 207 | // integrator's own output. The request stays put; nothing about |
| 208 | // it will change on its own. |
| 209 | fmt.Fprintf(in.out, " no event: a forged attestation is not staleness, and the vocabulary has no other word\n") |
| 210 | } |
| 211 | return v.Outcome, nil |
| 212 | } |
| 213 | |
| 214 | // landing is the commit a verdict would move the target to, and what the |
| 215 | // verdict was computed under. |
| 216 | type landing struct { |
| 217 | commit string // the commit that would be the target's new tip |
| 218 | digest string // the valley-tree-v1 digest of the resulting tree |
| 219 | policy string // a digest of the composed policy the verdict used |
| 220 | |
| 221 | // composition is what the pass has to say about how the policy layers |
| 222 | // resolved, or empty when both were where they are configured to be. |
| 223 | composition string |
| 224 | |
| 225 | // notes are the contributor's attestations as stored, by check name. |
| 226 | // The verdict does not read them; what lands countersigns them. |
| 227 | notes map[string][]byte |
| 228 | } |
| 229 | |
| 230 | // materialize gathers everything the verdict is a function of: the applied |
| 231 | // delta, the required checks, the recomputed closures, and what intervening |
| 232 | // landings touched. |
| 233 | func (in *integrator) materialize(r request, tip string) (verdict.Change, verdict.Snapshot, landing, error) { |
| 234 | var land landing |
| 235 | wt, err := addWorktree(in.repo, tip) |
| 236 | if err != nil { |
| 237 | return verdict.Change{}, verdict.Snapshot{}, land, err |
| 238 | } |
| 239 | defer wt.remove() |
| 240 | |
| 241 | base, err := gitLine(in.repo, "merge-base", tip, r.head) |
| 242 | if err != nil { |
| 243 | return verdict.Change{}, verdict.Snapshot{}, land, fmt.Errorf("%s and %s share no history", verdict.Short(r.head), r.target) |
| 244 | } |
| 245 | attested, err := in.treeDigest(wt, r.head) |
| 246 | if err != nil { |
| 247 | return verdict.Change{}, verdict.Snapshot{}, land, err |
| 248 | } |
| 249 | ch := verdict.Change{ID: r.change, Target: r.target, Base: base, Head: r.head, Attested: attested} |
| 250 | if ch.Evidence, land.notes, err = in.collectEvidence(wt, r.head, attested); err != nil { |
| 251 | return ch, verdict.Snapshot{}, land, err |
| 252 | } |
| 253 | |
| 254 | // The policy is read from the integrator's own side and never from the |
| 255 | // tree being gated: the project layer from this checkout of the target |
| 256 | // tip, the floor from the instance repository's integrated tip. Both |
| 257 | // are resolved once and held for the whole pass. |
| 258 | pol, closePolicy, err := in.policy.open(wt) |
| 259 | if err != nil { |
| 260 | return ch, verdict.Snapshot{}, land, err |
| 261 | } |
| 262 | defer closePolicy() |
| 263 | land.composition = pol.note |
| 264 | cat, policyDigest, err := pol.catalogue() |
| 265 | if err != nil { |
| 266 | return ch, verdict.Snapshot{}, land, err |
| 267 | } |
| 268 | land.policy = policyDigest |
| 269 | owed, err := pol.derive(wt, base, r.head) |
| 270 | if err != nil { |
| 271 | return ch, verdict.Snapshot{}, land, err |
| 272 | } |
| 273 | required, err := pol.required(owed, cat) |
| 274 | if err != nil { |
| 275 | return ch, verdict.Snapshot{}, land, err |
| 276 | } |
| 277 | |
| 278 | snap := verdict.Snapshot{Required: required, Touched: map[string]bool{}, Now: in.now()} |
| 279 | |
| 280 | // Apply the delta. A base that is already the tip is a fast-forward: |
| 281 | // the head lands as it stands and its tree is the tree that was |
| 282 | // attested. |
| 283 | if base == tip { |
| 284 | land.commit = r.head |
| 285 | land.digest = attested |
| 286 | snap.Apply = verdict.Applied{Clean: true, Tree: attested} |
| 287 | } else { |
| 288 | tree, conflict, err := mergeDelta(in.repo, base, tip, r.head) |
| 289 | if err != nil { |
| 290 | return ch, snap, land, err |
| 291 | } |
| 292 | if conflict != "" { |
| 293 | snap.Apply = verdict.Applied{Clean: false, Conflict: conflict} |
| 294 | return ch, snap, land, nil |
| 295 | } |
| 296 | if land.commit, err = in.commitTree(tree, tip, r); err != nil { |
| 297 | return ch, snap, land, err |
| 298 | } |
| 299 | if land.digest, err = in.treeDigest(wt, tree); err != nil { |
| 300 | return ch, snap, land, err |
| 301 | } |
| 302 | snap.Apply = verdict.Applied{Clean: true, Tree: land.digest} |
| 303 | |
| 304 | // What intervening landings touched, in the policy's own terms: |
| 305 | // the classes the deriver matches over base..tip. Asking the |
| 306 | // deriver rather than matching globs here keeps one implementation |
| 307 | // of what a class covers. |
| 308 | intervening, err := pol.derive(wt, base, tip) |
| 309 | if err != nil { |
| 310 | return ch, snap, land, err |
| 311 | } |
| 312 | snap.Touched = intervening.classes |
| 313 | } |
| 314 | |
| 315 | // The closures only have to be recomputed when the tree moved: an |
| 316 | // unmoved tree presents the identical computation by construction. |
| 317 | if land.digest != attested { |
| 318 | snap.Closures, snap.ClosureErrors = in.closures(wt, land.commit, required) |
| 319 | } |
| 320 | return ch, snap, land, nil |
| 321 | } |
| 322 | |
| 323 | // commitTree turns the merged tree into the commit that would become the |
| 324 | // target's new tip. The tip is its only parent, so the ref write is a |
| 325 | // fast-forward; the change's authorship is carried over from its head. |
| 326 | func (in *integrator) commitTree(tree, tip string, r request) (string, error) { |
| 327 | message, err := git(in.repo, "log", "-1", "--format=%B", r.head) |
| 328 | if err != nil { |
| 329 | return "", err |
| 330 | } |
| 331 | author, err := git(in.repo, "log", "-1", "--format=%an%n%ae%n%aI", r.head) |
| 332 | if err != nil { |
| 333 | return "", err |
| 334 | } |
| 335 | fields := strings.Split(strings.TrimRight(author, "\n"), "\n") |
| 336 | if len(fields) != 3 { |
| 337 | return "", fmt.Errorf("cannot read the authorship of %s", verdict.Short(r.head)) |
| 338 | } |
| 339 | cmd := []string{"commit-tree", tree, "-p", tip, "-m", strings.TrimRight(message, "\n")} |
| 340 | out, err := in.gitEnv(map[string]string{ |
| 341 | "GIT_AUTHOR_NAME": fields[0], |
| 342 | "GIT_AUTHOR_EMAIL": fields[1], |
| 343 | "GIT_AUTHOR_DATE": fields[2], |
| 344 | }, cmd...) |
| 345 | return strings.TrimSpace(out), err |
| 346 | } |
| 347 | |
| 348 | // land moves the protected ref, stores the evidence, and says so on the |
| 349 | // bus. The ref write is a compare-and-swap against the tip the verdict was |
| 350 | // computed over, so a request that lost a race to another lands nothing and |
| 351 | // is judged again next pass against the tip that won. |
| 352 | // |
| 353 | // The order is the commit point's. Everything that can fail while the |
| 354 | // integrator is still deciding happens first, and the ref write is the |
| 355 | // commit. Composing the transfer statement — vetting it, writing it down, |
| 356 | // signing it — is part of deciding: a claim the integrator cannot write |
| 357 | // down is a claim it has not made, and a stream moved on a decision that |
| 358 | // cannot be stated is a landing nothing records. A failure before the |
| 359 | // commit point leaves the stream where it was and the request where it was, |
| 360 | // which is a transaction abandoned before it committed and costs one pass |
| 361 | // to redo. |
| 362 | // |
| 363 | // Past the commit point the landing is a fact in the stream, and what is |
| 364 | // left is recording it: storing the evidence, consuming the request, and |
| 365 | // saying so on the bus. None of those may be skipped because an earlier one |
| 366 | // failed, and consuming the request in particular may not be reachable only |
| 367 | // through something that can fail — a request left pending for a change |
| 368 | // already in the stream is re-judged against an empty delta on every pass, |
| 369 | // forever. So each step runs, each failure is reported, and the landing is |
| 370 | // reported as having happened, because it did. |
| 371 | func (in *integrator) land(ch verdict.Change, v verdict.Verdict, r request, tip string, l landing) error { |
| 372 | transfer, err := in.composeTransfer(ch, v, l.digest, l.commit, tip, l.policy) |
| 373 | if err != nil { |
| 374 | return err |
| 375 | } |
| 376 | evidence, err := in.countersign(ch, v, l, transfer) |
| 377 | if err != nil { |
| 378 | return err |
| 379 | } |
| 380 | |
| 381 | // The commit point. |
| 382 | if _, err := git(in.repo, "update-ref", ch.Target, l.commit, tip); err != nil { |
| 383 | return fmt.Errorf("%s moved under the verdict; nothing landed: %w", ch.Target, err) |
| 384 | } |
| 385 | fmt.Fprintf(in.out, " landed %s %s -> %s\n", ch.Target, verdict.Short(tip), verdict.Short(l.commit)) |
| 386 | |
| 387 | var unrecorded []string |
| 388 | refs, err := in.store(evidence) |
| 389 | if err != nil { |
| 390 | unrecorded = append(unrecorded, fmt.Sprintf("the evidence was not stored (%v)", err)) |
| 391 | } |
| 392 | for _, ref := range refs { |
| 393 | fmt.Fprintf(in.out, " evidence %s\n", ref) |
| 394 | } |
| 395 | if _, err := git(in.repo, "update-ref", "-d", r.ref); err != nil { |
| 396 | unrecorded = append(unrecorded, fmt.Sprintf("the request ref %s was not consumed (%v)", r.ref, err)) |
| 397 | } |
| 398 | in.publishLanded(ch, v, tip, l.commit) |
| 399 | if len(unrecorded) > 0 { |
| 400 | return fmt.Errorf("%s landed as %s and the landing is not fully recorded: %s", |
| 401 | ch.ID, verdict.Short(l.commit), strings.Join(unrecorded, "; ")) |
| 402 | } |
| 403 | return nil |
| 404 | } |
| 405 | |
| 406 | // report prints the verdict, per check, in the order it was judged. |
| 407 | func (in *integrator) report(r request, tip string, v verdict.Verdict) { |
| 408 | fmt.Fprintf(in.out, "%s -> %s @ %s: %s\n", r.change, r.target, verdict.Short(tip), v.Outcome) |
| 409 | fmt.Fprintf(in.out, " %s\n", v.Reason) |
| 410 | for _, cv := range v.Checks { |
| 411 | if cv.Transferred { |
| 412 | fmt.Fprintf(in.out, " check %-24s transferred (%s)\n", cv.Name, cv.Rule) |
| 413 | continue |
| 414 | } |
| 415 | fmt.Fprintf(in.out, " check %-24s %s\n", cv.Name, cv.Reason) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // The memo is the level-trigger's memory: what this integrator last decided |
| 420 | // about a request, keyed by the request. It is durable in git like |
| 421 | // everything else the transport reads, so a restarted controller does not |
| 422 | // re-announce a judgement it has already made. |
| 423 | func (in *integrator) memoRef(r request) string { |
| 424 | return outcomePrefix + "/" + strings.TrimPrefix(r.ref, requestPrefix+"/") |
| 425 | } |
| 426 | |
| 427 | func (in *integrator) readMemo(r request) (string, error) { |
| 428 | out, ok := gitTry(in.repo, "cat-file", "blob", in.memoRef(r)) |
| 429 | if !ok { |
| 430 | return "", nil |
| 431 | } |
| 432 | return strings.TrimSpace(out), nil |
| 433 | } |
| 434 | |
| 435 | func (in *integrator) writeMemo(r request, value string) error { |
| 436 | blob, err := in.writeBlob([]byte(value + "\n")) |
| 437 | if err != nil { |
| 438 | return err |
| 439 | } |
| 440 | _, err = git(in.repo, "update-ref", in.memoRef(r), blob) |
| 441 | return err |
| 442 | } |
| 443 | |
| 444 | // evidenceState digests the attestation namespace: every ref under it and |
| 445 | // the object it points at. Attestation refs are create-only, so this moves |
| 446 | // exactly when evidence arrives. |
| 447 | // |
| 448 | // It is deliberately the whole namespace rather than the refs for one |
| 449 | // change's subject digest, which would take a checkout to compute and would |
| 450 | // have to be recomputed before the memo could rule the work out. So an |
| 451 | // attestation for one change re-judges every pending request. That is the |
| 452 | // conservative direction — a pass that runs and changes nothing costs a |
| 453 | // pass; a verdict never revisited strands a change — and it is bounded by |
| 454 | // the number of requests pending. |
| 455 | func (in *integrator) evidenceState() (string, error) { |
| 456 | out, err := git(in.repo, "for-each-ref", "--format=%(refname) %(objectname)", attestationPrefix) |
| 457 | if err != nil { |
| 458 | return "", err |
| 459 | } |
| 460 | return sha256hex([]byte(out))[:16], nil |
| 461 | } |
| 462 | |
| 463 | func (in *integrator) now() time.Time { |
| 464 | if !in.clock.IsZero() { |
| 465 | return in.clock |
| 466 | } |
| 467 | return time.Now().UTC() |
| 468 | } |