gunk-dev/the-valley

record.go

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