gunk-dev/the-valley

export.go

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