gunk-dev/the-valley

record.go

sourcedc7708a21f33main's published tip history
11.4 KiB
1// Package change is the change record: the versions of one change, as the
2// valley command writes them and the valley's push hook guards them.
3//
4// A change is one piece of work aimed at a target branch, with a stable
5// ID that survives rebases. Each time its author marks a new head ready,
6// the change gains a version. The record lists every version in order,
7// says which one is active, and says whether the change is ready, a draft
8// or withdrawn.
9//
10// A record lives at refs/the-valley/changes/<target>/<change ID>. The ref
11// points at a record commit whose tree holds one file, record.json, in the
12// schema valley-change-record/v1:
13//
14// {
15// "schema": "valley-change-record/v1",
16// "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
17// "target": "main",
18// "owner": "klaus-env",
19// "state": "ready",
20// "seq": 1,
21// "versions": [
22// {"n": 1, "head": "git-sha1:<40 hex>", "title": "the head's subject",
23// "branch": "topic", "uploader": "klaus-env"}
24// ],
25// "active": 1
26// }
27//
28// Reading is strict. The record must be valid UTF-8, name no key twice in
29// any object, hold no field the schema does not, and hold nothing after
30// the object. Every field has exactly the type above, and every integer is
31// in range. This package is the one reading of a record: the valley
32// command reads the record it is about to extend with it, and the hook
33// reads both sides of every pushed update with it, so a record one of them
34// accepts is a record the other accepts.
35//
36// The package depends on the standard library alone, like everything that
37// uses it.
38package change
39
40import (
41 "bytes"
42 "encoding/json"
43 "errors"
44 "fmt"
45 "regexp"
46 "strconv"
47 "strings"
48 "unicode"
49 "unicode/utf8"
50)
51
52// Schema names the record format.
53const Schema = "valley-change-record/v1"
54
55// The states a change can be in. A ready change is one its owner wants
56// landed. A draft is one paused, to be readied again. A withdrawn change is
57// one given up, until it is readied again.
58const (
59 Ready = "ready"
60 Draft = "draft"
61 Withdrawn = "withdrawn"
62)
63
64// The bounds a record is held to.
65const (
66 MaxSeq = 100000 // record updates in a change's life
67 MaxVersions = 1000 // versions of one change
68 MaxTitle = 200 // bytes in a version's title
69)
70
71// The bounds on the objects that hold records. A record commit names a
72// tree, at most two parents, an author, a committer and a short message,
73// and its tree names one file. Every reader holds a record to these before
74// it reads anything past them: the hook as it admits a record, and the
75// integrator and the valley command as they read one back.
76const (
77 MaxRecordCommit = 4 << 10 // bytes in a record commit
78 MaxRecordTree = 1 << 10 // bytes in its tree
79 MaxRecordBlob = 64 << 10 // bytes in its record.json
80 MaxRecordUpdates = 32 // record updates in one push
81
82 // MaxRecords is how many records a repository may hold. The hook
83 // refuses a create past it, but the bound is soft: pushes that run at
84 // once can each count the same records, and each create more.
85 MaxRecords = 2000
86)
87
88// HeadPrefix opens a version's head: the head is named by its hash
89// function and then its object ID.
90const HeadPrefix = "git-sha1:"
91
92// Record is one change's record.
93type Record struct {
94 Schema string `json:"schema"`
95 ChangeID string `json:"change_id"`
96 Target string `json:"target"`
97 Owner string `json:"owner"`
98 State string `json:"state"`
99 Seq int `json:"seq"`
100 Versions []Version `json:"versions"`
101 Active int `json:"active"`
102}
103
104// Version is one head a change was marked ready at.
105type Version struct {
106 N int `json:"n"`
107 Head string `json:"head"`
108 Title string `json:"title"`
109 Branch string `json:"branch"`
110 Uploader string `json:"uploader"`
111}
112
113// ActiveVersion is the version Active names. A record that parsed always
114// has one.
115func (r *Record) ActiveVersion() Version {
116 return r.Versions[r.Active-1]
117}
118
119// Last is the newest version.
120func (r *Record) Last() Version {
121 return r.Versions[len(r.Versions)-1]
122}
123
124// Parse reads record.json, strictly.
125func Parse(data []byte) (*Record, error) {
126 v, err := readJSON(data)
127 if err != nil {
128 return nil, err
129 }
130 o, err := fieldsOf(v, "the record", "schema", "change_id", "target", "owner", "state", "seq", "versions", "active")
131 if err != nil {
132 return nil, err
133 }
134 r := &Record{}
135 for _, f := range []struct {
136 name string
137 into *string
138 }{
139 {"schema", &r.Schema}, {"change_id", &r.ChangeID}, {"target", &r.Target},
140 {"owner", &r.Owner}, {"state", &r.State},
141 } {
142 if *f.into, err = stringOf(o[f.name], f.name); err != nil {
143 return nil, err
144 }
145 }
146 if r.Seq, err = integerOf(o["seq"], "seq", MaxSeq); err != nil {
147 return nil, err
148 }
149 if r.Active, err = integerOf(o["active"], "active", MaxVersions); err != nil {
150 return nil, err
151 }
152 versions := o["versions"]
153 if versions.kind != kindArray {
154 return nil, fmt.Errorf("its versions is %s, where an array is expected", versions.kind)
155 }
156 if len(versions.items) > MaxVersions {
157 return nil, fmt.Errorf("it holds %d versions, more than the %d a change may have", len(versions.items), MaxVersions)
158 }
159 for i, item := range versions.items {
160 where := fmt.Sprintf("versions[%d]", i)
161 vo, err := fieldsOf(item, where, "n", "head", "title", "branch", "uploader")
162 if err != nil {
163 return nil, err
164 }
165 var ver Version
166 if ver.N, err = integerOf(vo["n"], where+".n", MaxVersions); err != nil {
167 return nil, err
168 }
169 for _, f := range []struct {
170 name string
171 into *string
172 }{
173 {"head", &ver.Head}, {"title", &ver.Title}, {"branch", &ver.Branch}, {"uploader", &ver.Uploader},
174 } {
175 if *f.into, err = stringOf(vo[f.name], where+"."+f.name); err != nil {
176 return nil, err
177 }
178 }
179 r.Versions = append(r.Versions, ver)
180 }
181 if err := r.Check(); err != nil {
182 return nil, err
183 }
184 return r, nil
185}
186
187// Check holds a record to everything the schema says beyond the types of
188// its fields: the formats of its strings, the ranges of its integers, and
189// versions numbered 1, 2, 3 with no gap. Every string is UTF-8. git
190// accepts a branch name that is not, and encoding/json would write such a
191// name as another one, so Encode refuses it.
192func (r *Record) Check() error {
193 switch {
194 case r.Schema != Schema:
195 return fmt.Errorf("its schema is %q, where %q is expected", r.Schema, Schema)
196 case !ValidID(r.ChangeID):
197 return fmt.Errorf("its change_id %q is not a change ID: 32 letters from k to z", r.ChangeID)
198 case !ValidBranch(r.Target) || !utf8.ValidString(r.Target):
199 return fmt.Errorf("its target %q is not a branch name in UTF-8", r.Target)
200 case !ValidPrincipal(r.Owner):
201 return fmt.Errorf("its owner %q is not a principal name", r.Owner)
202 case r.State != Ready && r.State != Draft && r.State != Withdrawn:
203 return fmt.Errorf("its state is %q, where %q, %q or %q is expected", r.State, Ready, Draft, Withdrawn)
204 case r.Seq < 1 || r.Seq > MaxSeq:
205 return fmt.Errorf("its seq is %d, outside 1 to %d", r.Seq, MaxSeq)
206 case len(r.Versions) == 0:
207 return errors.New("it holds no version, and a change has at least one")
208 case len(r.Versions) > MaxVersions:
209 return fmt.Errorf("it holds %d versions, more than the %d a change may have", len(r.Versions), MaxVersions)
210 case r.Active < 1 || r.Active > len(r.Versions):
211 return fmt.Errorf("its active is %d, which names none of its %d versions", r.Active, len(r.Versions))
212 }
213 for i, v := range r.Versions {
214 where := fmt.Sprintf("versions[%d]", i)
215 switch {
216 case v.N != i+1:
217 return fmt.Errorf("its %s.n is %d, and versions are numbered 1, 2, 3 in order with no gap", where, v.N)
218 case !ValidHead(v.Head):
219 return fmt.Errorf("its %s.head %q is not %s and 40 lowercase hex digits", where, v.Head, HeadPrefix)
220 case !ValidTitle(v.Title):
221 return fmt.Errorf("its %s.title is not 1 to %d bytes free of control characters", where, MaxTitle)
222 case v.Branch != "" && (!ValidBranch(v.Branch) || !utf8.ValidString(v.Branch)):
223 return fmt.Errorf("its %s.branch %q is not a branch name in UTF-8", where, v.Branch)
224 case !ValidPrincipal(v.Uploader):
225 return fmt.Errorf("its %s.uploader %q is not a principal name", where, v.Uploader)
226 }
227 }
228 return nil
229}
230
231// Encode writes a record as record.json. It refuses a record Parse would
232// refuse, so what it writes always reads back as the same record.
233func Encode(r *Record) ([]byte, error) {
234 if err := r.Check(); err != nil {
235 return nil, fmt.Errorf("the record cannot be written: %w", err)
236 }
237 var buf bytes.Buffer
238 enc := json.NewEncoder(&buf)
239 enc.SetEscapeHTML(false)
240 enc.SetIndent("", " ")
241 if err := enc.Encode(r); err != nil {
242 return nil, err
243 }
244 return buf.Bytes(), nil
245}
246
247// fieldsOf is v's fields, when v is an object holding exactly the fields
248// named, no more and no fewer.
249func fieldsOf(v *value, what string, names ...string) (map[string]*value, error) {
250 if v.kind != kindObject {
251 return nil, fmt.Errorf("%s is %s, where an object is expected", what, v.kind)
252 }
253 for _, key := range v.keys {
254 known := false
255 for _, n := range names {
256 known = known || key == n
257 }
258 if !known {
259 return nil, fmt.Errorf("%s holds the field %q, which the schema does not have", what, key)
260 }
261 }
262 for _, n := range names {
263 if _, ok := v.fields[n]; !ok {
264 return nil, fmt.Errorf("%s has no field %q", what, n)
265 }
266 }
267 return v.fields, nil
268}
269
270func stringOf(v *value, name string) (string, error) {
271 if v.kind != kindString {
272 return "", fmt.Errorf("its %s is %s, where a string is expected", name, v.kind)
273 }
274 return v.text, nil
275}
276
277// integerOf reads an integer from 1 to max. Only a plain run of digits is
278// an integer: 3.0 and 3e0 are numbers of another type.
279func integerOf(v *value, name string, max int) (int, error) {
280 if v.kind != kindNumber {
281 return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.kind)
282 }
283 for _, c := range []byte(v.text) {
284 if c < '0' || c > '9' {
285 return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.text)
286 }
287 }
288 n, err := strconv.Atoi(v.text)
289 if err != nil || n < 1 || n > max {
290 return 0, fmt.Errorf("its %s is %s, outside 1 to %d", name, v.text, max)
291 }
292 return n, nil
293}
294
295// principalName is the shape of a principal's name (#PrincipalName in
296// schema/valley.cue).
297var principalName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
298
299// ValidPrincipal reports whether s is a principal's name.
300func ValidPrincipal(s string) bool {
301 return principalName.MatchString(s)
302}
303
304// ValidHead reports whether s names a head the way a version does.
305func ValidHead(s string) bool {
306 if len(s) != len(HeadPrefix)+40 || s[:len(HeadPrefix)] != HeadPrefix {
307 return false
308 }
309 for _, c := range []byte(s[len(HeadPrefix):]) {
310 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
311 return false
312 }
313 }
314 return true
315}
316
317// ValidTitle reports whether s may be a version's title: UTF-8, 1 to
318// MaxTitle bytes, holding no control character.
319func ValidTitle(s string) bool {
320 if len(s) < 1 || len(s) > MaxTitle || !utf8.ValidString(s) {
321 return false
322 }
323 for _, r := range s {
324 if unicode.IsControl(r) {
325 return false
326 }
327 }
328 return true
329}
330
331// Title makes a version's title from a commit's subject. Each control
332// character becomes a space, and bytes that are not UTF-8 become U+FFFD.
333// The result is cut to MaxTitle bytes at a character boundary. A subject
334// with nothing left is titled "(no subject)".
335func Title(subject string) string {
336 var b strings.Builder
337 for _, r := range strings.ToValidUTF8(subject, "�") {
338 if unicode.IsControl(r) {
339 r = ' '
340 }
341 if b.Len()+utf8.RuneLen(r) > MaxTitle {
342 break
343 }
344 b.WriteRune(r)
345 }
346 if t := strings.TrimSpace(b.String()); t != "" {
347 return t
348 }
349 return "(no subject)"
350}