gunk-dev/the-valley

record.go

source0cb9a251c595main's published tip history
16.6 KiB
1package main
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "reflect"
8 "strings"
9
10 "the-valley/change"
11)
12
13// A change record is a commit at refs/the-valley/changes/<target>/<change
14// ID> whose tree holds one file, record.json (the change module). The
15// record commit's parents tie it to what it records: a new change's record
16// has the head it marks ready as its one parent, and each later record has
17// the record it replaces as its first parent, then the head of the version
18// it adds, if it adds one. So a record ref holds on to every head the
19// change was ever ready at, as a topic branch holds on to its commits.
20//
21// The bounds on reading one, which the change module defines for every
22// reader of a record. They are far above what the valley command writes,
23// and they are checked before any object is read past them.
24const (
25 maxRecordCommit = change.MaxRecordCommit // bytes in a record commit
26 maxRecordTree = change.MaxRecordTree // bytes in its tree
27 maxRecordBlob = change.MaxRecordBlob // bytes in its record.json
28 maxRecordUpdates = change.MaxRecordUpdates // change record updates in one push
29 maxRecords = change.MaxRecords // change records a repository holds; a soft bound, below
30
31 // recordTarget is the one target a change may name for now.
32 recordTarget = "main"
33)
34
35// oneFile is the layout of a commit whose tree holds one file and nothing
36// else: a change record's, and a restack report's (report.go).
37type oneFile struct {
38 subject string // what such a commit is, as a refusal names it
39 name string // the one file its tree holds
40 commit, tree, blob int // the most bytes each of its objects may hold
41}
42
43var recordLayout = oneFile{
44 subject: "a change record", name: "record.json",
45 commit: maxRecordCommit, tree: maxRecordTree, blob: maxRecordBlob,
46}
47
48// fileCommit is what a commit of one file says: its parents, in order,
49// and its file, unread.
50type fileCommit struct {
51 parents []string
52 file []byte
53}
54
55func (gitRepository) record(id string) (fileCommit, error) {
56 return readOneFile(id, recordLayout)
57}
58
59// readOneFile reads the commit id names as a commit of the layout given,
60// in one stream of its own.
61func readOneFile(id string, layout oneFile) (fileCommit, error) {
62 b := attestationBudget
63 b.subject = layout.subject
64 objects, err := openObjectsWithin(b)
65 if err != nil {
66 return fileCommit{}, err
67 }
68 defer objects.close()
69 return readFileCommit(objects, id, layout)
70}
71
72// readFileCommit reads a commit, its tree and the one file in it, each
73// held to its bound before its content is asked for.
74func readFileCommit(objects *objectStream, id string, l oneFile) (fileCommit, error) {
75 hashSize := len(id) / 2
76 body, err := objects.read(id, "commit", l.commit)
77 if err != nil {
78 return fileCommit{}, fmt.Errorf("it %v", err)
79 }
80 tree, parents, err := commitLinks(body, hashSize)
81 if err != nil {
82 return fileCommit{}, err
83 }
84 entries, err := objects.read(tree, "tree", l.tree)
85 if err != nil {
86 return fileCommit{}, fmt.Errorf("its tree %v", err)
87 }
88 if len(entries) == 0 {
89 return fileCommit{}, fmt.Errorf("its tree is empty, and %s's tree holds %s alone", l.subject, l.name)
90 }
91 mode, name, blob, rest, err := treeEntry(entries, hashSize)
92 switch {
93 case err != nil:
94 return fileCommit{}, fmt.Errorf("its tree %v", err)
95 case len(rest) > 0:
96 return fileCommit{}, fmt.Errorf("its tree holds more than one entry, and %s's tree holds %s alone", l.subject, l.name)
97 case name != l.name || mode != "100644":
98 return fileCommit{}, fmt.Errorf("its tree holds %q with mode %s, and %s's tree holds %s alone, as a plain file", name, mode, l.subject, l.name)
99 }
100 data, err := objects.read(blob, "blob", l.blob)
101 if err != nil {
102 return fileCommit{}, fmt.Errorf("its %s %v", l.name, err)
103 }
104 return fileCommit{parents: parents, file: data}, nil
105}
106
107// commitLinks reads the tree and the parents out of a commit object, as
108// git reads them: a tree line first, and then every parent line that
109// follows it directly. A parent line anywhere later is one git ignores,
110// and a record that holds one is refused rather than read two ways.
111func commitLinks(body []byte, hashSize int) (tree string, parents []string, err error) {
112 header, _, _ := bytes.Cut(body, []byte("\n\n"))
113 lines := strings.Split(string(header), "\n")
114 tree, ok := strings.CutPrefix(lines[0], "tree ")
115 if !ok || !isHexID(tree, hashSize) {
116 return "", nil, errors.New("it is a commit git could not have written: it does not open with its tree")
117 }
118 rest := lines[1:]
119 for len(rest) > 0 && strings.HasPrefix(rest[0], "parent ") {
120 parent := strings.TrimPrefix(rest[0], "parent ")
121 if !isHexID(parent, hashSize) {
122 return "", nil, errors.New("it is a commit git could not have written: a parent is not an object ID")
123 }
124 parents = append(parents, parent)
125 rest = rest[1:]
126 }
127 for _, line := range rest {
128 if strings.HasPrefix(line, "parent ") {
129 return "", nil, errors.New("it names a parent after its other headers, which git does not read as a parent")
130 }
131 }
132 return tree, parents, nil
133}
134
135func (gitRepository) kind(id string) (string, error) {
136 out, err := run(nil, "cat-file", "-t", id)
137 if err != nil {
138 return "", errors.New("names an object this repository does not hold")
139 }
140 return strings.TrimSpace(string(out)), nil
141}
142
143// records counts the refs under refs/the-valley/changes/, past the bound
144// by one at most: for-each-ref stops printing there.
145//
146// The bound it is checked against is soft. A pre-receive hook runs before
147// git installs any ref, and nothing serializes the hooks of two pushes, so
148// pushes running at once can each count the same records and each create
149// more. The repository can then hold more than maxRecords, by at most the
150// record updates those pushes had in flight: maxRecordUpdates each. Once
151// it is over the bound, every later create is refused.
152func (gitRepository) records() (int, error) {
153 out, err := run(nil, "for-each-ref", fmt.Sprintf("--count=%d", maxRecords+1), "--format=x", change.RefPrefix)
154 if err != nil {
155 return 0, err
156 }
157 return bytes.Count(out, []byte("\n")), nil
158}
159
160// checkRecord decides a write to a change record ref, by the table of
161// transitions below, and returns the verb and the reason that refuse it,
162// or "" for the reason when the write is allowed. P is the new record
163// commit's parents, old the ref's value before the push, and h the head a
164// version names.
165//
166// create any named principal P = [h]
167// new version owner or approve holder P = [old, h]
168// unready owner or approve holder P = [old] ready → draft
169// re-ready owner or approve holder P = [old] draft or withdrawn → ready
170// withdraw owner or approve holder P = [old] ready or draft → withdrawn
171// restack restack holder P = [old, h] ready → ready
172// delete approve holder —
173//
174// A new version always leaves the change ready, from whatever state it
175// was in. A record whose one parent is old changes the state and the seq
176// alone. A withdrawn change comes back ready, at the same version or a new
177// one, and never as a draft. Every other combination is refused.
178//
179// The restack row is the one write the restack grant authorises: a
180// principal that neither owns the change nor holds the approve grant adds
181// one version to a change that is ready, on the branch and under the title
182// of the version that was active. It changes no state. A restack holder
183// that owns the change, or holds the approve grant too, writes by those
184// rows instead, unrestricted by this one.
185func (p policy) checkRecord(principal string, u update) (verb, why string) {
186 target, id, ok := change.ParseRef(u.ref)
187 if !ok || target != recordTarget {
188 return "write", fmt.Sprintf("a change record's ref is %s%s/<change ID>, with the change ID as 32 letters from k to z", change.RefPrefix, recordTarget)
189 }
190 if principal == "" {
191 return "write", "a change record takes writes only from a named principal, and a key that names no principal is none"
192 }
193 switch {
194 case isZero(u.new):
195 if !p.grants.holds(principal, grantApprove) {
196 return "delete", fmt.Sprintf("only a principal holding the %s may delete a change record, and %s holds none", approveGrant, principal)
197 }
198 return "delete", ""
199 case isZero(u.old):
200 if p.existingRecords+p.recordCreates > maxRecords {
201 return "create", fmt.Sprintf("the repository holds %d change records, and this push would create %d more, past the %d it may hold", p.existingRecords, p.recordCreates, maxRecords)
202 }
203 return "create", p.checkCreate(principal, target, id, u.new)
204 default:
205 return "update", p.checkUpdate(principal, target, id, u.old, u.new)
206 }
207}
208
209// checkCreate holds a new change's first record to the create row.
210func (p policy) checkCreate(principal, target, id, commit string) string {
211 rc, err := p.repo.record(commit)
212 if err != nil {
213 return err.Error()
214 }
215 if len(rc.parents) != 1 {
216 return fmt.Sprintf("the record that creates a change has the head it marks ready as its one parent, and this one has %d parents", len(rc.parents))
217 }
218 h := rc.parents[0]
219 if why := p.isCommit(h); why != "" {
220 return why
221 }
222 r, err := change.Parse(rc.file)
223 if err != nil {
224 return "its record.json does not read: " + err.Error()
225 }
226 if why := sameChange(r, target, id); why != "" {
227 return why
228 }
229 v := r.Versions[0]
230 switch {
231 case len(r.Versions) != 1:
232 return fmt.Sprintf("a new change's record holds one version, and this one holds %d", len(r.Versions))
233 case v.Head != change.HeadPrefix+h:
234 return fmt.Sprintf("its version 1 names the head %s, and the record commit's parent is %s", v.Head, h)
235 case v.Uploader != principal:
236 return fmt.Sprintf("its version 1 names %s as its uploader, and %s is pushing it", v.Uploader, principal)
237 case r.Owner != principal:
238 return fmt.Sprintf("it names %s as the owner, and a new change is owned by the principal that pushes it, %s", r.Owner, principal)
239 case r.Seq != 1:
240 return fmt.Sprintf("its seq is %d, and a new change's is 1", r.Seq)
241 case r.Active != 1:
242 return fmt.Sprintf("its active is %d, and a new change's is 1", r.Active)
243 case r.State != change.Ready:
244 return fmt.Sprintf("its state is %s, and a new change is %s", r.State, change.Ready)
245 }
246 return ""
247}
248
249// checkUpdate holds an update of a change's record to the rows after
250// create. Which row applies is read from the record commit's parents, and
251// the record has to say what that row says.
252func (p policy) checkUpdate(principal, target, id, old, commit string) string {
253 prev, err := p.repo.record(old)
254 if err != nil {
255 return "the record it replaces " + err.Error()
256 }
257 before, err := change.Parse(prev.file)
258 if err != nil {
259 return "the record it replaces does not read: " + err.Error()
260 }
261 // restack is whether the restack grant is what authorises the write,
262 // which holds it to the restack row alone.
263 restack := false
264 if principal != before.Owner && !p.grants.holds(principal, grantApprove) {
265 if !p.grants.holds(principal, grantRestack) {
266 return fmt.Sprintf("only the change's owner, %s, or a principal holding the %s may update its record", before.Owner, approveGrant)
267 }
268 if before.State != change.Ready {
269 return fmt.Sprintf("the change is %s, and the %s grant adds a version only to a change that is %s", before.State, grantRestack, change.Ready)
270 }
271 restack = true
272 }
273 rc, err := p.repo.record(commit)
274 if err != nil {
275 return err.Error()
276 }
277 after, err := change.Parse(rc.file)
278 if err != nil {
279 return "its record.json does not read: " + err.Error()
280 }
281 if why := sameChange(after, target, id); why != "" {
282 return why
283 }
284 switch {
285 case len(rc.parents) == 1 && rc.parents[0] == old:
286 if restack {
287 return fmt.Sprintf("a record whose one parent is the record it replaces changes the change's state, and the %s grant changes no state: it only adds a version", grantRestack)
288 }
289 return checkStateChange(before, after)
290 case len(rc.parents) == 2 && rc.parents[0] == old:
291 h := rc.parents[1]
292 if why := p.isCommit(h); why != "" {
293 return why
294 }
295 if why := checkNewVersion(principal, before, after, h); why != "" || !restack {
296 return why
297 }
298 return checkRestack(before, after)
299 default:
300 return "a record that updates a change has the record it replaces as its first parent, and no other parent but the head of the version it adds"
301 }
302}
303
304// checkStateChange holds a record whose one parent is the record it
305// replaces to the unready, re-ready and withdraw rows: the state changes,
306// by one of those rows, and the seq goes up by one. Nothing else changes,
307// and so the active version stays.
308func checkStateChange(before, after *change.Record) string {
309 switch {
310 case after.State == before.State:
311 return fmt.Sprintf("the change is %s already, and a record whose one parent is the record it replaces changes the state", before.State)
312 case before.State == change.Withdrawn && after.State == change.Draft:
313 return "the change is withdrawn, and a withdrawn change comes back ready, never as a draft"
314 case after.Seq != before.Seq+1:
315 return fmt.Sprintf("its seq is %d, and an update's is the seq before it plus one, %d", after.Seq, before.Seq+1)
316 case after.Owner != before.Owner:
317 return fmt.Sprintf("it changes the owner from %s to %s, and no update does", before.Owner, after.Owner)
318 case after.Active != before.Active:
319 return fmt.Sprintf("it changes active from %d to %d, and a change of state keeps the active version", before.Active, after.Active)
320 case !reflect.DeepEqual(after.Versions, before.Versions):
321 return "it changes the versions, and a change of state changes only the state and the seq"
322 }
323 return ""
324}
325
326// checkNewVersion holds a new version to adding exactly one version, at
327// the head h, and to the fields that follow from it.
328func checkNewVersion(principal string, before, after *change.Record, h string) string {
329 if len(after.Versions) != len(before.Versions)+1 {
330 return fmt.Sprintf("a new version adds one version to the %d before it, and this record holds %d", len(before.Versions), len(after.Versions))
331 }
332 for i, v := range before.Versions {
333 if after.Versions[i] != v {
334 return fmt.Sprintf("it changes version %d, and the versions before a new one stay exactly as they were", v.N)
335 }
336 }
337 v := after.Last()
338 switch {
339 case v.Head != change.HeadPrefix+h:
340 return fmt.Sprintf("its new version names the head %s, and the record commit's second parent is %s", v.Head, h)
341 case v.Head == before.ActiveVersion().Head:
342 return fmt.Sprintf("its new version's head is the active version's, %s, and a new version needs a new head", v.Head)
343 case v.Uploader != principal:
344 return fmt.Sprintf("its new version names %s as its uploader, and %s is pushing it", v.Uploader, principal)
345 case after.Active != v.N:
346 return fmt.Sprintf("its active is %d, and a new version becomes the active one, %d", after.Active, v.N)
347 case after.State != change.Ready:
348 return fmt.Sprintf("its state is %s, and a new version makes the change %s", after.State, change.Ready)
349 case after.Seq != before.Seq+1:
350 return fmt.Sprintf("its seq is %d, and an update's is the seq before it plus one, %d", after.Seq, before.Seq+1)
351 case after.Owner != before.Owner:
352 return fmt.Sprintf("it changes the owner from %s to %s, and no update does", before.Owner, after.Owner)
353 }
354 return ""
355}
356
357// checkRestack holds a new version that the restack grant authorises to
358// the restack row, past what checkNewVersion holds every new version to:
359// the change was ready before it, and the new version keeps the branch and
360// the title of the version that was active.
361func checkRestack(before, after *change.Record) string {
362 was, v := before.ActiveVersion(), after.Last()
363 switch {
364 case v.Branch != was.Branch:
365 return fmt.Sprintf("its new version names the branch %q, and the %s grant adds a version on the branch of the active one, %q", v.Branch, grantRestack, was.Branch)
366 case v.Title != was.Title:
367 return fmt.Sprintf("its new version is titled %q, and the %s grant adds a version under the title of the active one, %q", v.Title, grantRestack, was.Title)
368 }
369 return ""
370}
371
372// sameChange holds a record to naming the change and the target its ref
373// names. Neither ever changes, so an update keeps them too.
374func sameChange(r *change.Record, target, id string) string {
375 switch {
376 case r.ChangeID != id:
377 return fmt.Sprintf("it names the change %s, and its ref names %s", r.ChangeID, id)
378 case r.Target != target:
379 return fmt.Sprintf("it names the target %s, and its ref names %s", r.Target, target)
380 }
381 return ""
382}
383
384// isCommit refuses a head that is not a commit.
385func (p policy) isCommit(h string) string {
386 kind, err := p.repo.kind(h)
387 switch {
388 case err != nil:
389 return fmt.Sprintf("its head %s %v", h, err)
390 case kind != "commit":
391 return fmt.Sprintf("its head %s is a %s, and a head is a commit", h, kind)
392 }
393 return ""
394}
395
396func isHexID(s string, size int) bool {
397 if len(s) != 2*size {
398 return false
399 }
400 for _, c := range []byte(s) {
401 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
402 return false
403 }
404 }
405 return true
406}