gunk-dev/the-valley

export.go

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