gunk-dev/the-valley

project.go

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