| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "net/url" |
| 7 | "os/exec" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | tea "github.com/charmbracelet/bubbletea" |
| 14 | "the-valley/flow/internal/integration" |
| 15 | "the-valley/flow/internal/run" |
| 16 | "the-valley/flow/internal/valley" |
| 17 | ) |
| 18 | |
| 19 | // valleyWakeMsg says a valley host reported a record that can move a |
| 20 | // change. It wakes the integration check; it is never state. |
| 21 | type valleyWakeMsg struct{} |
| 22 | |
| 23 | // valleyWakeCheckMsg starts the check a wake asked for, once the burst of |
| 24 | // records that woke it has had wakeSettle to arrive. |
| 25 | type valleyWakeCheckMsg struct{} |
| 26 | |
| 27 | // wakeSettle is how long a wake waits for the rest of its burst of records, |
| 28 | // so the burst costs one check. |
| 29 | const wakeSettle = 500 * time.Millisecond |
| 30 | |
| 31 | const ( |
| 32 | // followFloor is the least time between two follows of one host, so a |
| 33 | // host that ends each follow at once isn't asked in a busy loop. |
| 34 | followFloor = time.Second |
| 35 | // followTries is how many follows in a row may fail, a little apart, |
| 36 | // before the dashboard says so and asks only every followRetry. |
| 37 | followTries = 3 |
| 38 | // followRetry is how long a host whose follows keep failing waits |
| 39 | // between follows: the minute's check carries the dashboard until one |
| 40 | // succeeds. |
| 41 | followRetry = 10 * time.Minute |
| 42 | ) |
| 43 | |
| 44 | // valleyWaker follows the telemetry of each valley host the dashboard's |
| 45 | // valley changes live on, with one follow of every stream from one checkout |
| 46 | // per host, so a dashboard holds one of a principal's follow slots per |
| 47 | // host. It says on its wake channel when a record arrives that can move a |
| 48 | // change. Records that arrive before the dashboard reads the channel are |
| 49 | // one wake. |
| 50 | type valleyWaker struct { |
| 51 | wake chan struct{} |
| 52 | want chan []string // the checkouts to follow from; only the latest counts |
| 53 | mu sync.Mutex // makes Track's replace of want atomic |
| 54 | logger *slog.Logger |
| 55 | |
| 56 | quietMu sync.Mutex |
| 57 | quiet map[string]bool // hosts whose failing telemetry was logged |
| 58 | } |
| 59 | |
| 60 | // startValleyWaker starts a valleyWaker that runs until ctx ends, logging |
| 61 | // to logger. |
| 62 | func startValleyWaker(ctx context.Context, logger *slog.Logger) *valleyWaker { |
| 63 | w := &valleyWaker{ |
| 64 | wake: make(chan struct{}, 1), |
| 65 | want: make(chan []string, 1), |
| 66 | logger: logger, |
| 67 | quiet: make(map[string]bool), |
| 68 | } |
| 69 | go w.run(ctx) |
| 70 | return w |
| 71 | } |
| 72 | |
| 73 | // valleyCheckouts returns the clones of the runs whose valley change the |
| 74 | // integration check asks the valley about: a run awaiting its change's |
| 75 | // integration, or a tracked change. |
| 76 | func valleyCheckouts(states []*run.State) []string { |
| 77 | seen := make(map[string]bool) |
| 78 | var dirs []string |
| 79 | for _, s := range states { |
| 80 | if s.Valley == nil || !(awaitsIntegration(s) || integration.TracksChange(s)) { |
| 81 | continue |
| 82 | } |
| 83 | if s.CloneDir != nil && *s.CloneDir != "" && !seen[*s.CloneDir] { |
| 84 | seen[*s.CloneDir] = true |
| 85 | dirs = append(dirs, *s.CloneDir) |
| 86 | } |
| 87 | } |
| 88 | sort.Strings(dirs) |
| 89 | return dirs |
| 90 | } |
| 91 | |
| 92 | // Track sets the checkouts whose origins' hosts to follow; none stops every |
| 93 | // follow. It never blocks. |
| 94 | func (w *valleyWaker) Track(dirs []string) { |
| 95 | if w == nil { |
| 96 | return |
| 97 | } |
| 98 | w.mu.Lock() |
| 99 | defer w.mu.Unlock() |
| 100 | select { |
| 101 | case <-w.want: |
| 102 | default: |
| 103 | } |
| 104 | w.want <- dirs |
| 105 | } |
| 106 | |
| 107 | // waitCmd waits for the next wake. |
| 108 | func (w *valleyWaker) waitCmd() tea.Cmd { |
| 109 | if w == nil { |
| 110 | return nil |
| 111 | } |
| 112 | return func() tea.Msg { |
| 113 | <-w.wake |
| 114 | return valleyWakeMsg{} |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | func (w *valleyWaker) poke() { |
| 119 | select { |
| 120 | case w.wake <- struct{}{}: |
| 121 | default: |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // run follows each tracked host's telemetry, once per host, until ctx |
| 126 | // ends. A host is followed from one of its tracked checkouts; when that |
| 127 | // checkout is no longer tracked, its follow restarts from another. |
| 128 | func (w *valleyWaker) run(ctx context.Context) { |
| 129 | type following struct { |
| 130 | dir string |
| 131 | stop context.CancelFunc |
| 132 | } |
| 133 | followers := make(map[string]following) // by host |
| 134 | hostOf := make(map[string]string) // checkout -> its origin's host |
| 135 | for { |
| 136 | var dirs []string |
| 137 | select { |
| 138 | case <-ctx.Done(): |
| 139 | return |
| 140 | case dirs = <-w.want: |
| 141 | } |
| 142 | hosts := make(map[string]string) // host -> the checkout to follow it from |
| 143 | for _, dir := range dirs { |
| 144 | host, ok := hostOf[dir] |
| 145 | if !ok { |
| 146 | if host = originHost(ctx, dir); host == "" { |
| 147 | continue // not a checkout now; asked again next time |
| 148 | } |
| 149 | hostOf[dir] = host |
| 150 | } |
| 151 | if f, ok := followers[host]; ok && f.dir == dir { |
| 152 | hosts[host] = dir // keep following from where it does |
| 153 | } else if _, ok := hosts[host]; !ok { |
| 154 | hosts[host] = dir |
| 155 | } |
| 156 | } |
| 157 | for host, f := range followers { |
| 158 | if hosts[host] != f.dir { |
| 159 | f.stop() |
| 160 | delete(followers, host) |
| 161 | } |
| 162 | } |
| 163 | for host, dir := range hosts { |
| 164 | if _, ok := followers[host]; ok { |
| 165 | continue |
| 166 | } |
| 167 | fctx, stop := context.WithCancel(ctx) |
| 168 | followers[host] = following{dir: dir, stop: stop} |
| 169 | go w.follow(fctx, host, dir) |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // follow follows host's telemetry from dir, resuming each follow where the |
| 175 | // last ended, until ctx ends. A failing follow, a refusal because the |
| 176 | // principal's follow slots are taken among them, is retried a little later, |
| 177 | // and after followTries failures in a row, logged once and retried only |
| 178 | // every followRetry. |
| 179 | func (w *valleyWaker) follow(ctx context.Context, host, dir string) { |
| 180 | cursor, failures := "", 0 |
| 181 | for { |
| 182 | started := time.Now() |
| 183 | next, err := valley.Follow(ctx, dir, cursor, w.poke) |
| 184 | if ctx.Err() != nil { |
| 185 | return |
| 186 | } |
| 187 | pause := followFloor - time.Since(started) |
| 188 | if err == nil { |
| 189 | cursor, failures = next, 0 |
| 190 | } else { |
| 191 | failures++ |
| 192 | pause = time.Second << (failures - 1) |
| 193 | if failures >= followTries { |
| 194 | pause = followRetry |
| 195 | w.noteQuiet(host, err) |
| 196 | } |
| 197 | } |
| 198 | if pause > 0 { |
| 199 | select { |
| 200 | case <-ctx.Done(): |
| 201 | return |
| 202 | case <-time.After(pause): |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // noteQuiet logs, once per host, that its telemetry can't be followed, so |
| 209 | // its changes are checked each minute only. |
| 210 | func (w *valleyWaker) noteQuiet(host string, err error) { |
| 211 | w.quietMu.Lock() |
| 212 | defer w.quietMu.Unlock() |
| 213 | if w.quiet[host] { |
| 214 | return |
| 215 | } |
| 216 | w.quiet[host] = true |
| 217 | w.logger.Info("can't follow the valley host's telemetry; checking its changes each minute", |
| 218 | "host", host, "err", err) |
| 219 | } |
| 220 | |
| 221 | // originHost returns the host of the origin of the checkout in dir: the |
| 222 | // host of an URL or of an scp-like address, or a local path as it is. "" |
| 223 | // when dir has no origin. |
| 224 | func originHost(ctx context.Context, dir string) string { |
| 225 | ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 226 | defer cancel() |
| 227 | cmd := exec.CommandContext(ctx, "git", "remote", "get-url", "origin") |
| 228 | cmd.Dir = dir |
| 229 | cmd.Env = append(cmd.Environ(), "GIT_TERMINAL_PROMPT=0") |
| 230 | out, err := cmd.Output() |
| 231 | if err != nil { |
| 232 | return "" |
| 233 | } |
| 234 | return remoteHost(strings.TrimSpace(string(out))) |
| 235 | } |
| 236 | |
| 237 | // remoteHost is the host a git remote address names, without its user or |
| 238 | // port: "valley.example" for ssh://git@valley.example:22/repo or |
| 239 | // git@valley.example:repo. A local path has no host, and stands for itself. |
| 240 | func remoteHost(remote string) string { |
| 241 | if u, err := url.Parse(remote); err == nil && u.Host != "" { |
| 242 | return u.Hostname() |
| 243 | } |
| 244 | if at, rest, ok := strings.Cut(remote, ":"); ok && !strings.Contains(at, "/") { |
| 245 | if _, host, ok := strings.Cut(at, "@"); ok { |
| 246 | return host |
| 247 | } |
| 248 | if rest != "" { |
| 249 | return at |
| 250 | } |
| 251 | } |
| 252 | return remote |
| 253 | } |