gunk-dev/the-valley

naming.go

source6a7605f70901main's published tip history
17.5 KiB
1package cmd
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 "sort"
12 "strings"
13
14 "github.com/spf13/cobra"
15
16 "the-valley/flow/internal/config"
17 "the-valley/flow/internal/git"
18 "the-valley/flow/internal/location"
19 "the-valley/flow/internal/project"
20 "the-valley/flow/internal/run"
21 "the-valley/flow/internal/selfupdate"
22 "the-valley/flow/internal/tmux"
23)
24
25var namingCmd = &cobra.Command{
26 Use: "naming",
27 Short: "Which names flow gives new state, and where its state is",
28}
29
30var namingStatusCmd = &cobra.Command{
31 Use: "status",
32 Short: "Report the naming generation, where state is, and what blocks advancing",
33 Long: `Reports the host's naming_generation and what this build gives new state
34under it: legacy names under legacy, and bridge names under bridge and flow,
35since this build does not build the flow generation's writers. Bridge names
36put new sessions, the sync log, consult snapshots, scaffolded declarations,
37and single-valued state that is in neither place under the flow names
38(~/.valley/flow), and keep the legacy names (~/.klaus) for the rest.
39
40It also reports where each kind of state is, under either names, and any
41kind found in both; the live sessions, with the build and generation that
42created each (legacy when a session records none); for each registered
43project, whether its worktrees' commit hooks are the current ones;
44self-update's current and previous builds; and what blocks each generation
45past the one set, each with its reason. It changes nothing.
46
47It sees only this machine's flow state: other machines, and timers or
48helpers that run outside flow, are for the operator to check. A running
49dashboard keeps the environment it started with, so it takes a changed
50setting at its next restart.`,
51 Args: cobra.NoArgs,
52 RunE: func(cmd *cobra.Command, args []string) error {
53 cmd.SilenceUsage = true
54 l, err := location.Host()
55 if err != nil {
56 return err
57 }
58 // The host config's generation: Load refuses one that is none.
59 cfg, err := config.Load("")
60 if err != nil {
61 return err
62 }
63 l.Gen = cfg.Generation()
64 r := buildNamingReport(cmd.Context(), namingInputs{
65 layout: l,
66 tmux: run.TmuxDepsFor(cmd.Context(), tmux.NewExecClient()),
67 })
68 if asJSON, _ := cmd.Flags().GetBool("json"); asJSON {
69 enc := json.NewEncoder(cmd.OutOrStdout())
70 enc.SetIndent("", " ")
71 return enc.Encode(r)
72 }
73 printNamingReport(cmd.OutOrStdout(), r, l.Home)
74 return nil
75 },
76}
77
78// namingSupportCmd is how a build says which generations it supports: the
79// operator asks a rollback target with it, since naming status runs no
80// program the self-update state names.
81var namingSupportCmd = &cobra.Command{
82 Use: "_naming-support",
83 Short: "Print the naming generations this build operates and allocates, as JSON",
84 Hidden: true,
85 Args: cobra.NoArgs,
86 RunE: func(cmd *cobra.Command, args []string) error {
87 return json.NewEncoder(cmd.OutOrStdout()).Encode(thisBuildSupport())
88 },
89}
90
91func init() {
92 namingStatusCmd.Flags().Bool("json", false, "Print the report as JSON")
93 namingCmd.AddCommand(namingStatusCmd)
94 rootCmd.AddCommand(namingCmd)
95 rootCmd.AddCommand(namingSupportCmd)
96}
97
98// namingSupport is which generations a build operates (finds, reads and
99// writes state of) and, for each it can be set to, which generation's
100// names it gives new state.
101type namingSupport struct {
102 Operates []location.Generation `json:"operates"`
103 Allocates map[location.Generation]location.Generation `json:"allocates"`
104}
105
106func thisBuildSupport() namingSupport {
107 s := namingSupport{Operates: location.Operates(), Allocates: map[location.Generation]location.Generation{}}
108 for _, g := range location.Generations {
109 s.Allocates[g] = location.Allocates(g)
110 }
111 return s
112}
113
114type namingInputs struct {
115 layout location.Layout
116 tmux run.TmuxDeps
117}
118
119type namingReport struct {
120 Generation location.Generation `json:"generation"`
121 Allocates location.Generation `json:"allocates"` // the names this build gives new state under Generation
122 Operates []location.Generation `json:"operates"`
123 Places []namingPlace `json:"places"`
124 Sessions []namingSession `json:"live_sessions"`
125 Projects []namingProject `json:"projects"`
126 SelfUpdate namingSelfUpdate `json:"self_update"`
127 Next location.Generation `json:"next,omitempty"`
128 Blockers []namingBlocker `json:"blockers"`
129 Unseen string `json:"unseen"`
130}
131
132// namingPlace is where one kind of state is.
133type namingPlace struct {
134 Kind string `json:"kind"`
135 Paths []string `json:"paths,omitempty"` // where it is, or where it goes
136 Exists bool `json:"exists"`
137 Error string `json:"error,omitempty"`
138}
139
140type namingSession struct {
141 ID string `json:"id"`
142 Dir string `json:"dir"`
143 CreatedBy string `json:"created_by,omitempty"` // empty: a build that recorded none
144 Generation string `json:"generation"`
145 Error string `json:"error,omitempty"` // its runs could not be read, so it may be live
146}
147
148type namingProject struct {
149 Name string `json:"name"`
150 Path string `json:"path"`
151 Declarations []string `json:"declarations,omitempty"`
152 Hooks []git.WorktreeHooks `json:"hooks"`
153 Error string `json:"error,omitempty"`
154}
155
156type namingSelfUpdate struct {
157 State string `json:"state,omitempty"`
158 Current *selfupdate.Install `json:"current,omitempty"`
159 Previous *selfupdate.Install `json:"previous,omitempty"`
160 Error string `json:"error,omitempty"`
161}
162
163type namingBlocker struct {
164 What string `json:"what"`
165 Reason string `json:"reason"`
166 Blocks location.Generation `json:"blocks"` // the first generation it keeps the host from
167}
168
169// namingUnseen is what the report can't see, among it the environment of a
170// running dashboard, which a process sets up as it starts
171// (flowenv.NormalizeProcess).
172const namingUnseen = "Not seen from here: other machines, and timers or helpers outside flow.\n" +
173 "A running dashboard keeps the environment it started with until it restarts."
174
175func buildNamingReport(ctx context.Context, in namingInputs) namingReport {
176 l := in.layout
177 gen, _ := l.Generation()
178 r := namingReport{
179 Generation: gen,
180 Allocates: location.Allocates(gen),
181 Operates: location.Operates(),
182 Next: gen.Next(),
183 Sessions: []namingSession{},
184 Projects: []namingProject{},
185 Blockers: []namingBlocker{},
186 Unseen: namingUnseen,
187 }
188
189 place := func(kind string, resolve func() (string, error)) {
190 p := namingPlace{Kind: kind}
191 path, err := resolve()
192 var conflict *location.ConflictError
193 switch {
194 case errors.As(err, &conflict):
195 p.Paths, p.Exists, p.Error = conflict.Paths, true, err.Error()
196 case err != nil:
197 p.Error = err.Error()
198 default:
199 _, statErr := os.Lstat(path)
200 p.Paths, p.Exists = []string{path}, statErr == nil
201 }
202 r.Places = append(r.Places, p)
203 }
204 place("host config", l.HostConfig)
205 place("project registry", l.Registry)
206 place("shared memory", l.Memory)
207 place("self-update state", l.SelfUpdateState)
208
209 sessions, sessErr := l.Sessions()
210 sp := namingPlace{Kind: "sessions"}
211 for _, root := range l.SessionRoots() {
212 if _, err := os.Stat(root); err == nil {
213 sp.Paths, sp.Exists = append(sp.Paths, root), true
214 }
215 }
216 if sessErr != nil {
217 sp.Error = sessErr.Error()
218 }
219 if len(sp.Paths) == 0 {
220 if root, err := l.NewSessionsRoot(); err == nil {
221 sp.Paths = []string{root}
222 }
223 }
224 r.Places = append(r.Places, sp)
225
226 // State of the new rule is listed wherever it exists, else where it goes.
227 newRule := func(kind string, existing []string, resolve func() (string, error)) {
228 if len(existing) > 0 {
229 r.Places = append(r.Places, namingPlace{Kind: kind, Paths: existing, Exists: true})
230 } else {
231 place(kind, resolve)
232 }
233 }
234 newRule("sync log", l.SyncLogs(), l.SyncLog)
235 newRule("consult snapshots", l.ConsultSnapshotDirs(), l.ConsultSnapshots)
236 locks := namingPlace{Kind: "global review locks", Paths: l.ReviewLockDirs()}
237 for _, d := range locks.Paths {
238 if _, err := os.Stat(d); err == nil {
239 locks.Exists = true
240 }
241 }
242 r.Places = append(r.Places, locks)
243
244 for _, s := range sessions {
245 live, err := sessionLive(s.Dir, in.tmux)
246 if err != nil {
247 // A session whose runs can't be read may be live: say so.
248 r.Sessions = append(r.Sessions, namingSession{ID: s.ID, Dir: s.Dir, Generation: string(location.Legacy), Error: err.Error()})
249 continue
250 }
251 if !live {
252 continue
253 }
254 ns := namingSession{ID: s.ID, Dir: s.Dir, Generation: string(location.Legacy)}
255 if st, err := run.NewHomeDirStoreFromPath(s.Dir).Load(s.ID); err == nil {
256 ns.CreatedBy = st.CreatedBy
257 if st.NamingGeneration != "" {
258 ns.Generation = st.NamingGeneration
259 }
260 }
261 r.Sessions = append(r.Sessions, ns)
262 }
263
264 if regPath, err := l.Registry(); err == nil {
265 reg, err := project.LoadFrom(regPath)
266 if err != nil {
267 for i := range r.Places {
268 if r.Places[i].Kind == "project registry" {
269 r.Places[i].Error = err.Error()
270 }
271 }
272 } else {
273 names := make([]string, 0, len(reg.Projects))
274 paths := reg.List() // ~ expanded
275 for name := range paths {
276 names = append(names, name)
277 }
278 sort.Strings(names)
279 for _, name := range names {
280 r.Projects = append(r.Projects, namingProjectOf(ctx, name, paths[name]))
281 }
282 }
283 }
284
285 r.SelfUpdate = namingSelfUpdateOf(l)
286 r.Blockers = namingBlockers(r)
287 return r
288}
289
290// namingTarget is the generation a report's state checks are for: the next
291// one, or the one set when this build doesn't build it; "" when neither.
292func namingTarget(r namingReport) location.Generation {
293 if r.Next != "" {
294 return r.Next
295 }
296 if r.Allocates != r.Generation {
297 return r.Generation
298 }
299 return ""
300}
301
302// unbuilt is the first generation from g on whose names this build doesn't
303// give new state, or "".
304func unbuilt(g location.Generation) location.Generation {
305 for x := g; x != ""; x = x.Next() {
306 if location.Allocates(x) != x {
307 return x
308 }
309 }
310 return ""
311}
312
313// sessionLive reports whether a session's coordinator, or any of its runs'
314// agents, is still running in tmux.
315func sessionLive(dir string, td run.TmuxDeps) (bool, error) {
316 states, unparsed, unreadable, err := run.NewHomeDirStoreFromPath(dir).Audit()
317 if err != nil {
318 return false, err
319 }
320 if len(unparsed) > 0 {
321 return false, fmt.Errorf("run records %s don't parse", strings.Join(unparsed, ", "))
322 }
323 if len(unreadable) > 0 {
324 msgs := make([]string, len(unreadable))
325 for i, e := range unreadable {
326 msgs[i] = e.Error()
327 }
328 return false, fmt.Errorf("run records can't be read: %s", strings.Join(msgs, "; "))
329 }
330 for _, s := range states {
331 if s.Type == "session" {
332 for _, p := range []*string{s.CoordinatorPane, s.DashboardPane} {
333 if p != nil && td.PaneExists(*p) && !td.PaneIsIdle(*p) {
334 return true, nil
335 }
336 }
337 continue
338 }
339 if s.IsAgentRunningWith(td) {
340 return true, nil
341 }
342 }
343 return false, nil
344}
345
346func namingProjectOf(ctx context.Context, name, path string) namingProject {
347 p := namingProject{Name: name, Path: path, Hooks: []git.WorktreeHooks{}}
348 for _, file := range location.ProjectFiles {
349 if f, err := location.ProjectFile(path, file); err == nil {
350 if _, err := os.Lstat(f); err == nil {
351 p.Declarations = append(p.Declarations, f)
352 }
353 }
354 }
355 hooks, err := git.InstalledHooks(ctx, path)
356 if err != nil {
357 p.Error = err.Error()
358 return p
359 }
360 p.Hooks = hooks
361 return p
362}
363
364func namingSelfUpdateOf(l location.Layout) namingSelfUpdate {
365 var su namingSelfUpdate
366 path, err := l.SelfUpdateState()
367 if err != nil {
368 su.Error = err.Error()
369 return su
370 }
371 su.State = path
372 st, err := selfupdate.LoadFile(path)
373 if err != nil {
374 su.Error = err.Error()
375 return su
376 }
377 su.Current, su.Previous = st.Current, st.Previous
378 return su
379}
380
381// namingBlockers is what keeps the host from each generation past what it
382// has, each with its reason and the first generation it blocks: this
383// build's own limit blocks the first generation it doesn't build, and the
384// state found here blocks namingTarget.
385func namingBlockers(r namingReport) []namingBlocker {
386 b := []namingBlocker{}
387 if g := unbuilt(r.Generation); g != "" {
388 b = append(b, namingBlocker{
389 What: "this build",
390 Reason: fmt.Sprintf("the %s generation's writers are not built", g),
391 Blocks: g,
392 })
393 }
394 next := namingTarget(r)
395 if next == "" {
396 return b
397 }
398 add := func(what, reason string) {
399 b = append(b, namingBlocker{What: what, Reason: reason, Blocks: next})
400 }
401 for _, p := range r.Places {
402 if p.Error != "" {
403 add(p.Kind, p.Error)
404 }
405 }
406 for _, s := range r.Sessions {
407 if s.Error != "" {
408 add("session "+s.ID, "its runs could not be read, so it may be live: "+s.Error)
409 continue
410 }
411 if s.CreatedBy == "" {
412 add("session "+s.ID, "it was created by a build that records no naming generation; let it finish")
413 }
414 }
415 for _, p := range r.Projects {
416 var stale int
417 for _, h := range p.Hooks {
418 if !h.Current {
419 stale++
420 }
421 }
422 if p.Error != "" {
423 add("project "+p.Name, "its commit hooks could not be read: "+p.Error)
424 } else if stale > 0 {
425 add("project "+p.Name, fmt.Sprintf("%d of its %d worktrees with flow's hooks have older ones; a run or session resume there installs the current ones", stale, len(p.Hooks)))
426 }
427 }
428 if su := r.SelfUpdate; su.Error != "" && !placeFailed(r, "self-update state") {
429 add("self-update state", "the rollback target could not be read from it: "+su.Error)
430 }
431 // The report runs no program the state file names, so what the
432 // rollback target supports is for the operator to ask it.
433 if prev := r.SelfUpdate.Previous; prev != nil {
434 add("self-update's previous build "+installLabel(prev),
435 fmt.Sprintf("it is the rollback target, and must operate %s state: %s _naming-support lists what it operates",
436 next, filepath.Join(prev.StorePath, "bin", "klaus")))
437 }
438 return b
439}
440
441// placeFailed reports whether r's place of kind already carries an error,
442// which is a blocker of its own.
443func placeFailed(r namingReport, kind string) bool {
444 for _, p := range r.Places {
445 if p.Kind == kind && p.Error != "" {
446 return true
447 }
448 }
449 return false
450}
451
452func installLabel(i *selfupdate.Install) string {
453 if i.Commit != "" {
454 return shortSHA(i.Commit)
455 }
456 return i.StorePath
457}
458
459// tildePath is p as the operator writes it: ~ for home when p is in it.
460func tildePath(home, p string) string {
461 if home != "" && (p == home || strings.HasPrefix(p, home+string(filepath.Separator))) {
462 return "~" + p[len(home):]
463 }
464 return p
465}
466
467func printNamingReport(w io.Writer, r namingReport, home string) {
468 tilde := func(p string) string { return tildePath(home, p) }
469 tildes := func(ps []string) string {
470 out := make([]string, len(ps))
471 for i, p := range ps {
472 out[i] = tilde(p)
473 }
474 return strings.Join(out, ", ")
475 }
476
477 head := fmt.Sprintf("naming generation %s · new state gets %s names", r.Generation, r.Allocates)
478 target := namingTarget(r)
479 blocking := map[location.Generation][]namingBlocker{}
480 for _, b := range r.Blockers {
481 blocking[b.Blocks] = append(blocking[b.Blocks], b)
482 }
483 switch n := len(blocking[target]); {
484 case target == "":
485 fmt.Fprintf(w, "✓ %s\n", head)
486 case n == 0:
487 fmt.Fprintf(w, "✓ %s · nothing here blocks %s\n", head, target)
488 default:
489 fmt.Fprintf(w, "◇ %s · %d %s %s\n", head, n, plural(n, "blocks", "block"), target)
490 }
491
492 fmt.Fprintln(w, "\nWhere state is")
493 for _, p := range r.Places {
494 line := tildes(p.Paths)
495 if !p.Exists {
496 line += " (none yet)"
497 }
498 if p.Error != "" && len(p.Paths) == 0 {
499 line = p.Error
500 }
501 fmt.Fprintf(w, " %-20s %s\n", p.Kind, line)
502 if p.Error != "" && len(p.Paths) > 0 {
503 fmt.Fprintf(w, " %-20s ✗ %s\n", "", p.Error)
504 }
505 }
506
507 fmt.Fprintln(w, "\nLive sessions")
508 if len(r.Sessions) == 0 {
509 fmt.Fprintln(w, " none")
510 }
511 for _, s := range r.Sessions {
512 by := "a build that recorded none"
513 if s.CreatedBy != "" {
514 by = s.CreatedBy
515 }
516 if s.Error != "" {
517 fmt.Fprintf(w, " %s · ✗ %s\n", s.ID, s.Error)
518 continue
519 }
520 fmt.Fprintf(w, " %s · created by %s · %s names\n", s.ID, by, s.Generation)
521 }
522
523 fmt.Fprintln(w, "\nCommit hooks")
524 if len(r.Projects) == 0 {
525 fmt.Fprintln(w, " no registered projects")
526 }
527 for _, p := range r.Projects {
528 var stale int
529 for _, h := range p.Hooks {
530 if !h.Current {
531 stale++
532 }
533 }
534 switch {
535 case p.Error != "":
536 fmt.Fprintf(w, " %s · ✗ %s\n", p.Name, p.Error)
537 case len(p.Hooks) == 0:
538 fmt.Fprintf(w, " %s · no worktrees with flow's hooks\n", p.Name)
539 case stale == 0:
540 fmt.Fprintf(w, " %s · ✓ %d %s current\n", p.Name, len(p.Hooks), plural(len(p.Hooks), "worktree", "worktrees"))
541 default:
542 fmt.Fprintf(w, " %s · ◇ %d of %d worktrees older\n", p.Name, stale, len(p.Hooks))
543 }
544 }
545
546 fmt.Fprintln(w, "\nSelf-update")
547 switch su := r.SelfUpdate; {
548 case su.Error != "":
549 fmt.Fprintf(w, " ✗ %s\n", su.Error)
550 case su.Current == nil && su.Previous == nil:
551 fmt.Fprintln(w, " nothing installed by self-update")
552 default:
553 for _, row := range []struct {
554 label string
555 i *selfupdate.Install
556 }{{"current", su.Current}, {"previous", su.Previous}} {
557 if row.i != nil {
558 fmt.Fprintf(w, " %-9s %s %s\n", row.label, installLabel(row.i), tilde(row.i.StorePath))
559 }
560 }
561 }
562
563 // A section for each generation from the one set on that something
564 // blocks, and for the target even when nothing does.
565 for g := r.Generation; g != ""; g = g.Next() {
566 if bs := blocking[g]; len(bs) > 0 || g == target {
567 if g == r.Generation {
568 fmt.Fprintf(w, "\nBlocks %s\n", g)
569 } else {
570 fmt.Fprintf(w, "\nBlocks advancing to %s\n", g)
571 }
572 if len(bs) == 0 {
573 fmt.Fprintln(w, " nothing found here")
574 }
575 for _, b := range bs {
576 fmt.Fprintf(w, " ◇ %s: %s\n", b.What, b.Reason)
577 }
578 }
579 }
580 fmt.Fprintf(w, "\n%s\n", r.Unseen)
581}
582
583func plural(n int, one, many string) string {
584 if n == 1 {
585 return one
586 }
587 return many
588}