gunk-dev/the-valley

history.go

source826ad0ddebbcmain's published tip history
16.9 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 under a
275 // review's name. Nil allows no name.
276 MayReview func(name string) bool
277 // Operator reports whether the principal may withdraw any review,
278 // whoever wrote it and under whatever name. A reviewer may always
279 // withdraw their own.
280 Operator bool
281}
282
283// CheckAppend is the push hook's decision on an update of a review
284// history's ref. It returns nil when the update appends one review, and
285// otherwise an error saying why it does not. The update appends one review
286// when:
287//
288// - the ref is a review history's ref, and the update moves it to a
289// commit rather than deleting it;
290// - the new commit is a review commit of the ref's change and target
291// whose first parent is the old commit, by the table above, and the
292// history at the old commit reads;
293// - the review names the pusher as its reviewer, under a review name
294// the pusher may write, and the review may follow the history: its ID
295// is new to it, and a withdrawal names a review the pusher wrote, or
296// any review when the pusher is an operator, who needs no name;
297// - a review that judges a version is about a change the repository
298// records, Against.RecordTip, and its binding verifies against a
299// (Verify).
300//
301// It decides who may write a review only through Pusher, which the hook
302// fills in from its grants. Everything that reads no tree is decided
303// before the binding is verified.
304func CheckAppend(r Repo, u Update, p Pusher, a Against) error {
305 target, id, ok := ParseRef(u.Ref)
306 switch {
307 case !ok:
308 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)
309 case none(u.New):
310 return errors.New("a review history keeps every review of the change, and no push deletes one")
311 case p.Principal == "":
312 return errors.New("a review takes writes only from a named principal, and a key that names no principal is none")
313 case a.Budget.Deadline.IsZero():
314 return errors.New("an append is checked within a deadline, and the budget sets none")
315 }
316 ctx, cancel := context.WithDeadline(context.Background(), a.Budget.Deadline)
317 defer cancel()
318 o, err := openObjects(ctx, r, historyBytes)
319 if err != nil {
320 return err
321 }
322 defer o.close()
323 h := &History{Target: target, ChangeID: id}
324 if !none(u.Old) {
325 if h, err = o.history(target, id, u.Old); err != nil {
326 return fmt.Errorf("the history it appends to does not read: %w", err)
327 }
328 }
329 if len(h.Entries) >= MaxHistory {
330 return fmt.Errorf("the history holds %d reviews, the most a history may", MaxHistory)
331 }
332 e, err := o.entry(target, id, u.New)
333 if err != nil {
334 return err
335 }
336 rec := e.Review
337 if rec.Reviewer != p.Principal {
338 return fmt.Errorf("its review names %s as the reviewer, and %s is pushing it", rec.Reviewer, p.Principal)
339 }
340 if err := h.follows(rec); err != nil {
341 return err
342 }
343 if rec.Judges() || !p.Operator {
344 if p.MayReview == nil || !p.MayReview(rec.Review) {
345 return fmt.Errorf("it is a review named %s, and %s may not write reviews under that name", rec.Review, p.Principal)
346 }
347 }
348 if !rec.Judges() {
349 withdrawn, _ := h.Find(*rec.Withdraws)
350 if withdrawn.Review.Reviewer != p.Principal && !p.Operator {
351 return fmt.Errorf("it withdraws a review %s wrote, and only its reviewer or an operator may withdraw it", withdrawn.Review.Reviewer)
352 }
353 }
354 switch prev := previous(e); {
355 case prev == h.Head():
356 case h.Head() == "":
357 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))
358 case prev == "":
359 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())
360 default:
361 return fmt.Errorf("its first parent is %s, and an append's is the history's head, %s", prev, h.Head())
362 }
363 if !rec.Judges() {
364 return nil
365 }
366 if none(a.RecordTip) {
367 return fmt.Errorf("the repository holds no record of the change %s, and a review judges a version of a recorded change", id)
368 }
369 if err := Verify(r, rec, a); err != nil {
370 return fmt.Errorf("its binding does not verify: %w", err)
371 }
372 return nil
373}
374
375// ErrRecorded is returned by Build when the history holds the review
376// already, as when an earlier publication of it went through unconfirmed.
377var ErrRecorded = errors.New("the history holds this review already")
378
379// Build writes the review commit that appends rec to the history of
380// rec's change whose head is old, "" for none, and returns it. It moves no
381// ref. It reads the history at old and refuses a review that may not
382// follow it, as CheckAppend does. When the history holds a review with
383// rec's ID that encodes as rec does, it returns that review's commit and
384// ErrRecorded.
385// It does not verify the binding: Bind makes one that verifies, and
386// CheckAppend verifies it as the hook will.
387//
388// The commit's author and committer are git's, as the repository's
389// environment and configuration name them.
390func Build(r Repo, old string, rec *Record, deadline time.Time) (string, error) {
391 data, err := Encode(rec)
392 if err != nil {
393 return "", err
394 }
395 ctx, cancel := context.WithDeadline(context.Background(), deadline)
396 defer cancel()
397 o, err := openObjects(ctx, r, historyBytes)
398 if err != nil {
399 return "", err
400 }
401 defer o.close()
402 h := &History{Target: rec.Target, ChangeID: rec.ChangeID}
403 if !none(old) {
404 if h, err = o.history(rec.Target, rec.ChangeID, old); err != nil {
405 return "", fmt.Errorf("the history it appends to does not read: %w", err)
406 }
407 }
408 if e, ok := h.Find(rec.ReviewID); ok {
409 if recorded, err := Encode(e.Review); err == nil && bytes.Equal(recorded, data) {
410 return e.Commit, ErrRecorded
411 }
412 }
413 if len(h.Entries) >= MaxHistory {
414 return "", fmt.Errorf("the history holds %d reviews, the most a history may", MaxHistory)
415 }
416 if err := h.follows(rec); err != nil {
417 return "", err
418 }
419 var parents []string
420 if !none(old) {
421 parents = append(parents, old)
422 }
423 if rec.Judges() {
424 parents = append(parents, objectOf(rec.Binding.Record))
425 }
426 blob, err := git(ctx, r, data, "hash-object", "-w", "--stdin")
427 if err != nil {
428 return "", err
429 }
430 tree, err := git(ctx, r, []byte("100644 blob "+strings.TrimSpace(string(blob))+"\t"+File+"\n"), "mktree")
431 if err != nil {
432 return "", err
433 }
434 args := []string{"commit-tree", strings.TrimSpace(string(tree)), "-m", rec.Verdict + " " + rec.Review + " " + rec.ReviewID}
435 for _, p := range parents {
436 args = append(args, "-p", p)
437 }
438 commit, err := git(ctx, r, nil, args...)
439 if err != nil {
440 return "", err
441 }
442 return strings.TrimSpace(string(commit)), nil
443}
444
445// ErrStale is returned by Publish when the remote's history is no longer
446// at the head the append was built on: another review was appended
447// first. Read the new head, build on it, and publish again.
448var ErrStale = errors.New("the remote's review history has moved since it was read")
449
450// Publish moves the history ref on the remote from old to new, "" for
451// none, and only if the ref is still at old: a compare-and-swap, as git's
452// --force-with-lease makes it.
453func Publish(r Repo, remote, ref, old, new string, deadline time.Time) error {
454 if none(old) {
455 old = ""
456 }
457 ctx, cancel := context.WithDeadline(context.Background(), deadline)
458 defer cancel()
459 out, err := git(ctx, r, nil, "push", "--porcelain", "--force-with-lease="+ref+":"+old, remote, new+":"+ref)
460 if err == nil {
461 return nil
462 }
463 if strings.Contains(string(out), "(stale info)") || strings.Contains(string(out), "(fetch first)") {
464 return ErrStale
465 }
466 return err
467}