gunk-dev/the-valley

export.go

sourceba15a5d4fa13main's published tip history
11.6 KiB
1package export
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "reflect"
11 "unicode"
12 "unicode/utf8"
13
14 "the-valley/knot"
15)
16
17// Schema is the export.json document's schema. A change to any field's
18// name or meaning is a new schema version.
19const Schema = "valley-web-export/v1"
20
21// Visibility is who may read an exported project. Public is the only
22// visibility v1 carries: the export holds what an anonymous reader may see.
23type Visibility string
24
25const Public Visibility = "public"
26
27// Export is export.json: every public project of one valley, as an
28// anonymous reader may see it.
29type Export struct {
30 Schema string `json:"schema"`
31 // Collected is when the plan was read (valley-plan/v1's now), in
32 // RFC 3339. It is display-time: the content digest leaves it out.
33 Collected string `json:"collected"`
34 Projects []Project `json:"projects"`
35}
36
37// Project is one exported project. Its two tips are different refs: the
38// graph tip is refs/the-valley/knots, which its knots were read at, and
39// the source tip is main, which its bundle carries.
40type Project struct {
41 Name string `json:"project"`
42 Visibility Visibility `json:"visibility"`
43 // GraphTip is "" for a project with no plan graph.
44 GraphTip string `json:"graph_tip"`
45 SourceTip string `json:"source_tip"`
46 // Roots are the outcomes with no parent, in tree order.
47 Roots []string `json:"roots"`
48 // Knots are every knot, in tree order, each with its body and comments.
49 Knots []Knot `json:"knots"`
50 // InFlight are the active knots that are claimed, the oldest claim
51 // first, then the active knots whose status is in-progress and that
52 // nobody claims, in tree order.
53 InFlight []string `json:"in_flight"`
54 OpenResiduals []Residuals `json:"open_residuals"`
55 // Changes are the changes ready for approval: ready, with an active
56 // version that has not landed.
57 Changes []Change `json:"changes"`
58}
59
60// Knot is one knot: its fields, what the graph derives of it, its edges to
61// other projects' knots, and its body and comments. Every principal name
62// in it has passed through the publisher's display mapping.
63type Knot struct {
64 ID string `json:"id"`
65 Type string `json:"type"`
66 Status string `json:"status"`
67 Active bool `json:"active"`
68 Title string `json:"title"`
69 Created string `json:"created"`
70 CreatedBy string `json:"created_by"`
71 Source string `json:"source,omitempty"`
72 Parent string `json:"parent,omitempty"`
73 Owner string `json:"owner,omitempty"`
74 BlockedBy []string `json:"blocked_by"`
75 Changes []string `json:"changes"`
76 Target string `json:"target,omitempty"`
77 GraduatedInto string `json:"graduated_into,omitempty"`
78
79 // State is valley-plan/v1's: ready, in-progress, blocked, active,
80 // done or abandoned.
81 State string `json:"state"`
82 Ready bool `json:"ready"`
83 WaitingOn []string `json:"waiting_on"`
84 ClearedByEnding []string `json:"cleared_by_ending"`
85 Dangling []string `json:"dangling"`
86 Unresolved []string `json:"unresolved"`
87 Children []string `json:"children"`
88 Blocks []string `json:"blocks"`
89 Progress *Progress `json:"progress,omitempty"`
90 Claim *Claim `json:"claim,omitempty"`
91 Edges []Edge `json:"edges"`
92
93 Body string `json:"body"`
94 Comments []Comment `json:"comments"`
95 CommentCount int `json:"comment_count"`
96}
97
98// Progress is a parent's finished descendants, out of those not abandoned.
99type Progress struct {
100 Done int `json:"done"`
101 Of int `json:"of"`
102}
103
104// Claim is a knot's claim. AgeSeconds and Stale are as of Collected; they
105// are display-time, and a reader derives a claim's age from At.
106type Claim struct {
107 By string `json:"by"`
108 At string `json:"at"`
109 AgeSeconds int64 `json:"age_seconds"`
110 Stale bool `json:"stale"`
111}
112
113// Edge is a reference to another project's knot, from blocked_by or
114// target. State is resolved or dangling, as valley-plan/v1 says, or hidden
115// when the project is not exported. A hidden edge carries the reference
116// alone: no status, no title and no why.
117type Edge struct {
118 Field string `json:"field"`
119 Ref string `json:"ref"`
120 Project string `json:"project"`
121 ID string `json:"id"`
122 State string `json:"state"`
123 Why *string `json:"why"`
124 Status *string `json:"status"`
125 Title *string `json:"title"`
126}
127
128// Edge states.
129const (
130 EdgeResolved = "resolved"
131 EdgeDangling = "dangling"
132 EdgeHidden = "hidden"
133)
134
135// Comment is one comment on a knot, oldest first. Op is the operation that
136// wrote it, which with the knot names the comment. A comment that has been
137// edited says when it was last edited, in Edited, and by whom, in
138// EditedBy; one never edited has neither.
139type Comment struct {
140 Author string `json:"author"`
141 At string `json:"at"`
142 Op string `json:"op"`
143 Edited string `json:"edited,omitempty"`
144 EditedBy string `json:"edited_by,omitempty"`
145 Body string `json:"body"`
146}
147
148// Residuals are the open bugs under one parent, or under none.
149type Residuals struct {
150 Parent *string `json:"parent"`
151 Bugs []string `json:"bugs"`
152}
153
154// Change is a change ready for approval, with its active version alone.
155type Change struct {
156 ChangeID string `json:"change_id"`
157 Handle string `json:"handle"`
158 Target string `json:"target"`
159 Owner string `json:"owner"`
160 Version Version `json:"version"`
161 // Includes are the changes this one includes that the export carries.
162 Includes []string `json:"includes"`
163 Knots []KnotRef `json:"knots"`
164}
165
166// Version is a change's active version.
167type Version struct {
168 N int `json:"n"`
169 Head string `json:"head"`
170 Title string `json:"title"`
171 Uploader string `json:"uploader"`
172 // Landing is not-landed or uncertain: a ready change's active version
173 // has not landed.
174 Landing string `json:"landing"`
175 Request *Request `json:"request"`
176 Outcome *Outcome `json:"outcome"`
177}
178
179// Request is the integration request that approves the version's head.
180type Request struct {
181 Commit string `json:"commit"`
182}
183
184// Outcome is the integrator's last decision about the version.
185type Outcome struct {
186 Decision string `json:"decision"`
187 Head string `json:"head"`
188 Tip *string `json:"tip"`
189}
190
191// KnotRef is a knot of the same project that links a change.
192type KnotRef struct {
193 ID string `json:"id"`
194 Type string `json:"type"`
195 Status string `json:"status"`
196 Title string `json:"title"`
197}
198
199// Encode writes the export as export.json's bytes: compact JSON and a
200// closing newline.
201func (e *Export) Encode() ([]byte, error) {
202 if err := e.Validate(); err != nil {
203 return nil, err
204 }
205 b, err := json.Marshal(e)
206 if err != nil {
207 return nil, err
208 }
209 return append(b, '\n'), nil
210}
211
212// Decode reads export.json strictly: a field the schema does not name,
213// anything but white space after the document, or an export Validate
214// refuses, fails the read.
215func Decode(data []byte) (*Export, error) {
216 return DecodeContext(context.Background(), bytes.NewReader(data))
217}
218
219// DecodeContext reads and validates an export while ctx remains active.
220func DecodeContext(ctx context.Context, r io.Reader) (*Export, error) {
221 dec := json.NewDecoder(decodeReader{ctx, r})
222 dec.UseNumber()
223 var e Export
224 if err := decodeValue(ctx, dec, reflect.ValueOf(&e).Elem()); err != nil {
225 return nil, fmt.Errorf("export.json: %w", err)
226 }
227 if _, err := dec.Token(); err != io.EOF {
228 if ctx.Err() != nil {
229 return nil, ctx.Err()
230 }
231 return nil, errors.New("export.json holds more than its one document")
232 }
233 if err := e.ValidateContext(ctx); err != nil {
234 return nil, err
235 }
236 return &e, nil
237}
238
239// Validate holds an export to what a server may route by and show without
240// further checks: its schema, project names that are safe as file names,
241// one entry per project in name order, object IDs for tips, and knot IDs
242// that are unique within their project. Text fields are valid UTF-8 with
243// no control character other than a newline or a tab.
244func (e *Export) Validate() error {
245 return e.ValidateContext(context.Background())
246}
247
248// ValidateContext checks the export while ctx remains active.
249func (e *Export) ValidateContext(ctx context.Context) error {
250 if err := ctx.Err(); err != nil {
251 return err
252 }
253 if e.Schema != Schema {
254 return fmt.Errorf("export.json has schema %q, not %q", e.Schema, Schema)
255 }
256 for i, p := range e.Projects {
257 if err := ctx.Err(); err != nil {
258 return err
259 }
260 if !ValidName(p.Name) {
261 return fmt.Errorf("export.json names a project %q, which is not a project name", p.Name)
262 }
263 if i > 0 && e.Projects[i-1].Name >= p.Name {
264 return fmt.Errorf("export.json lists project %s out of order or twice", p.Name)
265 }
266 if p.Visibility != Public {
267 return fmt.Errorf("project %s has visibility %q; v1 exports public projects alone", p.Name, p.Visibility)
268 }
269 if p.GraphTip != "" && !ValidObjectID(p.GraphTip) {
270 return fmt.Errorf("project %s has graph tip %q, which is not an object ID", p.Name, p.GraphTip)
271 }
272 if !ValidObjectID(p.SourceTip) {
273 return fmt.Errorf("project %s has source tip %q, which is not an object ID", p.Name, p.SourceTip)
274 }
275 seen := map[string]bool{}
276 for _, k := range p.Knots {
277 if err := ctx.Err(); err != nil {
278 return err
279 }
280 if !knot.IsLocalID(k.ID) {
281 return fmt.Errorf("project %s holds a knot %q, which is not a knot ID", p.Name, k.ID)
282 }
283 if seen[k.ID] {
284 return fmt.Errorf("project %s holds knot %s twice", p.Name, k.ID)
285 }
286 seen[k.ID] = true
287 for _, s := range []string{k.Title, k.Body, k.Source, k.CreatedBy, k.Owner} {
288 if err := ctx.Err(); err != nil {
289 return err
290 }
291 if !validTextContext(ctx, s) {
292 if err := ctx.Err(); err != nil {
293 return err
294 }
295 return fmt.Errorf("knot %s:%s holds text that is not valid UTF-8 or holds a control character", p.Name, k.ID)
296 }
297 }
298 for _, c := range k.Comments {
299 if err := ctx.Err(); err != nil {
300 return err
301 }
302 if !validTextContext(ctx, c.Body) || !validTextContext(ctx, c.Author) || !validTextContext(ctx, c.EditedBy) || !validTextContext(ctx, c.Edited) {
303 if err := ctx.Err(); err != nil {
304 return err
305 }
306 return fmt.Errorf("a comment on knot %s:%s holds text that is not valid UTF-8 or holds a control character", p.Name, k.ID)
307 }
308 }
309 }
310 for _, c := range p.Changes {
311 if err := ctx.Err(); err != nil {
312 return err
313 }
314 if !ValidObjectID(c.Version.Head) {
315 return fmt.Errorf("change %s of project %s has head %q, which is not an object ID", c.ChangeID, p.Name, c.Version.Head)
316 }
317 }
318 }
319 return nil
320}
321
322// ValidName reports whether s is a project's name: the plan graph's rule
323// for a project's or a principal's name. Such a name holds no slash and
324// cannot be a dot segment, so it is safe as a file name.
325func ValidName(s string) bool { return knot.IsName(s) }
326
327// ValidObjectID reports whether s is a full git object ID, SHA-1 or
328// SHA-256, in lowercase hex.
329func ValidObjectID(s string) bool {
330 return (len(s) == 40 || len(s) == 64) && isHex(s)
331}
332
333func isHex(s string) bool {
334 for _, c := range []byte(s) {
335 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
336 return false
337 }
338 }
339 return true
340}
341
342// validText is valid UTF-8 holding no control character but a newline or
343// a tab.
344func validText(s string) bool {
345 return validTextContext(context.Background(), s)
346}
347
348func validTextContext(ctx context.Context, s string) bool {
349 nextCheck := 0
350 for i := 0; i < len(s); {
351 if i >= nextCheck {
352 if ctx.Err() != nil {
353 return false
354 }
355 nextCheck = i + 4096
356 }
357 r, n := utf8.DecodeRuneInString(s[i:])
358 if (r == utf8.RuneError && n == 1) || (unicode.IsControl(r) && r != '\n' && r != '\t') {
359 return false
360 }
361 i += n
362 }
363 return ctx.Err() == nil
364}