gunk-dev/the-valley

project.go

source32bd55de0d87main's published tip history
13.5 KiB
1package export
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "slices"
8 "sort"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12)
13
14// The schemas of the valley's own JSON the projection reads.
15const (
16 planSchema = "valley-plan/v1"
17 pendingSchema = "valley-pending/v1"
18 detailSchema = "valley-knot/v1"
19)
20
21// ErrInconsistent is the error for inputs read at different graph tips: a
22// knot's detail read after the plan saw a later graph. The publisher reads
23// the inputs again rather than publish them.
24var ErrInconsistent = errors.New("the inputs were read at different graph tips")
25
26// Inputs are what the projection reads: the valley's own JSON, as its
27// commands print it, and the publisher's configuration.
28type Inputs struct {
29 // Plan is `valley plan --all --json`.
30 Plan []byte
31 // Pending is `valley pending --all --json`.
32 Pending []byte
33 // Details are `valley knot show --project P <id> --json`, one for
34 // every knot of every public project.
35 Details [][]byte
36 // Visibility is each project's visibility. A project it does not name
37 // is not exported.
38 Visibility map[string]Visibility
39 // SourceTips are each public project's main.
40 SourceTips map[string]string
41 // Principals is the display mapping principal names pass through.
42 Principals Principals
43}
44
45// Principals maps a principal's name to what an export shows in its place,
46// such as operator or agent. A name it does not map is shown as Unmapped.
47type Principals map[string]string
48
49// Unmapped is what an export shows for a principal the display mapping
50// does not name.
51const Unmapped = "contributor"
52
53// Show is what an export shows for the principal name: its mapping, or
54// Unmapped. The empty name, for a field that names nobody, stays empty.
55func (p Principals) Show(name string) string {
56 if name == "" {
57 return ""
58 }
59 if shown, ok := p[name]; ok {
60 return shown
61 }
62 return Unmapped
63}
64
65// check holds every shown name to 1 to 64 bytes of UTF-8 with no control
66// character.
67func (p Principals) check() error {
68 for name, shown := range p {
69 bad := len(shown) == 0 || len(shown) > 64 || !utf8.ValidString(shown) ||
70 containsControl(shown)
71 if bad {
72 return fmt.Errorf("the display mapping shows %q as %q; a shown name is 1 to 64 bytes of text, with no control character", name, shown)
73 }
74 }
75 return nil
76}
77
78func containsControl(s string) bool {
79 for _, r := range s {
80 if unicode.IsControl(r) {
81 return true
82 }
83 }
84 return false
85}
86
87// The valley's JSON, as far as the projection reads it. A field not named
88// here is never read, so a field the valley adds is not exported until the
89// projection names it.
90type (
91 planDoc struct {
92 Schema string `json:"schema"`
93 Now string `json:"now"`
94 Projects []planProject `json:"projects"`
95 }
96 planProject struct {
97 Project string `json:"project"`
98 Error *string `json:"error"`
99 Tip string `json:"tip"`
100 Roots []string `json:"roots"`
101 Knots []planKnot `json:"knots"`
102 InFlight []string `json:"in_flight"`
103 OpenResiduals []Residuals `json:"open_residuals"`
104 }
105 planKnot struct {
106 ID string `json:"id"`
107 Type string `json:"type"`
108 Status string `json:"status"`
109 Active bool `json:"active"`
110 Title string `json:"title"`
111 Created string `json:"created"`
112 CreatedBy string `json:"created_by"`
113 Source string `json:"source"`
114 Parent string `json:"parent"`
115 Owner string `json:"owner"`
116 BlockedBy []string `json:"blocked_by"`
117 Changes []string `json:"changes"`
118 Target string `json:"target"`
119 GraduatedInto string `json:"graduated_into"`
120 CommentCount int `json:"comment_count"`
121 State string `json:"state"`
122 Ready bool `json:"ready"`
123 WaitingOn []string `json:"waiting_on"`
124 ClearedByEnding []string `json:"cleared_by_ending"`
125 Dangling []string `json:"dangling"`
126 Unresolved []string `json:"unresolved"`
127 Children []string `json:"children"`
128 Blocks []string `json:"blocks"`
129 Progress *Progress `json:"progress"`
130 Claim *Claim `json:"claim"`
131 Edges []Edge `json:"edges"`
132 }
133 detailDoc struct {
134 Schema string `json:"schema"`
135 Project string `json:"project"`
136 Tip string `json:"tip"`
137 Knot struct {
138 ID string `json:"id"`
139 Body *string `json:"body"`
140 Comments []Comment `json:"comments"`
141 } `json:"knot"`
142 }
143 pendingDoc struct {
144 Schema string `json:"schema"`
145 Repos []pendingRepo `json:"repos"`
146 }
147 pendingRepo struct {
148 Repo string `json:"repo"`
149 Error *string `json:"error"`
150 Changes []pendingChange `json:"changes"`
151 }
152 pendingChange struct {
153 ChangeID string `json:"change_id"`
154 Handle string `json:"handle"`
155 Target string `json:"target"`
156 Owner string `json:"owner"`
157 State string `json:"state"`
158 Active int `json:"active"`
159 Versions []pendingVersion `json:"versions"`
160 Includes []string `json:"includes"`
161 Knots []KnotRef `json:"knots"`
162 }
163 pendingVersion struct {
164 N int `json:"n"`
165 Head string `json:"head"`
166 Title string `json:"title"`
167 Uploader string `json:"uploader"`
168 Landing string `json:"landing"`
169 Request *struct {
170 Commit string `json:"commit"`
171 } `json:"request"`
172 Outcome *Outcome `json:"outcome"`
173 }
174)
175
176// detailKey names a knot's detail: IDs are unique within a project, not
177// across projects.
178type detailKey struct{ project, id string }
179
180// Build projects the valley's JSON onto the public export. It is a pure
181// function of its inputs. It exports each project whose visibility is
182// public, and everything of it an anonymous reader may see: every knot,
183// with its body and comments, and the changes ready for approval, each
184// with its active version alone. It leaves out what is not the reader's:
185// the plan's operator sections, drafts, branches, older versions,
186// repository URLs, error text and the file each knot is stored in. A
187// reference to a project that is not exported keeps only the reference,
188// and every principal name passes through the display mapping.
189//
190// A public project whose plan or pending listing could not be read, whose
191// knot lacks its detail, or whose detail was read at another graph tip
192// fails the projection, so a partial export is never published. The last
193// of these is ErrInconsistent.
194func Build(in Inputs) (*Export, error) {
195 if err := in.Principals.check(); err != nil {
196 return nil, err
197 }
198 var plan planDoc
199 if err := decodeInput("the plan", in.Plan, planSchema, &plan, &plan.Schema); err != nil {
200 return nil, err
201 }
202 var pending pendingDoc
203 if err := decodeInput("the pending listing", in.Pending, pendingSchema, &pending, &pending.Schema); err != nil {
204 return nil, err
205 }
206 details := map[detailKey]detailDoc{}
207 for _, raw := range in.Details {
208 var d detailDoc
209 if err := decodeInput("a knot's detail", raw, detailSchema, &d, &d.Schema); err != nil {
210 return nil, err
211 }
212 key := detailKey{d.Project, d.Knot.ID}
213 if _, twice := details[key]; twice {
214 return nil, fmt.Errorf("the details hold knot %s:%s twice", d.Project, d.Knot.ID)
215 }
216 details[key] = d
217 }
218
219 exported := map[string]bool{}
220 for name, v := range in.Visibility {
221 switch v {
222 case Public:
223 exported[name] = true
224 default:
225 return nil, fmt.Errorf("project %s has visibility %q; v1 exports public projects alone", name, v)
226 }
227 }
228 planned := map[string]planProject{}
229 for _, p := range plan.Projects {
230 planned[p.Project] = p
231 }
232 repos := map[string]pendingRepo{}
233 for _, r := range pending.Repos {
234 repos[r.Repo] = r
235 }
236
237 e := &Export{Schema: Schema, Collected: plan.Now, Projects: []Project{}}
238 var names []string
239 for name := range exported {
240 names = append(names, name)
241 }
242 sort.Strings(names)
243 for _, name := range names {
244 p, ok := planned[name]
245 if !ok {
246 return nil, fmt.Errorf("public project %s is not in the plan", name)
247 }
248 if p.Error != nil {
249 return nil, fmt.Errorf("the plan could not read public project %s", name)
250 }
251 r, ok := repos[name]
252 if !ok {
253 return nil, fmt.Errorf("public project %s is not in the pending listing", name)
254 }
255 if r.Error != nil {
256 return nil, fmt.Errorf("the pending listing could not read public project %s", name)
257 }
258 out, err := project(name, p, r, details, exported, in)
259 if err != nil {
260 return nil, err
261 }
262 e.Projects = append(e.Projects, out)
263 }
264 if err := e.Validate(); err != nil {
265 return nil, err
266 }
267 return e, nil
268}
269
270func project(name string, p planProject, r pendingRepo, details map[detailKey]detailDoc,
271 exported map[string]bool, in Inputs) (Project, error) {
272 shown := in.Principals.Show
273 tip := in.SourceTips[name]
274 if !ValidObjectID(tip) {
275 return Project{}, fmt.Errorf("public project %s has no source tip, or one that is not an object ID", name)
276 }
277 out := Project{
278 Name: name, Visibility: Public, GraphTip: p.Tip, SourceTip: tip,
279 Roots: nonNil(p.Roots), Knots: []Knot{}, OpenResiduals: []Residuals{}, Changes: []Change{},
280 }
281 for _, g := range p.OpenResiduals {
282 out.OpenResiduals = append(out.OpenResiduals, Residuals{Parent: g.Parent, Bugs: nonNil(g.Bugs)})
283 }
284
285 // A reference to another project's knot is hidden when that project
286 // is not exported. Each list of the view a hidden reference appears in
287 // says something of the knot's status, so it is dropped from them all.
288 // A knot that waits on a hidden knot says only that it does.
289 hidden := func(ref string) bool {
290 project, _, qualified := strings.Cut(ref, ":")
291 return qualified && !exported[project]
292 }
293 var inProgress []string
294 inFlight := map[string]bool{}
295 for _, id := range p.InFlight {
296 inFlight[id] = true
297 }
298 for _, k := range p.Knots {
299 d, ok := details[detailKey{name, k.ID}]
300 if !ok {
301 return Project{}, fmt.Errorf("knot %s:%s has no detail", name, k.ID)
302 }
303 if d.Tip != p.Tip {
304 return Project{}, fmt.Errorf("%w: the plan read %s at %s, and knot %s at %s", ErrInconsistent, name, p.Tip, k.ID, d.Tip)
305 }
306 if d.Knot.Body == nil {
307 return Project{}, fmt.Errorf("the detail of knot %s:%s holds no body", name, k.ID)
308 }
309 if len(d.Knot.Comments) != k.CommentCount {
310 return Project{}, fmt.Errorf("%w: the plan counts %d comments on %s:%s, and its detail holds %d", ErrInconsistent, k.CommentCount, name, k.ID, len(d.Knot.Comments))
311 }
312 x := Knot{
313 ID: k.ID, Type: k.Type, Status: k.Status, Active: k.Active, Title: k.Title,
314 Created: k.Created, CreatedBy: shown(k.CreatedBy), Source: k.Source, Parent: k.Parent,
315 Owner: shown(k.Owner), BlockedBy: nonNil(k.BlockedBy), Changes: nonNil(k.Changes),
316 Target: k.Target, GraduatedInto: k.GraduatedInto,
317 State: k.State, Ready: k.Ready,
318 WaitingOn: drop(k.WaitingOn, hidden), WaitingOnHidden: slices.ContainsFunc(k.WaitingOn, hidden),
319 ClearedByEnding: drop(k.ClearedByEnding, hidden), Dangling: drop(k.Dangling, hidden),
320 Unresolved: drop(k.Unresolved, hidden), Children: nonNil(k.Children), Blocks: nonNil(k.Blocks),
321 Progress: k.Progress, Edges: []Edge{}, Body: *d.Knot.Body, Comments: []Comment{},
322 CommentCount: k.CommentCount,
323 }
324 if k.Claim != nil {
325 c := *k.Claim
326 c.By = shown(c.By)
327 x.Claim = &c
328 }
329 for _, edge := range k.Edges {
330 if !exported[edge.Project] {
331 edge = Edge{Field: edge.Field, Ref: edge.Ref, Project: edge.Project, ID: edge.ID, State: EdgeHidden}
332 }
333 x.Edges = append(x.Edges, edge)
334 }
335 for _, c := range d.Knot.Comments {
336 c.Author, c.EditedBy = shown(c.Author), shown(c.EditedBy)
337 x.Comments = append(x.Comments, c)
338 }
339 if k.Active && k.Status == "in-progress" && !inFlight[k.ID] {
340 inProgress = append(inProgress, k.ID)
341 }
342 out.Knots = append(out.Knots, x)
343 }
344 out.InFlight = append(nonNil(p.InFlight), inProgress...)
345
346 // includes may name a draft, which the export does not carry.
347 listed := map[string]bool{}
348 for _, c := range r.Changes {
349 listed[c.ChangeID] = true
350 }
351 for _, c := range r.Changes {
352 if c.State != "ready" {
353 return Project{}, fmt.Errorf("the pending listing holds change %s of %s, which is %s, among the ready changes", c.ChangeID, name, c.State)
354 }
355 var active *pendingVersion
356 for i := range c.Versions {
357 if c.Versions[i].N == c.Active {
358 active = &c.Versions[i]
359 }
360 }
361 if active == nil {
362 return Project{}, fmt.Errorf("change %s of %s holds no version %d, its active one", c.ChangeID, name, c.Active)
363 }
364 v := Version{N: active.N, Head: active.Head, Title: active.Title, Uploader: shown(active.Uploader),
365 Landing: active.Landing, Outcome: active.Outcome}
366 if active.Request != nil {
367 v.Request = &Request{Commit: active.Request.Commit}
368 }
369 out.Changes = append(out.Changes, Change{
370 ChangeID: c.ChangeID, Handle: c.Handle, Target: c.Target, Owner: shown(c.Owner), Version: v,
371 Includes: drop(c.Includes, func(id string) bool { return !listed[id] }), Knots: nonNilRefs(c.Knots),
372 })
373 }
374 return out, nil
375}
376
377// decodeInput reads one of the valley's documents and checks its schema.
378func decodeInput(what string, raw []byte, schema string, into any, got *string) error {
379 if err := json.Unmarshal(raw, into); err != nil {
380 return fmt.Errorf("%s: %w", what, err)
381 }
382 if *got != schema {
383 return fmt.Errorf("%s has schema %q, not %q", what, *got, schema)
384 }
385 return nil
386}
387
388// drop is list without the entries hidden reports, never nil.
389func drop(list []string, hidden func(string) bool) []string {
390 kept := []string{}
391 for _, s := range list {
392 if !hidden(s) {
393 kept = append(kept, s)
394 }
395 }
396 return kept
397}
398
399func nonNil(list []string) []string {
400 if list == nil {
401 return []string{}
402 }
403 return list
404}
405
406func nonNilRefs(list []KnotRef) []KnotRef {
407 if list == nil {
408 return []KnotRef{}
409 }
410 return list
411}