gunk-dev/the-valley

history.go

source57f1659f405fmain's published tip history
17.4 KiB
1package review
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "strings"
9 "time"
10
11 "the-valley/change"
12)
13
14// A change's reviews are kept in one history, at
15// refs/the-valley/reviews/<target>/<change ID>. The ref points at the
16// newest review commit. Each review commit holds one review, as
17// review.json, the one entry of its tree. Its parents say where it stands:
18//
19// first review P = [record]
20// a later review that judges a version P = [previous, record]
21// a withdrawal P = [previous]
22//
23// previous is the review commit before it, the ref's value when the review
24// was appended, and record is the change record commit its binding names.
25// So the first-parent chain is every review in order, and the ref keeps
26// every record a review judged, with the versions that record holds, even
27// once the change's own record ref is deleted.
28//
29// A history is append-only. Each review in it has its own review ID, so a
30// client that publishes a review again, after a push it could not confirm,
31// can tell that it is there already. A withdrawal names a review earlier in
32// the same history that is not itself a withdrawal and that nothing has
33// withdrawn yet, under the same review name. A withdrawal is final: no
34// review withdraws one.
35//
36// An append is a compare-and-swap. The pusher moves the ref from the
37// history's head as they read it to a commit whose first parent is that
38// head, and the move fails if the ref has moved since. They then read the
39// new head and append again; their review keeps its ID, so the retry needs
40// no new judgment. CheckAppend is what the push hook holds an append to.
41
42// RefPrefix opens every review history's ref.
43const RefPrefix = "refs/the-valley/reviews/"
44
45// File is the one file of a review commit's tree.
46const File = "review.json"
47
48// The bounds on the objects that hold reviews, and on a history. A review
49// commit names a tree, at most two parents, an author, a committer and a
50// short message, and its tree names one file. A history holds at most
51// MaxHistory reviews, so reading one whole is bounded too.
52const (
53 MaxCommit = 4 << 10 // bytes in a review commit
54 MaxTree = 1 << 10 // bytes in its tree
55 MaxHistory = 512 // reviews in one history
56)
57
58// reviewLayout is a review commit's layout.
59var reviewLayout = oneFile{subject: "the review commit", name: File, commit: MaxCommit, tree: MaxTree, blob: MaxRecord}
60
61// Ref is the ref a change's review history lives at.
62func Ref(target, id string) string {
63 return RefPrefix + target + "/" + id
64}
65
66// ParseRef splits a review history's ref into its target and change ID.
67// It reports false for a ref that is not refs/the-valley/reviews/<target>/<ID>
68// with a branch name as the target and a change ID as the ID.
69func ParseRef(ref string) (target, id string, ok bool) {
70 rest, found := strings.CutPrefix(ref, RefPrefix)
71 if !found {
72 return "", "", false
73 }
74 slash := strings.LastIndexByte(rest, '/')
75 if slash < 0 {
76 return "", "", false
77 }
78 target, id = rest[:slash], rest[slash+1:]
79 if !change.ValidBranch(target) || !change.ValidID(id) {
80 return "", "", false
81 }
82 return target, id, true
83}
84
85// Entry is one review of a history, with the commit that holds it and
86// that commit's parents.
87type Entry struct {
88 Commit string
89 Parents []string
90 Review *Record
91}
92
93// History is a change's reviews, oldest first.
94type History struct {
95 Target, ChangeID string
96 Entries []Entry
97}
98
99// Head is the newest review commit, or "" for an empty history.
100func (h *History) Head() string {
101 if len(h.Entries) == 0 {
102 return ""
103 }
104 return h.Entries[len(h.Entries)-1].Commit
105}
106
107// Find is the review with the ID given, if the history holds one.
108func (h *History) Find(id string) (Entry, bool) {
109 for _, e := range h.Entries {
110 if e.Review.ReviewID == id {
111 return e, true
112 }
113 }
114 return Entry{}, false
115}
116
117// Withdrawal is the withdrawal of the review with the ID given, if the
118// history holds one.
119func (h *History) Withdrawal(id string) (Entry, bool) {
120 for _, e := range h.Entries {
121 if w := e.Review.Withdraws; w != nil && *w == id {
122 return e, true
123 }
124 }
125 return Entry{}, false
126}
127
128// ReadHistory reads the history whose ref is ref and whose head is the
129// commit head, and holds it to the history's rules: every commit is a
130// review commit of the ref's change and target with its parents as the
131// table above gives them, every review ID is its own, and every
132// withdrawal names a review it may withdraw. It reads at most MaxHistory
133// reviews, each within its bounds, by the deadline.
134//
135// It does not verify the bindings, which the push hook verified as each
136// review was appended. A reader that relies on one runs Verify.
137func ReadHistory(r Repo, ref, head string, deadline time.Time) (*History, error) {
138 target, id, ok := ParseRef(ref)
139 if !ok {
140 return nil, fmt.Errorf("%s is not a review history's ref, %s<target>/<change ID>", ref, RefPrefix)
141 }
142 ctx, cancel := context.WithDeadline(context.Background(), deadline)
143 defer cancel()
144 o, err := openObjects(ctx, r, historyBytes)
145 if err != nil {
146 return nil, err
147 }
148 defer o.close()
149 return o.history(target, id, head)
150}
151
152// historyBytes is the most a whole history can take to read.
153const historyBytes = MaxHistory * (MaxCommit + MaxTree + MaxRecord)
154
155// history reads the history of the change id on target whose head is
156// head, newest first, and checks it oldest first.
157func (o *objects) history(target, id, head string) (*History, error) {
158 h := &History{Target: target, ChangeID: id}
159 for commit := head; commit != ""; {
160 if len(h.Entries) == MaxHistory {
161 return nil, fmt.Errorf("the history holds more than the %d reviews a history may", MaxHistory)
162 }
163 e, err := o.entry(target, id, commit)
164 if err != nil {
165 return nil, err
166 }
167 h.Entries = append(h.Entries, e)
168 commit = previous(e)
169 }
170 for i, j := 0, len(h.Entries)-1; i < j; i, j = i+1, j-1 {
171 h.Entries[i], h.Entries[j] = h.Entries[j], h.Entries[i]
172 }
173 checked := &History{Target: target, ChangeID: id}
174 for _, e := range h.Entries {
175 if err := checked.follows(e.Review); err != nil {
176 return nil, fmt.Errorf("the review commit %s: %w", e.Commit, err)
177 }
178 checked.Entries = append(checked.Entries, e)
179 }
180 return h, nil
181}
182
183// entry reads one review commit of the change id on target, and holds its
184// parents to the table above.
185func (o *objects) entry(target, id, commit string) (Entry, error) {
186 parents, file, err := o.readOneFile(commit, reviewLayout)
187 if err != nil {
188 return Entry{}, err
189 }
190 rec, err := Parse(file)
191 if err != nil {
192 return Entry{}, fmt.Errorf("the review commit %s holds a %s that does not read: %w", commit, File, err)
193 }
194 switch {
195 case rec.ChangeID != id:
196 return Entry{}, fmt.Errorf("the review commit %s holds a review of the change %s, and its history is %s's", commit, rec.ChangeID, id)
197 case rec.Target != target:
198 return Entry{}, fmt.Errorf("the review commit %s holds a review on the target %s, and its history is on %s", commit, rec.Target, target)
199 }
200 e := Entry{Commit: commit, Parents: parents, Review: rec}
201 if err := checkParents(e); err != nil {
202 return Entry{}, fmt.Errorf("the review commit %s %w", commit, err)
203 }
204 return e, nil
205}
206
207// checkParents holds a review commit's parents to the table above.
208func checkParents(e Entry) error {
209 p := e.Parents
210 if !e.Review.Judges() {
211 if len(p) != 1 {
212 return fmt.Errorf("holds a withdrawal, and has %d parents where a withdrawal has one: the review before it", len(p))
213 }
214 return nil
215 }
216 record := objectOf(e.Review.Binding.Record)
217 switch {
218 case len(p) != 1 && len(p) != 2:
219 return fmt.Errorf("has %d parents, where a review that judges a version has the review before it, if any, and then the record it binds", len(p))
220 case p[len(p)-1] != record:
221 return fmt.Errorf("has %s as its last parent, and its review binds the record %s, which the commit keeps as its last parent", p[len(p)-1], record)
222 }
223 return nil
224}
225
226// previous is the review commit before e, or "" for the first.
227func previous(e Entry) string {
228 if e.Review.Judges() && len(e.Parents) == 1 {
229 return ""
230 }
231 return e.Parents[0]
232}
233
234// follows refuses a review that may not follow the history h: one whose
235// ID the history holds already, and a withdrawal that names no review of
236// h, names a withdrawal, names a review already withdrawn, or names a
237// review under another review name.
238func (h *History) follows(rec *Record) error {
239 if e, ok := h.Find(rec.ReviewID); ok {
240 return fmt.Errorf("its review_id %s is the ID of the review in %s, and each review has its own", rec.ReviewID, e.Commit)
241 }
242 if rec.Judges() {
243 return nil
244 }
245 w := *rec.Withdraws
246 target, ok := h.Find(w)
247 if !ok {
248 return fmt.Errorf("it withdraws %s, and the history before it holds no review with that ID", w)
249 }
250 if earlier, ok := h.Withdrawal(w); ok {
251 return fmt.Errorf("it withdraws %s, which the review %s withdrew already", w, earlier.Review.ReviewID)
252 }
253 switch {
254 case !target.Review.Judges():
255 return fmt.Errorf("it withdraws %s, which is a withdrawal, and a withdrawal is final", w)
256 case target.Review.Review != rec.Review:
257 return fmt.Errorf("it withdraws %s under the review name %s, and %s is a review named %s", w, rec.Review, w, target.Review.Review)
258 }
259 return nil
260}
261
262// Update is one push's update of a review history's ref: the ref, and the
263// commits it moves from and to. "" or git's all-zero ID is no commit.
264type Update struct {
265 Ref, Old, New string
266}
267
268// Pusher is who pushes an update, and what they may write, as the push
269// hook knows them from its grants.
270type Pusher struct {
271 // Principal is the authenticated principal pushing, or "" for a key
272 // that names none.
273 Principal string
274 // MayReview reports whether the principal may write reviews that
275 // judge a version under a review's name. Nil allows no name. A
276 // withdrawal needs no grant of its name.
277 MayReview func(name string) bool
278 // Operator reports whether the principal may withdraw any review,
279 // whoever wrote it and under whatever name. A reviewer may always
280 // withdraw their own, even once MayReview no longer allows its name.
281 Operator bool
282}
283
284// CheckAppend is the push hook's decision on an update of a review
285// history's ref. It returns nil when the update appends one review, and
286// otherwise an error saying why it does not. The update appends one review
287// when:
288//
289// - the ref is a review history's ref, and the update moves it to a
290// commit rather than deleting it;
291// - the new commit is a review commit of the ref's change and target
292// whose first parent is the old commit, by the table above, and the
293// history at the old commit reads;
294// - the review names the pusher as its reviewer, and may follow the
295// history: its ID is new to it, and a withdrawal names a review of it,
296// under the same review name, that may be withdrawn;
297// - a review that judges a version is under a review name the pusher
298// may write, and a withdrawal names a review the pusher wrote, or any
299// review when the pusher is an operator. A withdrawal needs no grant
300// of its name, so a reviewer whose grant is revoked can still take
301// back their own judgment;
302// - a review that judges a version is about a change the repository
303// records, Against.RecordTip, and its binding verifies against a
304// (Verify).
305//
306// It decides who may write a review only through Pusher, which the hook
307// fills in from its grants. Everything that reads no tree is decided
308// before the binding is verified.
309func CheckAppend(r Repo, u Update, p Pusher, a Against) error {
310 target, id, ok := ParseRef(u.Ref)
311 switch {
312 case !ok:
313 return fmt.Errorf("a review history's ref is %s<target>/<change ID>, with the change ID as 32 letters from k to z", RefPrefix)
314 case none(u.New):
315 return errors.New("a review history keeps every review of the change, and no push deletes one")
316 case p.Principal == "":
317 return errors.New("a review takes writes only from a named principal, and a key that names no principal is none")
318 case a.Budget.Deadline.IsZero():
319 return errors.New("an append is checked within a deadline, and the budget sets none")
320 }
321 ctx, cancel := context.WithDeadline(context.Background(), a.Budget.Deadline)
322 defer cancel()
323 o, err := openObjects(ctx, r, historyBytes)
324 if err != nil {
325 return err
326 }
327 defer o.close()
328 h := &History{Target: target, ChangeID: id}
329 if !none(u.Old) {
330 if h, err = o.history(target, id, u.Old); err != nil {
331 return fmt.Errorf("the history it appends to does not read: %w", err)
332 }
333 }
334 if len(h.Entries) >= MaxHistory {
335 return fmt.Errorf("the history holds %d reviews, the most a history may", MaxHistory)
336 }
337 e, err := o.entry(target, id, u.New)
338 if err != nil {
339 return err
340 }
341 rec := e.Review
342 if rec.Reviewer != p.Principal {
343 return fmt.Errorf("its review names %s as the reviewer, and %s is pushing it", rec.Reviewer, p.Principal)
344 }
345 if err := h.follows(rec); err != nil {
346 return err
347 }
348 // A judgment needs the grant of its name. A withdrawal does not: its
349 // reviewer may take it back after losing the grant, and an operator
350 // may take back any.
351 if rec.Judges() {
352 if p.MayReview == nil || !p.MayReview(rec.Review) {
353 return fmt.Errorf("it is a review named %s, and %s may not write reviews under that name", rec.Review, p.Principal)
354 }
355 } else {
356 withdrawn, _ := h.Find(*rec.Withdraws)
357 if withdrawn.Review.Reviewer != p.Principal && !p.Operator {
358 return fmt.Errorf("it withdraws a review %s wrote, and only its reviewer or an operator may withdraw it", withdrawn.Review.Reviewer)
359 }
360 }
361 switch prev := previous(e); {
362 case prev == h.Head():
363 case h.Head() == "":
364 return fmt.Errorf("it starts the history, and the first review commit has the record it binds as its one parent, where this one has %d parents", len(e.Parents))
365 case prev == "":
366 return fmt.Errorf("it has the record it binds as its one parent, as the first review commit does, and an append has the history's head, %s, as its first parent", h.Head())
367 default:
368 return fmt.Errorf("its first parent is %s, and an append's is the history's head, %s", prev, h.Head())
369 }
370 if !rec.Judges() {
371 return nil
372 }
373 if none(a.RecordTip) {
374 return fmt.Errorf("the repository holds no record of the change %s, and a review judges a version of a recorded change", id)
375 }
376 if err := Verify(r, rec, a); err != nil {
377 return fmt.Errorf("its binding does not verify: %w", err)
378 }
379 return nil
380}
381
382// ErrRecorded is returned by Build when the history holds the review
383// already, as when an earlier publication of it went through unconfirmed.
384var ErrRecorded = errors.New("the history holds this review already")
385
386// Build writes the review commit that appends rec to the history of
387// rec's change whose head is old, "" for none, and returns it. It moves no
388// ref. It reads the history at old and refuses a review that may not
389// follow it, as CheckAppend does. When the history holds a review with
390// rec's ID that encodes as rec does, it returns that review's commit and
391// ErrRecorded.
392// It does not verify the binding: Bind makes one that verifies, and
393// CheckAppend verifies it as the hook will.
394//
395// The commit's author and committer are git's, as the repository's
396// environment and configuration name them.
397func Build(r Repo, old string, rec *Record, deadline time.Time) (string, error) {
398 data, err := Encode(rec)
399 if err != nil {
400 return "", err
401 }
402 ctx, cancel := context.WithDeadline(context.Background(), deadline)
403 defer cancel()
404 o, err := openObjects(ctx, r, historyBytes)
405 if err != nil {
406 return "", err
407 }
408 defer o.close()
409 h := &History{Target: rec.Target, ChangeID: rec.ChangeID}
410 if !none(old) {
411 if h, err = o.history(rec.Target, rec.ChangeID, old); err != nil {
412 return "", fmt.Errorf("the history it appends to does not read: %w", err)
413 }
414 }
415 if e, ok := h.Find(rec.ReviewID); ok {
416 if recorded, err := Encode(e.Review); err == nil && bytes.Equal(recorded, data) {
417 return e.Commit, ErrRecorded
418 }
419 }
420 if len(h.Entries) >= MaxHistory {
421 return "", fmt.Errorf("the history holds %d reviews, the most a history may", MaxHistory)
422 }
423 if err := h.follows(rec); err != nil {
424 return "", err
425 }
426 var parents []string
427 if !none(old) {
428 parents = append(parents, old)
429 }
430 if rec.Judges() {
431 parents = append(parents, objectOf(rec.Binding.Record))
432 }
433 blob, err := git(ctx, r, data, "hash-object", "-w", "--stdin")
434 if err != nil {
435 return "", err
436 }
437 tree, err := git(ctx, r, []byte("100644 blob "+strings.TrimSpace(string(blob))+"\t"+File+"\n"), "mktree")
438 if err != nil {
439 return "", err
440 }
441 args := []string{"commit-tree", strings.TrimSpace(string(tree)), "-m", rec.Verdict + " " + rec.Review + " " + rec.ReviewID}
442 for _, p := range parents {
443 args = append(args, "-p", p)
444 }
445 commit, err := git(ctx, r, nil, args...)
446 if err != nil {
447 return "", err
448 }
449 return strings.TrimSpace(string(commit)), nil
450}
451
452// ErrStale is returned by Publish when the remote's history is no longer
453// at the head the append was built on: another review was appended
454// first. Read the new head, build on it, and publish again.
455var ErrStale = errors.New("the remote's review history has moved since it was read")
456
457// Publish moves the history ref on the remote from old to new, "" for
458// none, and only if the ref is still at old: a compare-and-swap, as git's
459// --force-with-lease makes it.
460func Publish(r Repo, remote, ref, old, new string, deadline time.Time) error {
461 if none(old) {
462 old = ""
463 }
464 ctx, cancel := context.WithDeadline(context.Background(), deadline)
465 defer cancel()
466 out, err := git(ctx, r, nil, "push", "--porcelain", "--force-with-lease="+ref+":"+old, remote, new+":"+ref)
467 if err == nil {
468 return nil
469 }
470 if strings.Contains(string(out), "(stale info)") || strings.Contains(string(out), "(fetch first)") {
471 return ErrStale
472 }
473 return err
474}