| 1 | package integration |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "os" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | "time" |
| 10 | |
| 11 | "the-valley/flow/internal/run" |
| 12 | "the-valley/flow/internal/valley" |
| 13 | ) |
| 14 | |
| 15 | // ValleyChecker asks a valley where pushed runs' changes stand, and defers to |
| 16 | // a GitChecker for the runs the valley doesn't place. |
| 17 | // |
| 18 | // A check runs `valley changes --all --json` once, for every repo the valley |
| 19 | // serves, and only when finalize found that some run's repo delivers to a |
| 20 | // valley (run.State.Valley), or a valley change is tracked (TracksChange). It places a run by repo, change ID and version |
| 21 | // head: the run's version is the one whose head is the run's pushed SHA, in |
| 22 | // the listed repo that is the run's own. A run whose repo klaus doesn't know |
| 23 | // is never placed, and neither is any run in a repo the valley couldn't read |
| 24 | // or whose change is in a state klaus doesn't know. |
| 25 | // If valley fails or prints a schema klaus doesn't know, every run is judged |
| 26 | // by git and the report says why (ValleyErr). The failure is logged at warn |
| 27 | // level once per streak of failures, and the recovery once. |
| 28 | // |
| 29 | // Git can't settle a change finalize marked ready: a deleted branch says |
| 30 | // nothing about a change the valley still holds as uncertain or rejected. For |
| 31 | // such a run, git's Gone is Unknown. |
| 32 | type ValleyChecker struct { |
| 33 | git *GitChecker |
| 34 | logger *slog.Logger |
| 35 | |
| 36 | mu sync.Mutex |
| 37 | failing bool // the previous check failed: log the next failure only after a success |
| 38 | } |
| 39 | |
| 40 | // NewValleyChecker returns a ValleyChecker that logs failed checks to logger |
| 41 | // (slog.Default when nil). |
| 42 | func NewValleyChecker(logger *slog.Logger) *ValleyChecker { |
| 43 | if logger == nil { |
| 44 | logger = slog.Default() |
| 45 | } |
| 46 | return &ValleyChecker{git: NewGitChecker(logger), logger: logger} |
| 47 | } |
| 48 | |
| 49 | // Check returns a result for every run that Applies, and the valley's view |
| 50 | // of every change it lists. |
| 51 | func (c *ValleyChecker) Check(ctx context.Context, runs []*run.State) Report { |
| 52 | dir, ok := valleyDir(runs) |
| 53 | if !ok { |
| 54 | return Report{Runs: c.judgeByGit(ctx, runs)} |
| 55 | } |
| 56 | start := time.Now() |
| 57 | changes, err := valley.List(ctx, dir) |
| 58 | c.note(dir, err, time.Since(start)) |
| 59 | if err != nil { |
| 60 | return Report{Runs: c.judgeByGit(ctx, runs), Asked: true, ValleyErr: oneLine(err)} |
| 61 | } |
| 62 | for _, vr := range changes.Repos { |
| 63 | if e := vr.Err(); e != "" { |
| 64 | c.logger.Debug("valley couldn't read a repo; judging its runs by git", "repo", vr.Repo, "err", e) |
| 65 | } |
| 66 | } |
| 67 | out := make(map[string]Result) |
| 68 | var rest []*run.State |
| 69 | for _, s := range runs { |
| 70 | if r, ok := place(changes, s); ok { |
| 71 | out[s.ID] = r |
| 72 | } else { |
| 73 | rest = append(rest, s) |
| 74 | } |
| 75 | } |
| 76 | for id, r := range c.judgeByGit(ctx, rest) { |
| 77 | out[id] = r |
| 78 | } |
| 79 | return Report{Runs: out, Changes: activeVersions(changes), Listing: changes, Asked: true} |
| 80 | } |
| 81 | |
| 82 | // note logs a check's outcome when it starts or ends a streak of failures. |
| 83 | func (c *ValleyChecker) note(dir string, err error, took time.Duration) { |
| 84 | c.mu.Lock() |
| 85 | was := c.failing |
| 86 | c.failing = err != nil |
| 87 | c.mu.Unlock() |
| 88 | switch { |
| 89 | case err != nil && !was: |
| 90 | c.logger.Warn("valley check failed; judging runs by git", "dir", dir, "err", err, "took", took.Round(time.Millisecond)) |
| 91 | case err == nil && was: |
| 92 | c.logger.Warn("valley check recovered", "dir", dir, "took", took.Round(time.Millisecond)) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // oneLine is err's message on one line, without the "valley changes: " |
| 97 | // prefix a valley.Error carries. |
| 98 | func oneLine(err error) string { |
| 99 | msg := err.Error() |
| 100 | if ve, ok := err.(*valley.Error); ok { |
| 101 | msg = ve.Reason |
| 102 | } |
| 103 | return strings.Join(strings.Fields(msg), " ") |
| 104 | } |
| 105 | |
| 106 | // judgeByGit asks the GitChecker about runs the valley didn't place. A run |
| 107 | // finalize marked ready on a valley is never Gone, only Unknown: its change |
| 108 | // may still need the operator, whatever became of its branch. |
| 109 | func (c *ValleyChecker) judgeByGit(ctx context.Context, runs []*run.State) map[string]Result { |
| 110 | out := c.git.judge(ctx, runs) |
| 111 | for _, s := range runs { |
| 112 | if r, ok := out[s.ID]; ok && r.Verdict == Gone && RecordedChange(s) != nil { |
| 113 | out[s.ID] = Result{Verdict: Unknown} |
| 114 | } |
| 115 | } |
| 116 | return out |
| 117 | } |
| 118 | |
| 119 | // valleyDir picks where to run valley: the clone of a run whose repo |
| 120 | // delivers to a valley, or of a tracked valley change (TracksChange), or the |
| 121 | // current directory when no such clone is there. ok is false when no run's |
| 122 | // repo delivers to a valley and no change is tracked. |
| 123 | func valleyDir(runs []*run.State) (dir string, ok bool) { |
| 124 | for _, s := range runs { |
| 125 | if !(Applies(s) || TracksChange(s)) || s.Valley == nil { |
| 126 | continue |
| 127 | } |
| 128 | ok = true |
| 129 | if s.CloneDir != nil && *s.CloneDir != "" { |
| 130 | if fi, err := os.Stat(*s.CloneDir); err == nil && fi.IsDir() { |
| 131 | return *s.CloneDir, true |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | return "", ok |
| 136 | } |
| 137 | |
| 138 | // place finds a run's version among the valley's changes: in the run's repo, |
| 139 | // a change with the run's change ID and a version whose head is the run's |
| 140 | // pushed SHA. When several match, the one that is its change's active version |
| 141 | // wins. ok is false when none does, when klaus doesn't know the run's repo, |
| 142 | // or when the valley couldn't read that repo: records listed beside a read |
| 143 | // error may be stale. A change in a state klaus doesn't know, from a later |
| 144 | // valley, places nothing. |
| 145 | func place(changes *valley.Changes, s *run.State) (Result, bool) { |
| 146 | repo := RepoName(s) |
| 147 | if !Applies(s) || s.ChangeID == "" || repo == "" { |
| 148 | return Result{}, false |
| 149 | } |
| 150 | var found Result |
| 151 | ok := false |
| 152 | for _, vr := range changes.Repos { |
| 153 | if vr.Repo != repo || vr.Err() != "" { |
| 154 | continue |
| 155 | } |
| 156 | for _, ch := range vr.Changes { |
| 157 | if ch.ChangeID != s.ChangeID || !knownState(ch.State) { |
| 158 | continue |
| 159 | } |
| 160 | v, match := versionAt(ch, *s.PushedSHA) |
| 161 | if !match { |
| 162 | continue |
| 163 | } |
| 164 | r := Result{Verdict: verdictOf(ch, v), Change: changeAt(vr.Repo, ch, v)} |
| 165 | if v.N == ch.Active { |
| 166 | return r, true |
| 167 | } |
| 168 | if !ok { |
| 169 | found, ok = r, true |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | return found, ok |
| 174 | } |
| 175 | |
| 176 | // activeVersions is the valley's view of every change it lists in a repo it |
| 177 | // could read and a state klaus knows: the change's active version, and what |
| 178 | // the valley's record of it says (ListedChanges). |
| 179 | func activeVersions(changes *valley.Changes) map[ChangeKey]Result { |
| 180 | out := make(map[ChangeKey]Result) |
| 181 | for k, ch := range ListedChanges(changes) { |
| 182 | v, _ := ActiveVersion(ch) |
| 183 | out[k] = Result{Verdict: verdictOf(ch, v), Change: changeAt(k.Repo, ch, v)} |
| 184 | } |
| 185 | return out |
| 186 | } |
| 187 | |
| 188 | // ListedChanges is the valley's record of every change it lists in a repo |
| 189 | // it could read and a state klaus knows, by change: the record that decides |
| 190 | // where the change stands, whatever became of any one run's version. A |
| 191 | // change whose active version isn't listed has none. Where a repo lists a |
| 192 | // change ID more than once (under several targets), a withdrawn record |
| 193 | // gives way to another. |
| 194 | func ListedChanges(changes *valley.Changes) map[ChangeKey]valley.Change { |
| 195 | out := make(map[ChangeKey]valley.Change) |
| 196 | if changes == nil { |
| 197 | return out |
| 198 | } |
| 199 | for _, vr := range changes.Repos { |
| 200 | if vr.Err() != "" { |
| 201 | continue |
| 202 | } |
| 203 | for _, ch := range vr.Changes { |
| 204 | if !knownState(ch.State) { |
| 205 | continue |
| 206 | } |
| 207 | k := ChangeKey{Repo: vr.Repo, ChangeID: ch.ChangeID} |
| 208 | if prev, ok := out[k]; ok { |
| 209 | if v, _ := ActiveVersion(prev); verdictOf(prev, v) != Withdrawn { |
| 210 | continue |
| 211 | } |
| 212 | } |
| 213 | if _, ok := ActiveVersion(ch); ok { |
| 214 | out[k] = ch |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | return out |
| 219 | } |
| 220 | |
| 221 | // ActiveVersion returns ch's active version; ok is false when it isn't |
| 222 | // listed. |
| 223 | func ActiveVersion(ch valley.Change) (valley.Version, bool) { |
| 224 | for _, v := range ch.Versions { |
| 225 | if v.N == ch.Active { |
| 226 | return v, true |
| 227 | } |
| 228 | } |
| 229 | return valley.Version{}, false |
| 230 | } |
| 231 | |
| 232 | // changeAt is how the valley knows version v of change ch in repo. |
| 233 | func changeAt(repo string, ch valley.Change, v valley.Version) *Change { |
| 234 | c := &Change{Repo: repo, ChangeID: ch.ChangeID, Handle: ch.Handle, Title: v.Title, |
| 235 | Version: v.N, Head: v.Head, Branch: v.Branch, Active: v.N == ch.Active, Checks: v.Checks} |
| 236 | if w, ok := LandedAs(ch, v); ok { |
| 237 | c.LandedAs, c.LandedCommit = w.N, w.Head |
| 238 | if w.LandedCommit != nil && *w.LandedCommit != "" { |
| 239 | c.LandedCommit = *w.LandedCommit |
| 240 | } |
| 241 | } |
| 242 | for _, k := range ch.Knots { |
| 243 | c.Knots = append(c.Knots, k.ID) |
| 244 | } |
| 245 | return c |
| 246 | } |
| 247 | |
| 248 | // knownState reports whether klaus knows what a change state means. |
| 249 | func knownState(state string) bool { |
| 250 | return state == valley.StateReady || state == valley.StateDraft || state == valley.StateWithdrawn |
| 251 | } |
| 252 | |
| 253 | // RepoName is the valley's name for a run's repo, as finalize's `valley |
| 254 | // ready` reported it; or else, for a run that continues another's change, the |
| 255 | // repo that run had (ChangeRepo), so a follow-up names its change as the run |
| 256 | // it continues does; or else as launch's `valley unready` reported it; or |
| 257 | // else the short name of the run's target repo: its last path component, |
| 258 | // without ".git". "" means unknown, and an unknown repo matches none. It is |
| 259 | // how klaus tells which runs share a change: the same repo and change ID. |
| 260 | func RepoName(s *run.State) string { |
| 261 | if s.Valley != nil && s.Valley.Repo != "" { |
| 262 | return s.Valley.Repo |
| 263 | } |
| 264 | if s.ChangeRepo != "" { |
| 265 | return s.ChangeRepo |
| 266 | } |
| 267 | if s.Unready != nil && s.Unready.Repo != "" { |
| 268 | return s.Unready.Repo |
| 269 | } |
| 270 | if s.TargetRepo == nil { |
| 271 | return "" |
| 272 | } |
| 273 | name := strings.TrimRight(*s.TargetRepo, "/") |
| 274 | if i := strings.LastIndexAny(name, "/:"); i >= 0 { |
| 275 | name = name[i+1:] |
| 276 | } |
| 277 | return strings.TrimSuffix(name, ".git") |
| 278 | } |
| 279 | |
| 280 | // versionAt returns the version of ch whose head is head: the active one if |
| 281 | // that head was marked ready more than once, else the latest. |
| 282 | func versionAt(ch valley.Change, head string) (valley.Version, bool) { |
| 283 | var found valley.Version |
| 284 | ok := false |
| 285 | for _, v := range ch.Versions { |
| 286 | if v.Head != head { |
| 287 | continue |
| 288 | } |
| 289 | if v.N == ch.Active { |
| 290 | return v, true |
| 291 | } |
| 292 | if !ok || v.N > found.N { |
| 293 | found, ok = v, true |
| 294 | } |
| 295 | } |
| 296 | return found, ok |
| 297 | } |
| 298 | |
| 299 | // verdictOf reads the valley's record of version v of change ch, whose state |
| 300 | // klaus knows. Landing evidence comes first: once the valley says the change |
| 301 | // landed (LandedAs), every version of it is Integrated, whichever is active |
| 302 | // and even if the change went back to draft. A draft change's active version is otherwise Draft, whatever the |
| 303 | // valley is unsure of or the integrator decided on its request: its submitter |
| 304 | // has it back, and there is nothing for the operator to do. |
| 305 | func verdictOf(ch valley.Change, v valley.Version) Verdict { |
| 306 | if _, ok := LandedAs(ch, v); ok { |
| 307 | return Integrated |
| 308 | } |
| 309 | switch { |
| 310 | case ch.State == valley.StateWithdrawn: |
| 311 | return Withdrawn |
| 312 | case v.N != ch.Active: |
| 313 | return Superseded |
| 314 | case ch.State == valley.StateDraft: |
| 315 | return Draft |
| 316 | case v.Landing == valley.Uncertain: |
| 317 | return Uncertain |
| 318 | case v.Outcome != nil: |
| 319 | switch strings.ToLower(v.Outcome.Decision) { |
| 320 | case "stale": |
| 321 | return StaleReason(ch, v) |
| 322 | case "rejected": |
| 323 | return Rejected |
| 324 | case "failed": |
| 325 | return Failed |
| 326 | } |
| 327 | return Uncertain |
| 328 | case v.Landing != valley.NotLanded: |
| 329 | // A landing value from a later valley. |
| 330 | return Uncertain |
| 331 | case v.Request != nil: |
| 332 | return Approved |
| 333 | default: |
| 334 | return Ready |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // LandedAs is the version change ch landed as, seen from its version v, and |
| 339 | // whether it landed: the valley's own verdict (landed_version), which reads |
| 340 | // a next round, made on a main that already holds a landing, unlanded. A |
| 341 | // valley older than the verdict leaves klaus the rule the versions show: a |
| 342 | // change has landed once any of its versions has (the valley's |
| 343 | // rebase.Snapshot.LandedAs), as v if it landed, else the newest that did. |
| 344 | func LandedAs(ch valley.Change, v valley.Version) (valley.Version, bool) { |
| 345 | if lv := ch.LandedVersion; lv.Listed { |
| 346 | if lv.N == nil { |
| 347 | return valley.Version{}, false |
| 348 | } |
| 349 | w := valley.Version{N: *lv.N} |
| 350 | for _, x := range ch.Versions { |
| 351 | if x.N == *lv.N { |
| 352 | w = x |
| 353 | } |
| 354 | } |
| 355 | if ch.LandedCommit != nil && *ch.LandedCommit != "" { |
| 356 | w.LandedCommit = ch.LandedCommit |
| 357 | } |
| 358 | return w, true |
| 359 | } |
| 360 | if landed(v) { |
| 361 | return v, true |
| 362 | } |
| 363 | var found valley.Version |
| 364 | ok := false |
| 365 | for _, w := range ch.Versions { |
| 366 | if landed(w) && (!ok || w.N > found.N) { |
| 367 | found, ok = w, true |
| 368 | } |
| 369 | } |
| 370 | return found, ok |
| 371 | } |
| 372 | |
| 373 | // landed reports whether the valley says version v landed. |
| 374 | func landed(v valley.Version) bool { |
| 375 | return v.Landing == valley.Landed || v.Landing == valley.LandedRecorded |
| 376 | } |
| 377 | |
| 378 | // StaleReason says what a stale decision on version v of change ch means. A |
| 379 | // conflict in the change's current restack report is Conflicting. Else the |
| 380 | // checks decide: pending ones leave the change Approved (the integrator |
| 381 | // re-judges the request when the evidence arrives), failed ones ChecksFailed. Passed |
| 382 | // checks, or none listed (an older valley), leave Stale: the evidence was |
| 383 | // found lacking for another reason. |
| 384 | func StaleReason(ch valley.Change, v valley.Version) Verdict { |
| 385 | if rs := ch.Restack; rs != nil && rs.Current && rs.Report != nil && rs.Report.Result == valley.RestackConflict { |
| 386 | return Conflicting |
| 387 | } |
| 388 | if v.Checks != nil { |
| 389 | switch v.Checks.State { |
| 390 | case valley.ChecksPending: |
| 391 | return Approved |
| 392 | case valley.ChecksFailed: |
| 393 | return ChecksFailed |
| 394 | } |
| 395 | } |
| 396 | return Stale |
| 397 | } |