gunk-dev/the-valley

project.go

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