gunk-dev/the-valley

export.go

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