gunk-dev/the-valley

plan.go

source30fe2c053de0main's published tip history
16.7 KiB
1package server
2
3import (
4 "context"
5 "net/http"
6 "net/url"
7 "sort"
8 "strconv"
9 "strings"
10
11 "the-valley/knot"
12 "the-valley/web/export"
13)
14
15// index is one reader's view of an export: the projects the authorization
16// lets the reader read and their knots, by name, where each of those
17// projects' pages are, and the plan page's structure. It is built once for
18// each generation, authorization and reader, from what visible returns
19// alone, so no page built from it names a project the reader may not read.
20type index struct {
21 // building is set only while the worker constructs the index.
22 building context.Context
23 projects map[string]*export.Project
24 knots map[string]map[string]*export.Knot
25 // public are the visible projects' names, in the export's order: those
26 // that have a web URL, which a project in no group does not.
27 public []string
28 // bases are each public project's URL, /<group name>/<web name>,
29 // escaped, by the project's identifier. groups are the public
30 // projects by group name and then by web name. formers are where the
31 // URLs under a public project's former names redirect to, its base,
32 // by group name and then by former name. aliases are where each
33 // alias's URLs redirect to: a group's alias to /<group name>, and a
34 // project's short alias to its base.
35 bases map[string]string
36 groups map[string]map[string]*export.Project
37 formers map[string]map[string]string
38 aliases map[string]string
39 // plan is the plan page, but for what is in flight, whose ages are
40 // read at each request. Requests share it and do not change it.
41 plan *planPage
42}
43
44// indexCancelled unwinds the nested graph walks when their worker stops.
45type indexCancelled struct{ err error }
46
47func (idx *index) checkBuild() {
48 if idx.building != nil {
49 if err := idx.building.Err(); err != nil {
50 panic(indexCancelled{err})
51 }
52 }
53}
54
55// visible is the one project-view filter: the projects of e that the
56// authorization lets reader read, by name, each named with the identity e
57// gives it. A nil authorization lets no one read anything. Every view a
58// server builds, of the plan, the navigation, the groups, the references
59// between projects and the redirects, is built through it.
60func visible(e *export.Export, a *export.Authorization, reader string) map[string]bool {
61 shown := map[string]bool{}
62 for _, p := range e.Projects {
63 if a.Allows(reader, p.Name, p.Identity) {
64 shown[p.Name] = true
65 }
66 }
67 return shown
68}
69
70// newIndex is the index of e's projects that shown names.
71func newIndex(ctx context.Context, e *export.Export, shown map[string]bool) (result *index, err error) {
72 defer func() {
73 if p := recover(); p != nil {
74 if stopped, ok := p.(indexCancelled); ok {
75 result, err = nil, stopped.err
76 } else {
77 panic(p)
78 }
79 }
80 }()
81 idx := &index{building: ctx, projects: map[string]*export.Project{}, knots: map[string]map[string]*export.Knot{},
82 bases: map[string]string{}, groups: map[string]map[string]*export.Project{},
83 formers: map[string]map[string]string{}, aliases: map[string]string{}}
84 idx.checkBuild()
85 defer func() { idx.building = nil }()
86 idx.place(e, shown)
87 for i := range e.Projects {
88 idx.checkBuild()
89 p := &e.Projects[i]
90 if !shown[p.Name] {
91 continue
92 }
93 idx.projects[p.Name] = p
94 byID := map[string]*export.Knot{}
95 for j := range p.Knots {
96 idx.checkBuild()
97 byID[p.Knots[j].ID] = &p.Knots[j]
98 }
99 idx.knots[p.Name] = byID
100 }
101 idx.plan = idx.planPage()
102 idx.checkBuild()
103 return idx, nil
104}
105
106// place indexes where each project shown names has its pages, and where
107// each alias and former name redirects to. A project in no group has no
108// pages, and a group with no project shown has no alias. It checks for
109// cancellation before each group, project and name, so the work between
110// two checks is bounded by a name's length.
111func (idx *index) place(e *export.Export, shown map[string]bool) {
112 groups := map[string]export.Group{}
113 for _, g := range e.Groups {
114 idx.checkBuild()
115 groups[g.ID] = g
116 }
117 used := map[string]bool{}
118 for i := range e.Projects {
119 idx.checkBuild()
120 p := &e.Projects[i]
121 g, grouped := groups[p.Group]
122 if !shown[p.Name] || !grouped {
123 continue
124 }
125 used[g.ID] = true
126 idx.public = append(idx.public, p.Name)
127 base := "/" + url.PathEscape(g.Name) + "/" + url.PathEscape(p.WebName)
128 idx.bases[p.Name] = base
129 if idx.groups[g.Name] == nil {
130 idx.groups[g.Name] = map[string]*export.Project{}
131 idx.formers[g.Name] = map[string]string{}
132 }
133 idx.groups[g.Name][p.WebName] = p
134 for _, former := range p.FormerNames {
135 idx.checkBuild()
136 idx.formers[g.Name][former] = base
137 }
138 for _, alias := range p.Aliases {
139 idx.checkBuild()
140 idx.aliases[alias] = base
141 }
142 }
143 for _, g := range e.Groups {
144 idx.checkBuild()
145 if !used[g.ID] {
146 continue
147 }
148 for _, alias := range g.Aliases {
149 idx.checkBuild()
150 idx.aliases[alias] = "/" + url.PathEscape(g.Name)
151 }
152 }
153}
154
155// knotURL is a knot's page, under its project's base.
156func knotURL(base, id string) string {
157 return base + "/knots/" + url.PathEscape(id)
158}
159
160// knotLink is a knot as a page links to it.
161type knotLink struct {
162 Project string
163 ID string
164 Title string
165 State string
166 URL string
167}
168
169func (idx *index) linkOf(project string, k *export.Knot) knotLink {
170 return knotLink{Project: project, ID: k.ID, Title: k.Title, State: k.State, URL: knotURL(idx.bases[project], k.ID)}
171}
172
173// The plan page, in its reading order: what waits on the reader, what is
174// in flight, the paths, and the milestones.
175type planPage struct {
176 Projects string
177 Tally []tally
178 InFlight []flight
179 Changes []readyChange
180 Paths []path
181 Milestones []milestone
182}
183
184// tally is how many knots are in one state.
185type tally struct {
186 N int
187 Label string
188}
189
190// flight is a knot in flight, with who claims it and since when.
191type flight struct {
192 Knot knotLink
193 Note string
194}
195
196// readyChange is a change ready for approval.
197type readyChange struct {
198 Handle string
199 Title string
200 Version string
201 Note string
202 Knots []knotLink
203}
204
205// path is one parent's children in the order their blocked_by edges set:
206// each stage holds the children whose blockers among their siblings are
207// all in earlier stages.
208type path struct {
209 Parent knotLink
210 Stages [][]knotLink
211}
212
213// milestone is an outcome with no parent and the tree of knots under it,
214// or a project's knots that have no parent and are no milestone.
215type milestone struct {
216 Knot *knotLink
217 Title string
218 Project string
219 Count string
220 Cord []string
221 Tree []node
222}
223
224// node is one knot of a milestone's tree, with the knots under it.
225type node struct {
226 Row row
227 Children []node
228 Open bool
229}
230
231// row is how a knot reads in a tree: its glyph, ID and title, and chips
232// saying what more there is to know.
233type row struct {
234 knotLink
235 Filter string
236 Chips []chip
237}
238
239type chip struct {
240 Class string
241 Text string
242}
243
244// stateRank orders a tree's children: work in progress first, finished
245// work last.
246var stateRank = map[string]int{"in-progress": 0, "ready": 1, "blocked": 2, "active": 3, "done": 4, "abandoned": 5}
247
248func rank(state string) int {
249 if r, ok := stateRank[state]; ok {
250 return r
251 }
252 return len(stateRank)
253}
254
255// plan serves the plan page: the generation's structure, and what is in
256// flight as of the request.
257func (q *request) plan() {
258 p := *q.idx.plan
259 for _, name := range q.idx.public {
260 p.InFlight = append(p.InFlight, q.inFlight(q.idx.projects[name])...)
261 }
262 q.page(http.StatusOK, "plan", "Plan", p)
263}
264
265// planPage is the plan page's structure, without what is in flight.
266func (idx *index) planPage() *planPage {
267 var p planPage
268 p.Projects = strings.Join(idx.public, " · ")
269 counts := map[string]int{}
270 for _, name := range idx.public {
271 idx.checkBuild()
272 proj := idx.projects[name]
273 roots := idx.buildSet(proj.Roots)
274 for i := range proj.Knots {
275 idx.checkBuild()
276 k := &proj.Knots[i]
277 if (k.Type == "outcome" || k.Type == "bug") && !roots[k.ID] {
278 counts[k.State]++
279 }
280 }
281 p.Changes = append(p.Changes, idx.readyChanges(proj)...)
282 p.Paths = append(p.Paths, idx.paths(proj)...)
283 p.Milestones = append(p.Milestones, idx.milestones(proj)...)
284 }
285 for _, s := range []string{"done", "in-progress", "ready", "blocked"} {
286 idx.checkBuild()
287 p.Tally = append(p.Tally, tally{counts[s], stateLabel(s)})
288 }
289 return &p
290}
291
292// inFlight is the project's knots in flight, in the export's order: the
293// claimed ones, oldest claim first, then those in progress that nobody
294// claims. A claim's age is read from when it was made.
295func (q *request) inFlight(p *export.Project) []flight {
296 var out []flight
297 for _, id := range p.InFlight {
298 k, ok := q.idx.knots[p.Name][id]
299 if !ok {
300 continue
301 }
302 f := flight{Knot: q.idx.linkOf(p.Name, k), Note: "in progress, unclaimed"}
303 if c := k.Claim; c != nil {
304 f.Note = "claimed by " + c.By
305 if at, err := parseTime(c.At); err == nil {
306 age := q.now.Sub(at)
307 f.Note += " " + ago(age)
308 if age > knot.StaleClaim {
309 f.Note += "; the claim is stale"
310 }
311 }
312 }
313 out = append(out, f)
314 }
315 return out
316}
317
318// readyChanges are the project's changes ready for approval, each with
319// its active version, whether an integration request approves it, and the
320// integrator's last decision.
321func (idx *index) readyChanges(p *export.Project) []readyChange {
322 var out []readyChange
323 for _, c := range p.Changes {
324 idx.checkBuild()
325 v := c.Version
326 notes := []string{"not approved"}
327 if v.Request != nil {
328 notes = []string{"approved"}
329 }
330 if v.Outcome != nil {
331 notes = append(notes, "integrator: "+v.Outcome.Decision)
332 }
333 if v.Landing == "uncertain" {
334 notes = append(notes, "landing uncertain")
335 }
336 rc := readyChange{Handle: c.Handle, Title: v.Title, Version: p.Name + " v" + strconv.Itoa(v.N),
337 Note: strings.Join(notes, " · ")}
338 for _, ref := range c.Knots {
339 idx.checkBuild()
340 if k, ok := idx.knots[p.Name][ref.ID]; ok {
341 rc.Knots = append(rc.Knots, idx.linkOf(p.Name, k))
342 }
343 }
344 out = append(out, rc)
345 }
346 return out
347}
348
349// paths are the project's parents whose children wait on one another,
350// each with its children in stages. A child's stage is one past the
351// latest stage of the siblings in its blocked_by, done or not, so
352// children with no order between them share a stage and can run in
353// parallel. Abandoned children are left out.
354func (idx *index) paths(p *export.Project) []path {
355 knots := idx.knots[p.Name]
356 var out []path
357 for i := range p.Knots {
358 idx.checkBuild()
359 parent := &p.Knots[i]
360 var kids []*export.Knot
361 siblings := map[string]bool{}
362 for _, id := range parent.Children {
363 idx.checkBuild()
364 if k, ok := knots[id]; ok && k.State != "abandoned" && !siblings[id] {
365 kids = append(kids, k)
366 siblings[id] = true
367 }
368 }
369 // waits counts each child's sibling blockers not yet placed, and
370 // next lists the siblings each child blocks.
371 waits, next := map[string]int{}, map[string][]string{}
372 for _, k := range kids {
373 idx.checkBuild()
374 for _, b := range k.BlockedBy {
375 idx.checkBuild()
376 if siblings[b] {
377 waits[k.ID]++
378 next[b] = append(next[b], k.ID)
379 }
380 }
381 }
382 if len(next) == 0 {
383 continue
384 }
385 // A child is placed once its sibling blockers all are, each child
386 // and each edge once.
387 stage, placed := map[string]int{}, map[string]bool{}
388 var ready []string
389 for _, k := range kids {
390 idx.checkBuild()
391 if waits[k.ID] == 0 {
392 ready, placed[k.ID] = append(ready, k.ID), true
393 }
394 }
395 for len(ready) > 0 {
396 idx.checkBuild()
397 id := ready[0]
398 ready = ready[1:]
399 for _, c := range next[id] {
400 idx.checkBuild()
401 stage[c] = max(stage[c], stage[id]+1)
402 if waits[c]--; waits[c] == 0 {
403 ready, placed[c] = append(ready, c), true
404 }
405 }
406 }
407 // The graph holds blocked_by acyclic. A cycle it did not would
408 // leave its knots, and those waiting on them, unplaced, and they
409 // share a last stage.
410 last := 0
411 for id := range placed {
412 idx.checkBuild()
413 last = max(last, stage[id]+1)
414 }
415 pa := path{Parent: idx.linkOf(p.Name, parent)}
416 for _, k := range kids {
417 idx.checkBuild()
418 s := stage[k.ID]
419 if !placed[k.ID] {
420 s = last
421 }
422 for len(pa.Stages) <= s {
423 idx.checkBuild()
424 pa.Stages = append(pa.Stages, nil)
425 }
426 pa.Stages[s] = append(pa.Stages[s], idx.linkOf(p.Name, k))
427 }
428 out = append(out, pa)
429 }
430 return out
431}
432
433// milestones are the project's roots, each with its tree, and then its
434// knots that have no parent and are no root, as one more box. A knot is
435// shown once in the project's trees, and counted once, however the
436// graph's children lists name it.
437func (idx *index) milestones(p *export.Project) []milestone {
438 knots := idx.knots[p.Name]
439 var out []milestone
440 counted, shown := map[string]bool{}, map[string]bool{}
441 for _, id := range p.Roots {
442 idx.checkBuild()
443 k, ok := knots[id]
444 if !ok || shown[id] {
445 continue
446 }
447 counted[id], shown[id] = true, true
448 done, of := 0, 0
449 var cord []string
450 for _, d := range idx.descendants(p.Name, k, counted) {
451 idx.checkBuild()
452 if d.State == "abandoned" {
453 continue
454 }
455 of++
456 if d.State == "done" {
457 done++
458 }
459 cord = append(cord, d.State)
460 }
461 // The cord reads finished work first, then the rest by state.
462 sort.SliceStable(cord, func(i, j int) bool {
463 idx.checkBuild()
464 di, dj := cord[i] == "done", cord[j] == "done"
465 if di != dj {
466 return di
467 }
468 return rank(cord[i]) < rank(cord[j])
469 })
470 link := idx.linkOf(p.Name, k)
471 out = append(out, milestone{Knot: &link, Title: k.Title, Project: p.Name,
472 Count: strconv.Itoa(done) + " of " + strconv.Itoa(of) + " done", Cord: cord,
473 Tree: idx.tree(p.Name, k.Children, 1, shown)})
474 }
475 roots := idx.buildSet(p.Roots)
476 var loose []string
477 for _, k := range p.Knots {
478 idx.checkBuild()
479 if k.Parent == "" && !roots[k.ID] {
480 loose = append(loose, k.ID)
481 }
482 }
483 if len(loose) > 0 {
484 out = append(out, milestone{Title: "Unfiled", Project: p.Name, Count: count(len(loose), "knot"),
485 Tree: idx.tree(p.Name, loose, 1, shown)})
486 }
487 return out
488}
489
490// descendants is every knot under k that counted does not hold, each
491// added to counted as it is found. It walks the graph with a stack, so a
492// chain of any depth takes no recursion, and counted guards against a
493// parent cycle the graph would not hold.
494func (idx *index) descendants(project string, k *export.Knot, counted map[string]bool) []*export.Knot {
495 var out []*export.Knot
496 stack := []*export.Knot{k}
497 for len(stack) > 0 {
498 idx.checkBuild()
499 k := stack[len(stack)-1]
500 stack = stack[:len(stack)-1]
501 for _, id := range k.Children {
502 idx.checkBuild()
503 if c, ok := idx.knots[project][id]; ok && !counted[id] {
504 counted[id] = true
505 out = append(out, c)
506 stack = append(stack, c)
507 }
508 }
509 }
510 return out
511}
512
513// tree is the knots called ids and everything under them, each level
514// ordered by state, at depth depth of a milestone's tree. shown holds the
515// knots the project's trees show already, which are not shown again, so a
516// tree takes one step for each knot and each child it lists. A knot at
517// MaxPlanDepth is shown without the knots under it, and says they are on
518// its page.
519func (idx *index) tree(project string, ids []string, depth int, shown map[string]bool) []node {
520 var kids []*export.Knot
521 for _, id := range ids {
522 idx.checkBuild()
523 if k, ok := idx.knots[project][id]; ok && !shown[id] {
524 shown[id] = true
525 kids = append(kids, k)
526 }
527 }
528 sort.SliceStable(kids, func(i, j int) bool { idx.checkBuild(); return rank(kids[i].State) < rank(kids[j].State) })
529 var out []node
530 for _, k := range kids {
531 idx.checkBuild()
532 n := node{Row: idx.row(project, k), Open: k.State != "done" && k.State != "abandoned"}
533 if depth < MaxPlanDepth {
534 n.Children = idx.tree(project, k.Children, depth+1, shown)
535 } else if len(k.Children) > 0 {
536 n.Row.Chips = append(n.Row.Chips, chip{"quiet", "more on its page"})
537 }
538 out = append(out, n)
539 }
540 return out
541}
542
543// row is a knot's line in a tree. Filter is the state the page's filters
544// read: abandoned work is finished work, as done is.
545func (idx *index) row(project string, k *export.Knot) row {
546 r := row{knotLink: idx.linkOf(project, k), Filter: k.State}
547 if k.State == "abandoned" {
548 r.Filter = "done"
549 }
550 if k.Target != "" && k.Target != project {
551 text, _ := idx.named(project, k.Target)
552 r.Chips = append(r.Chips, chip{"quiet", "lands in " + text})
553 }
554 if k.Claim != nil {
555 r.Chips = append(r.Chips, chip{"", "claimed by " + k.Claim.By})
556 }
557 if k.State == "blocked" {
558 r.Chips = append(r.Chips, chip{"blocked", "waits on " + idx.waitsOn(k.WaitingOn, k.WaitingOnHidden)})
559 }
560 if k.Progress != nil && k.Progress.Of > 0 {
561 r.Chips = append(r.Chips, chip{"quiet", strconv.Itoa(k.Progress.Done) + "/" + strconv.Itoa(k.Progress.Of)})
562 }
563 if k.CommentCount > 0 {
564 r.Chips = append(r.Chips, chip{"quiet", count(k.CommentCount, "comment")})
565 }
566 return r
567}
568
569func set(list []string) map[string]bool {
570 m := map[string]bool{}
571 for _, s := range list {
572 m[s] = true
573 }
574 return m
575}
576
577func (idx *index) buildSet(list []string) map[string]bool {
578 m := map[string]bool{}
579 for _, s := range list {
580 idx.checkBuild()
581 m[s] = true
582 }
583 return m
584}