gunk-dev/the-valley

plan.go

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