gunk-dev/the-valley

export.go

source876e6ddf614dmain's published tip history
11.5 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 := newTokenDecoder(ctx, r)
222 var e Export
223 if err := decodeValue(ctx, dec, reflect.ValueOf(&e).Elem()); err != nil {
224 return nil, fmt.Errorf("export.json: %w", err)
225 }
226 if _, err := dec.Token(); err != io.EOF {
227 if ctx.Err() != nil {
228 return nil, ctx.Err()
229 }
230 return nil, errors.New("export.json holds more than its one document")
231 }
232 if err := e.ValidateContext(ctx); err != nil {
233 return nil, err
234 }
235 return &e, nil
236}
237
238// Validate holds an export to what a server may route by and show without
239// further checks: its schema, project names that are safe as file names,
240// one entry per project in name order, object IDs for tips, and knot IDs
241// that are unique within their project. Text fields are valid UTF-8 with
242// no control character other than a newline or a tab.
243func (e *Export) Validate() error {
244 return e.ValidateContext(context.Background())
245}
246
247// ValidateContext checks the export while ctx remains active.
248func (e *Export) ValidateContext(ctx context.Context) error {
249 if err := ctx.Err(); err != nil {
250 return err
251 }
252 if e.Schema != Schema {
253 return fmt.Errorf("export.json has schema %q, not %q", e.Schema, Schema)
254 }
255 for i, p := range e.Projects {
256 if err := ctx.Err(); err != nil {
257 return err
258 }
259 if !ValidName(p.Name) {
260 return fmt.Errorf("export.json names a project %q, which is not a project name", p.Name)
261 }
262 if i > 0 && e.Projects[i-1].Name >= p.Name {
263 return fmt.Errorf("export.json lists project %s out of order or twice", p.Name)
264 }
265 if p.Visibility != Public {
266 return fmt.Errorf("project %s has visibility %q; v1 exports public projects alone", p.Name, p.Visibility)
267 }
268 if p.GraphTip != "" && !ValidObjectID(p.GraphTip) {
269 return fmt.Errorf("project %s has graph tip %q, which is not an object ID", p.Name, p.GraphTip)
270 }
271 if !ValidObjectID(p.SourceTip) {
272 return fmt.Errorf("project %s has source tip %q, which is not an object ID", p.Name, p.SourceTip)
273 }
274 seen := map[string]bool{}
275 for _, k := range p.Knots {
276 if err := ctx.Err(); err != nil {
277 return err
278 }
279 if !knot.IsLocalID(k.ID) {
280 return fmt.Errorf("project %s holds a knot %q, which is not a knot ID", p.Name, k.ID)
281 }
282 if seen[k.ID] {
283 return fmt.Errorf("project %s holds knot %s twice", p.Name, k.ID)
284 }
285 seen[k.ID] = true
286 for _, s := range []string{k.Title, k.Body, k.Source, k.CreatedBy, k.Owner} {
287 if err := ctx.Err(); err != nil {
288 return err
289 }
290 if !validTextContext(ctx, s) {
291 if err := ctx.Err(); err != nil {
292 return err
293 }
294 return fmt.Errorf("knot %s:%s holds text that is not valid UTF-8 or holds a control character", p.Name, k.ID)
295 }
296 }
297 for _, c := range k.Comments {
298 if err := ctx.Err(); err != nil {
299 return err
300 }
301 if !validTextContext(ctx, c.Body) || !validTextContext(ctx, c.Author) || !validTextContext(ctx, c.EditedBy) || !validTextContext(ctx, c.Edited) {
302 if err := ctx.Err(); err != nil {
303 return err
304 }
305 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)
306 }
307 }
308 }
309 for _, c := range p.Changes {
310 if err := ctx.Err(); err != nil {
311 return err
312 }
313 if !ValidObjectID(c.Version.Head) {
314 return fmt.Errorf("change %s of project %s has head %q, which is not an object ID", c.ChangeID, p.Name, c.Version.Head)
315 }
316 }
317 }
318 return nil
319}
320
321// ValidName reports whether s is a project's name: the plan graph's rule
322// for a project's or a principal's name. Such a name holds no slash and
323// cannot be a dot segment, so it is safe as a file name.
324func ValidName(s string) bool { return knot.IsName(s) }
325
326// ValidObjectID reports whether s is a full git object ID, SHA-1 or
327// SHA-256, in lowercase hex.
328func ValidObjectID(s string) bool {
329 return (len(s) == 40 || len(s) == 64) && isHex(s)
330}
331
332func isHex(s string) bool {
333 for _, c := range []byte(s) {
334 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
335 return false
336 }
337 }
338 return true
339}
340
341// validText is valid UTF-8 holding no control character but a newline or
342// a tab.
343func validText(s string) bool {
344 return validTextContext(context.Background(), s)
345}
346
347func validTextContext(ctx context.Context, s string) bool {
348 nextCheck := 0
349 for i := 0; i < len(s); {
350 if i >= nextCheck {
351 if ctx.Err() != nil {
352 return false
353 }
354 nextCheck = i + 4096
355 }
356 r, n := utf8.DecodeRuneInString(s[i:])
357 if (r == utf8.RuneError && n == 1) || (unicode.IsControl(r) && r != '\n' && r != '\t') {
358 return false
359 }
360 i += n
361 }
362 return ctx.Err() == nil
363}