gunk-dev/the-valley

queue.go

source4cbb5ec9c5dbmain's published tip history
21.4 KiB
1package cmd
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "io"
10 "os"
11 "sort"
12 "strings"
13 "time"
14
15 "github.com/spf13/cobra"
16 "the-valley/flow/internal/checksfix"
17 "the-valley/flow/internal/event"
18 "the-valley/flow/internal/integration"
19 "the-valley/flow/internal/restack"
20 "the-valley/flow/internal/run"
21)
22
23var queueCmd = &cobra.Command{
24 Use: "queue",
25 Short: "List what waits on the coordinator, oldest first",
26 Long: `Lists what waits on the coordinator, oldest first, each with how long it
27has waited and the one command that moves it on; then, as a group of its
28own, what waits on the operator. Prints nothing and exits 0 when nothing
29waits.
30
31It waits on the coordinator when nothing else will move it:
32needs-attention, awaiting-review (a draft to review, then valley flow
33ready), stale, rejected, failed, draft (no run working on it), and
34checks-failed or conflicting once flow's dispatch for it stopped short,
35its run finished without a new head, or the change isn't flow's. It waits
36on the operator when only approval or integration moves it:
37awaiting-approval, awaiting-integration, uncertain, and a PR ready to
38merge that nobody approved; that group carries no commands. Work in
39progress and done work are left out. A change is listed once, under its
40newest run.
41
42AGE runs from the event that put the item in its state (agent:change-draft
43for awaiting-review, agent:change-ready for awaiting-approval, and so on),
44and reads - when no event marks it. valley flow watch --queue waits until
45the queue differs from the one it last printed.`,
46 Example: ` valley flow queue
47 valley flow queue --json`,
48 Args: cobra.NoArgs,
49 RunE: func(cmd *cobra.Command, args []string) error {
50 asJSON, _ := cmd.Flags().GetBool("json")
51 store, err := sessionStore()
52 if err != nil {
53 return err
54 }
55 q, _, err := computeQueue(cmd.Context(), store)
56 if err != nil {
57 return err
58 }
59 if asJSON {
60 return q.writeJSON(cmd.OutOrStdout(), time.Now())
61 }
62 q.write(cmd.OutOrStdout(), time.Now())
63 return nil
64 },
65}
66
67func init() {
68 queueCmd.Flags().Bool("json", false, "Print the queue as one JSON object: {\"coordinator\": [...], \"operator\": [...]}")
69 rootCmd.AddCommand(queueCmd)
70}
71
72// party is whose move a state is.
73type party int
74
75const (
76 partyNone party = iota // done: nothing is left to do
77 partyFlow // in progress: an agent, the pipeline, the integrator or flow's dispatchers move it
78 partyCoordinator // only the coordinator moves it
79 partyOperator // only the operator's approval or integration moves it
80)
81
82// stateRule says, for a state valley flow status shows, whose move it is and
83// which events put a run or change in it.
84type stateRule struct {
85 party party
86 entered []string
87}
88
89// stateRules says whose move each state is, and which events date it. A
90// state missing from it is done. queueState refines it for failed checks,
91// restack conflicts and PRs ready to merge.
92var stateRules = map[string]stateRule{
93 "running": {party: partyFlow},
94 "working": {party: partyFlow},
95 "tracking": {party: partyFlow},
96 "active": {party: partyFlow},
97 "pr-created": {party: partyFlow, entered: []string{event.AgentPRCreated}},
98 "approved": {party: partyFlow, entered: []string{event.ChangeApproved}},
99 "needs-attention": {party: partyCoordinator, entered: []string{event.AgentNeedsAttention, event.AgentSharedGitChanged}},
100 "awaiting-review": {party: partyCoordinator, entered: []string{event.AgentChangeDraft}},
101 "checks-failed": {party: partyCoordinator, entered: []string{event.ChangeChecksFailed, event.ChangeChecksStalled, event.ChangeStale}},
102 "conflicting": {party: partyCoordinator, entered: []string{event.ChangeRestackStalled, event.ChangeStale}},
103 "stale": {party: partyCoordinator, entered: []string{event.ChangeStale}},
104 "rejected": {party: partyCoordinator, entered: []string{event.ChangeRejected}},
105 "failed": {party: partyCoordinator, entered: []string{event.ChangeFailed}},
106 "draft": {party: partyCoordinator, entered: []string{event.AgentCompleted, event.AgentNeedsAttention}},
107 "awaiting-approval": {party: partyOperator, entered: []string{event.AgentChangeReady, event.ChangeNewVersion}},
108 "awaiting-integration": {party: partyOperator, entered: []string{event.AgentBranchPushed}},
109 "uncertain": {party: partyOperator},
110 "ready-to-merge": {party: partyOperator, entered: []string{event.PRAwaitingApproval}},
111}
112
113// stateClock dates states by the session's events: when each event type
114// was last emitted for each run, change and PR, and about which head.
115type stateClock struct {
116 latest map[string]map[string]stamp // subject → event type → latest
117}
118
119// stamp is when an event was emitted, and the head it names, if any.
120type stamp struct {
121 at time.Time
122 head string
123}
124
125func newStateClock() *stateClock {
126 return &stateClock{latest: make(map[string]map[string]stamp)}
127}
128
129// loadStateClock reads the events of the session in dir; a log it can't
130// read dates nothing.
131func loadStateClock(dir string) *stateClock {
132 c := newStateClock()
133 events, err := event.NewLog(dir).Read()
134 if err != nil {
135 fmt.Fprintf(os.Stderr, "warning: reading events to date states: %v\n", err)
136 }
137 for _, e := range events {
138 c.observe(e)
139 }
140 return c
141}
142
143// loadClock is the state clock of store's session; empty for a store with
144// no session directory.
145func loadClock(store run.StateStore) *stateClock {
146 if hds, ok := store.(*run.HomeDirStore); ok {
147 return loadStateClock(hds.BaseDir())
148 }
149 return newStateClock()
150}
151
152// Subjects an event is about: its run (a run's ID, a PR's number or a
153// change's handle or ID), its change (by change ID), and its PR (by the
154// repo-qualified key every PR event carries, owner/repo#number).
155func runSubject(id string) string { return "run:" + id }
156func changeSubject(id string) string { return "change:" + id }
157func prSubject(key string) string { return "pr:" + key }
158
159// observe records evt.
160func (c *stateClock) observe(evt event.Event) {
161 t, err := time.Parse(time.RFC3339, evt.Timestamp)
162 if err != nil {
163 return
164 }
165 subjects := []string{runSubject(evt.RunID)}
166 if id, _ := evt.Data["change_id"].(string); id != "" {
167 subjects = append(subjects, changeSubject(id))
168 }
169 if key, _ := evt.Data["key"].(string); strings.Contains(key, "#") {
170 subjects = append(subjects, prSubject(key))
171 }
172 head, _ := evt.Data["head"].(string)
173 for _, s := range subjects {
174 m := c.latest[s]
175 if m == nil {
176 m = make(map[string]stamp)
177 c.latest[s] = m
178 }
179 if t.After(m[evt.Type].at) {
180 m[evt.Type] = stamp{t, head}
181 }
182 }
183}
184
185// since is when run s, or its change, entered state at head: the latest
186// event that enters it, about the run itself for needs-attention, its PR
187// for ready-to-merge, and the run or its change otherwise, and not about
188// another head; zero, unknown, when none is.
189func (c *stateClock) since(s *run.State, state, head string) time.Time {
190 rule, ok := stateRules[state]
191 if c == nil || !ok {
192 return time.Time{}
193 }
194 subjects := []string{runSubject(s.ID)}
195 switch {
196 case state == "ready-to-merge":
197 subjects = nil
198 if key := runPRKey(s); key != "" {
199 subjects = []string{prSubject(key)}
200 }
201 case state != "needs-attention" && s.ChangeID != "":
202 subjects = append(subjects, changeSubject(s.ChangeID))
203 }
204 var out time.Time
205 for _, sub := range subjects {
206 for _, t := range rule.entered {
207 st := c.latest[sub][t]
208 if st.head != "" && head != "" && st.head != head {
209 continue
210 }
211 if st.at.After(out) {
212 out = st.at
213 }
214 }
215 }
216 return out
217}
218
219// rowHead is the head row r stands at: its version's, else its push's.
220func rowHead(r runRow) string {
221 switch {
222 case r.change != nil:
223 return r.change.Head
224 case r.run.PushedSHA != nil:
225 return *r.run.PushedSHA
226 }
227 return r.run.HeadSHA
228}
229
230// runCreated is when run s was launched; zero when its record doesn't say.
231func runCreated(s *run.State) time.Time {
232 t, _ := time.Parse(time.RFC3339, s.CreatedAt)
233 return t
234}
235
236// runPRKey names run s's PR qualified by its repo, owner/repo#number, as PR
237// events name it; "" for a run without one.
238func runPRKey(s *run.State) string {
239 if pr := runPRNumber(s); pr != "" {
240 if key := changeKey(runRepoKey(s), pr, s.ChangeID); strings.Contains(key, "#") {
241 return key
242 }
243 }
244 return ""
245}
246
247// dispatchFinished reports whether the run flow dispatched as runID, for a
248// failed or conflicting head, has finished without leaving a new one: its
249// record reads it not running, and it pushed nothing or head again; or
250// cleanup removed its record, as cleared says. A dispatch that still reads
251// dispatched is for the change's current head, so a removed run left none
252// newer. A run with no record that cleanup didn't remove is still
253// launching: the failed-check dispatcher records a dispatch before it
254// launches the run.
255func dispatchFinished(runID, head string, states []*run.State, statuses []string, cleared map[string]bool) bool {
256 if runID == "" {
257 return false
258 }
259 for i, s := range states {
260 if s.ID == runID {
261 return statuses[i] != "running" && (s.PushedSHA == nil || *s.PushedSHA == head)
262 }
263 }
264 return cleared[runID]
265}
266
267// queueItem is one thing that waits on the coordinator or the operator.
268type queueItem struct {
269 party party
270 key string // what the item is: a run, a change or a PR
271 Run string // the run the item names, whose ID the next command takes
272 Change string // the change as valley flow status names it: handle, PR number or change ID prefix
273 ChangeID string
274 Project string
275 Head string
276 State string
277 Checks string // the operator's items: the checks' or CI's result, when there is one
278 Since time.Time // zero when no event dates the state
279 Next string // the one command that moves it on; none for the operator's
280 Note string // the failed checks, where a restack conflict stands, or the checks' result
281}
282
283// queue is what waits, each group oldest first.
284type queue struct {
285 coordinator, operator []queueItem
286}
287
288// computeQueue reads where the session's runs stand, as valley flow status
289// does, and returns what waits on the coordinator and on the operator.
290// provisional is set when a run record didn't parse, as one caught while
291// it is rewritten doesn't, so the queue may lack that run.
292func computeQueue(ctx context.Context, store run.StateStore) (q queue, provisional bool, err error) {
293 var states []*run.State
294 if hds, ok := store.(*run.HomeDirStore); ok {
295 var unparsed []string
296 states, unparsed, err = hds.Scan()
297 provisional = len(unparsed) > 0
298 } else {
299 states, err = store.List()
300 }
301 if err != nil {
302 return queue{}, false, err
303 }
304 clock := loadClock(store)
305 rows, report, err := runRows(ctx, store, states, clock, io.Discard)
306 if err != nil {
307 return queue{}, false, err
308 }
309 return buildQueue(rows, report, clock), provisional, nil
310}
311
312// queueState is the one rule for whose move a row is, and the state it
313// stands in for that. A ready change whose checks failed, or whose restack
314// conflict stands, is flow's while its dispatcher works on it: a dispatch
315// is due, or the run it dispatched is alive or left a new head. It is the
316// coordinator's once the dispatcher stops short, its run finished without
317// a new head, or the change isn't flow's; it waits on the operator's
318// approval only with neither. A PR ready to merge that nobody approved
319// waits on the operator.
320func queueState(r runRow) (string, party) {
321 state := r.status
322 switch {
323 case state == "awaiting-approval" && r.ci == "failing":
324 state = "checks-failed"
325 case (state == "awaiting-approval" || state == "draft") && r.restack != nil:
326 // A restack conflict stands, or flow's dispatch returned the
327 // change to draft to resolve it.
328 state = "conflicting"
329 case (state == "pr-created" || state == "tracking" && r.run.PRURL != nil) && r.merge == "ready" && !r.approved && !r.draftPR:
330 state = "ready-to-merge"
331 }
332 switch {
333 case state == "checks-failed" && r.checks != nil && checksAtWork(r):
334 return state, partyFlow
335 case state == "conflicting" && r.restack != nil && restackAtWork(r):
336 return state, partyFlow
337 }
338 return state, stateRules[state].party
339}
340
341// checksAtWork reports whether flow's failed-check dispatch works on row
342// r's change: a fix run is due, a run is on it, or the fix run it
343// dispatched hasn't finished without a new head.
344func checksAtWork(r runRow) bool {
345 switch r.checks.State {
346 case checksfix.StateDue, checksfix.StateBusy:
347 return true
348 case checksfix.StateDispatched:
349 return !r.checksDone
350 }
351 return false
352}
353
354// restackAtWork reports whether flow's restack dispatch works on row r's
355// conflict: anything short of stopping, refusing or leaving it alone,
356// unless the resolution run it dispatched finished without a new head.
357func restackAtWork(r runRow) bool {
358 switch r.restack.State {
359 case restack.StateStopped, restack.StateRefused, restack.StateHeld:
360 return false
361 case restack.StateDispatched:
362 return !r.restackDone
363 }
364 return true
365}
366
367// speaksForChange reports whether row r stands for its change as the
368// valley lists it now: its status is its version's, the active one, or a
369// run is at work on the change. A run that exited without pushing, or
370// whose attention is its own, speaks for no version.
371func speaksForChange(r runRow) bool {
372 return r.change != nil || r.status == "running" || r.status == "working"
373}
374
375// buildQueue returns what waits among rows. A run's own attention is its
376// item; everything else is its change's, listed once under its newest run.
377// A valley change with runs that read older-version, as when the restacker
378// made its active version, and none that speaks for it (speaksForChange)
379// stands where the valley's listing says.
380func buildQueue(rows []runRow, report integration.Report, clock *stateClock) queue {
381 states := make([]*run.State, len(rows))
382 for i, r := range rows {
383 states[i] = r.run
384 }
385 changeOf := changeKeys(states)
386 type slot struct {
387 row runRow
388 state string
389 party party
390 }
391 seen := make(map[string]slot)
392 var order []string
393 older := make(map[integration.ChangeKey][]runRow) // changes with runs that read older-version
394 current := make(map[integration.ChangeKey]bool) // changes some run speaks for
395 for _, r := range rows {
396 k, inChange := changeOf(r.run)
397 if inChange && r.status == "older-version" {
398 older[k] = append(older[k], r)
399 continue
400 }
401 if inChange && speaksForChange(r) {
402 current[k] = true
403 }
404 state, p := queueState(r)
405 if p != partyCoordinator && p != partyOperator {
406 continue
407 }
408 id := "run:" + r.run.ID
409 switch key := runPRKey(r.run); {
410 case key != "" && state == "ready-to-merge":
411 // A PR's state is one item, whichever of its runs, an agent's
412 // or a track record, speaks for it.
413 id = "pr:" + key
414 case inChange && state != "needs-attention":
415 // A run's attention is its own; any other state, its change's.
416 id = fmt.Sprintf("change:%s/%s", k.Repo, k.ChangeID)
417 }
418 if prev, ok := seen[id]; ok && !createdBefore(prev.row.run, r.run) {
419 continue
420 } else if !ok {
421 order = append(order, id)
422 }
423 seen[id] = slot{r, state, p}
424 }
425 olderKeys := make([]integration.ChangeKey, 0, len(older))
426 for k := range older {
427 olderKeys = append(olderKeys, k)
428 }
429 sort.Slice(olderKeys, func(i, j int) bool {
430 return olderKeys[i].Repo+"/"+olderKeys[i].ChangeID < olderKeys[j].Repo+"/"+olderKeys[j].ChangeID
431 })
432 for _, k := range olderKeys {
433 rs := older[k]
434 if current[k] {
435 continue
436 }
437 newest := rs[0]
438 for _, r := range rs[1:] {
439 if createdBefore(newest.run, r.run) {
440 newest = r
441 }
442 }
443 view := report.Changes[valleyKey(newest.run)]
444 if view.Change == nil {
445 continue
446 }
447 r := newest
448 r.status, r.change, r.ci = pushedStatus(view.Verdict, true), view.Change, "-"
449 if c := checksCI(view.Change.Checks); c != "" {
450 r.ci = c
451 }
452 state, p := queueState(r)
453 if p != partyCoordinator && p != partyOperator {
454 continue
455 }
456 r.since = clock.since(r.run, state, rowHead(r))
457 id := fmt.Sprintf("change:%s/%s", k.Repo, k.ChangeID)
458 order = append(order, id)
459 seen[id] = slot{r, state, p}
460 }
461
462 var q queue
463 for _, id := range order {
464 sl := seen[id]
465 it := newQueueItem(sl.row, sl.state, sl.party)
466 it.key = id
467 if sl.party == partyCoordinator {
468 q.coordinator = append(q.coordinator, it)
469 } else {
470 q.operator = append(q.operator, it)
471 }
472 }
473 // Oldest first; an item no event dates goes last, as the newest.
474 for _, items := range [][]queueItem{q.coordinator, q.operator} {
475 sort.SliceStable(items, func(i, j int) bool {
476 a, b := items[i].Since, items[j].Since
477 return !a.IsZero() && (b.IsZero() || a.Before(b))
478 })
479 }
480 return q
481}
482
483// newQueueItem is row r's item in state, dated as the row is.
484func newQueueItem(r runRow, state string, p party) queueItem {
485 s := r.run
486 it := queueItem{party: p, Run: s.ID, ChangeID: s.ChangeID, State: state, Since: r.since, Head: rowHead(r)}
487 if r.label != "-" {
488 it.Change = r.label
489 }
490 if r.change != nil {
491 it.Project = r.change.Repo
492 if r.change.Handle != "" {
493 it.Change = r.change.Handle
494 }
495 }
496 if it.Project == "" && s.TargetRepo != nil {
497 it.Project = *s.TargetRepo
498 }
499 switch {
500 case state == "checks-failed" && r.change != nil && r.change.Checks != nil:
501 it.Note = strings.Join(r.change.Checks.FailedNames(), ", ")
502 case state == "conflicting" && r.restack != nil:
503 it.Note = r.restack.Summary()
504 case p == partyOperator && r.ci != "" && r.ci != "-":
505 it.Checks = r.ci
506 it.Note = "checks " + r.ci
507 }
508 if p == partyCoordinator {
509 it.Next = nextCommand(s, state, it.Head)
510 }
511 return it
512}
513
514// nextCommand is the one command that moves run s, in state, on.
515func nextCommand(s *run.State, state, head string) string {
516 repo := ""
517 if s.TargetRepo != nil && *s.TargetRepo != "" {
518 repo = " --repo " + shellWord(*s.TargetRepo)
519 }
520 switch state {
521 case "needs-attention":
522 if s.SharedGitChanged() {
523 return "valley flow status"
524 }
525 return "valley flow launch" + repo + " --resume-from " + s.ID + ` "<brief>"`
526 case "awaiting-review":
527 return "valley flow ready " + s.ID + " --head " + head
528 }
529 return "valley flow launch" + repo + " --change " + s.ID + ` "<brief>"`
530}
531
532// glyph marks an item: ✗ for a failure, ◇ for anything else that waits.
533func (it queueItem) glyph() string {
534 switch it.State {
535 case "checks-failed", "rejected", "failed":
536 return "✗"
537 }
538 return "◇"
539}
540
541// line is the item's verdict line: what it is, its state, how long it has
542// waited, its head and any note.
543func (it queueItem) line(now time.Time) string {
544 name := it.Change
545 if name == "" {
546 name = it.Run
547 }
548 if it.Project != "" {
549 name = shortRepoName(it.Project) + " " + name
550 }
551 parts := []string{it.glyph() + " " + name, it.State, "for " + formatAge(it.Since, now)}
552 if it.Head != "" {
553 parts = append(parts, "head "+shortSHA(it.Head))
554 }
555 line := strings.Join(parts, " · ")
556 // The note gets what is left of 80 columns.
557 if room := 80 - len([]rune(line)) - len(" · "); it.Note != "" && room > 1 {
558 line += " · " + truncateLine(it.Note, room)
559 }
560 return line
561}
562
563// digest is a stable hash of what waits: each item's group, identity,
564// state and head, and for the operator's its checks. Ages, notes and order
565// are left out: they change without anything entering or leaving a state.
566func (q queue) digest() string {
567 var lines []string
568 for _, it := range q.coordinator {
569 lines = append(lines, strings.Join([]string{"coordinator", it.key, it.State, it.Head}, "\x00"))
570 }
571 for _, it := range q.operator {
572 lines = append(lines, strings.Join([]string{"operator", it.key, it.State, it.Head, it.Checks}, "\x00"))
573 }
574 sort.Strings(lines)
575 sum := sha256.Sum256([]byte(strings.Join(lines, "\n")))
576 return hex.EncodeToString(sum[:8])
577}
578
579// write prints the queue: the coordinator's items, each with the command
580// that moves it on, then the operator's; nothing when nothing waits.
581func (q queue) write(w io.Writer, now time.Time) {
582 groups := []struct {
583 title string
584 items []queueItem
585 }{{"Waiting on the coordinator", q.coordinator}, {"Waiting on the operator", q.operator}}
586 first := true
587 for _, g := range groups {
588 if len(g.items) == 0 {
589 continue
590 }
591 if !first {
592 fmt.Fprintln(w)
593 }
594 first = false
595 fmt.Fprintln(w, g.title)
596 for _, it := range g.items {
597 fmt.Fprintln(w, it.line(now))
598 if it.Next != "" {
599 verb := "run"
600 if it.Next == "valley flow status" {
601 verb = "see"
602 }
603 fmt.Fprintf(w, " %s: %s\n", verb, it.Next)
604 }
605 }
606 }
607}
608
609// jsonValue is the queue as valley flow queue --json prints it, with each
610// item's age in seconds: null, as its since is, when no event dates it.
611func (q queue) jsonValue(now time.Time) map[string][]map[string]interface{} {
612 conv := func(items []queueItem) []map[string]interface{} {
613 out := make([]map[string]interface{}, 0, len(items))
614 for _, it := range items {
615 m := map[string]interface{}{"run": it.Run, "state": it.State, "since": nil, "age_seconds": nil}
616 if !it.Since.IsZero() {
617 m["since"] = it.Since.UTC().Format(time.RFC3339)
618 m["age_seconds"] = int64(max(now.Sub(it.Since), 0).Seconds())
619 }
620 for k, v := range map[string]string{"change": it.Change, "change_id": it.ChangeID, "project": it.Project,
621 "head": it.Head, "checks": it.Checks, "next": it.Next, "note": it.Note} {
622 if v != "" {
623 m[k] = v
624 }
625 }
626 out = append(out, m)
627 }
628 return out
629 }
630 return map[string][]map[string]interface{}{"coordinator": conv(q.coordinator), "operator": conv(q.operator)}
631}
632
633// writeJSON prints the queue as one JSON object, its groups empty lists
634// when nothing waits.
635func (q queue) writeJSON(w io.Writer, now time.Time) error {
636 data, err := json.Marshal(q.jsonValue(now))
637 if err != nil {
638 return err
639 }
640 _, err = fmt.Fprintln(w, string(data))
641 return err
642}