gunk-dev/the-valley

plan.go

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