gunk-dev/the-valley

record.go

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