gunk-dev/the-valley

export.go

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