| 1 | package restack |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "os" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "the-valley/flow/internal/event" |
| 14 | "the-valley/flow/internal/integration" |
| 15 | "the-valley/flow/internal/run" |
| 16 | "the-valley/flow/internal/valley" |
| 17 | ) |
| 18 | |
| 19 | // Repo is a valley repo the session's runs deliver to, and a clone to read |
| 20 | // it in and launch from. |
| 21 | type Repo struct { |
| 22 | Name string // the valley's name for it (integration.RepoName) |
| 23 | Dir string // a clone whose origin it is |
| 24 | Project string // what launch --repo names it by; "" to launch from Dir |
| 25 | } |
| 26 | |
| 27 | // Repos returns the valley repos the runs deliver to: a run's repo counts |
| 28 | // once finalize marked a version ready there, launch returned its change |
| 29 | // to draft, or klaus track added it. Each is read in a run's clone, or else |
| 30 | // in root, the repo the caller runs in; a listing names its repo, and one |
| 31 | // that names another is skipped. |
| 32 | func Repos(states []*run.State, root string) []Repo { |
| 33 | byName := make(map[string]Repo) |
| 34 | for _, s := range states { |
| 35 | if s.Valley == nil && s.Unready == nil && !integration.TracksChange(s) { |
| 36 | continue |
| 37 | } |
| 38 | name := integration.RepoName(s) |
| 39 | if name == "" { |
| 40 | continue |
| 41 | } |
| 42 | if s.CloneDir != nil && *s.CloneDir != "" { |
| 43 | if fi, err := os.Stat(*s.CloneDir); err == nil && fi.IsDir() { |
| 44 | r := Repo{Name: name, Dir: *s.CloneDir} |
| 45 | if s.TargetRepo != nil { |
| 46 | r.Project = *s.TargetRepo |
| 47 | } |
| 48 | if prev, ok := byName[name]; !ok || prev.Project == "" { |
| 49 | byName[name] = r |
| 50 | } |
| 51 | continue |
| 52 | } |
| 53 | } |
| 54 | if _, ok := byName[name]; !ok && root != "" { |
| 55 | byName[name] = Repo{Name: name, Dir: root} |
| 56 | } |
| 57 | } |
| 58 | out := make([]Repo, 0, len(byName)) |
| 59 | for _, r := range byName { |
| 60 | out = append(out, r) |
| 61 | } |
| 62 | sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) |
| 63 | return out |
| 64 | } |
| 65 | |
| 66 | // Launch is a resolution run to launch, in Dir: klaus launch [--repo |
| 67 | // Project] --change ChangeID --run-id RunID --expect-owner Owner |
| 68 | // --expect-branch Branch --expect-head Head --expect-draft --reason |
| 69 | // restack-conflict Prompt. Launch checks the change still stands as klaus |
| 70 | // checked it, and starts no worker unless it does. |
| 71 | type Launch struct { |
| 72 | Dir, Project, ChangeID, Prompt string |
| 73 | RunID string // the run's ID, which klaus records before launching it |
| 74 | Owner, Branch, Head string // the change as klaus checked it: its owner, branch and head, a draft |
| 75 | } |
| 76 | |
| 77 | // ErrNotStarted is a launch error that says no worker started: launch |
| 78 | // failed before starting one. |
| 79 | var ErrNotStarted = errors.New("launch started no worker") |
| 80 | |
| 81 | // Deps are what a pass reads and does. Production uses Default's; tests |
| 82 | // replace them. |
| 83 | type Deps struct { |
| 84 | List func(ctx context.Context, dir string) (*valley.Changes, error) |
| 85 | Principal func(ctx context.Context, dir string) string |
| 86 | OriginRefs func(ctx context.Context, dir string, refs ...string) (map[string]string, error) |
| 87 | Unready func(ctx context.Context, dir, changeID string) error |
| 88 | // NewRunID names a run before it is launched. |
| 89 | NewRunID func() (string, error) |
| 90 | // Launch launches a resolution run under l.RunID. An error wrapping |
| 91 | // ErrNotStarted says no worker started; any other may come after one |
| 92 | // did. |
| 93 | Launch func(ctx context.Context, l Launch) error |
| 94 | // Started reports whether a run by an ID is recorded, in any session. |
| 95 | Started func(runID string) bool |
| 96 | // Running reports whether a run, in any session, is working on the |
| 97 | // change or its branch. |
| 98 | Running func(k Key, branch string) bool |
| 99 | // WorkerGone reports whether klaus can prove that no worker of a run |
| 100 | // by an ID runs, nor is about to start, from the clone at dir. Any |
| 101 | // doubt is false. |
| 102 | WorkerGone func(ctx context.Context, dir, runID string) bool |
| 103 | // Emit records an event under a run ID. |
| 104 | Emit func(runID, typ string, data map[string]interface{}) |
| 105 | Now func() time.Time |
| 106 | } |
| 107 | |
| 108 | // Default returns the Deps that run valley and git. launch, started, |
| 109 | // running, gone and emit are the caller's. |
| 110 | func Default(launch func(context.Context, Launch) error, started func(string) bool, running func(Key, string) bool, |
| 111 | gone func(context.Context, string, string) bool, emit func(string, string, map[string]interface{})) Deps { |
| 112 | return Deps{ |
| 113 | List: valley.ListRepo, |
| 114 | Principal: valley.Principal, |
| 115 | OriginRefs: valley.OriginRefs, |
| 116 | Unready: func(ctx context.Context, dir, id string) error { |
| 117 | _, err := valley.Unready(ctx, dir, id) |
| 118 | return err |
| 119 | }, |
| 120 | NewRunID: run.GenID, |
| 121 | Launch: launch, |
| 122 | Started: started, |
| 123 | Running: running, |
| 124 | WorkerGone: gone, |
| 125 | Emit: emit, |
| 126 | Now: time.Now, |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // RunningOn returns a Running that reports whether any of states, judged |
| 131 | // by td, is running on a change (its change ID in its repo) or its branch. |
| 132 | func RunningOn(states []*run.State, td run.TmuxDeps) func(Key, string) bool { |
| 133 | return func(k Key, branch string) bool { |
| 134 | for _, s := range states { |
| 135 | if s == nil || integration.RepoName(s) != k.Repo { |
| 136 | continue |
| 137 | } |
| 138 | if (s.ChangeID == k.ChangeID || branch != "" && s.Branch == branch) && s.IsAgentRunningWith(td) { |
| 139 | return true |
| 140 | } |
| 141 | } |
| 142 | return false |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // The states of a View. |
| 147 | const ( |
| 148 | StateDue = "due" // a run would be dispatched (a pass that doesn't act) |
| 149 | StateDispatched = "dispatched" // a run was dispatched for the conflict |
| 150 | StateLaunching = "launching" // klaus launched a run and can't yet tell whether it started |
| 151 | StateBusy = "busy" // a run is working on the change |
| 152 | StateCooldown = "cooldown" // a run was dispatched within the cooldown |
| 153 | StateStopped = "stopped" // the attempts are spent |
| 154 | StateRefused = "refused" // klaus didn't launch: Detail says why |
| 155 | StateHeld = "held" // klaus leaves the conflict alone: Detail says why |
| 156 | StateStale = "stale" // the report's inputs moved when klaus read them again |
| 157 | ) |
| 158 | |
| 159 | // View is where a change's restack conflict stands after a pass. |
| 160 | type View struct { |
| 161 | Key |
| 162 | Handle string |
| 163 | Version int |
| 164 | Head string |
| 165 | TargetTip string |
| 166 | State string |
| 167 | RunID string // the latest resolution run |
| 168 | Attempts int |
| 169 | Detail string |
| 170 | } |
| 171 | |
| 172 | // Name is how a view names its change: repo and handle, or the change ID. |
| 173 | func (v View) Name() string { |
| 174 | if v.Handle != "" { |
| 175 | return v.Repo + " " + v.Handle |
| 176 | } |
| 177 | return v.Repo + " " + v.ChangeID |
| 178 | } |
| 179 | |
| 180 | // Summary says, in a line, where the conflict stands. |
| 181 | func (v View) Summary() string { |
| 182 | switch v.State { |
| 183 | case StateDue: |
| 184 | return "a resolution run is due" |
| 185 | case StateDispatched: |
| 186 | return fmt.Sprintf("resolution run %s dispatched (attempt %d of %d)", v.RunID, v.Attempts, MaxAttempts) |
| 187 | case StateLaunching: |
| 188 | if v.Detail != "" { |
| 189 | return fmt.Sprintf("resolution run %s (attempt %d of %d) may have started its worker: %s; klaus waits until it can tell none runs", v.RunID, v.Attempts, MaxAttempts, v.Detail) |
| 190 | } |
| 191 | return fmt.Sprintf("launching resolution run %s (attempt %d of %d)", v.RunID, v.Attempts, MaxAttempts) |
| 192 | case StateBusy: |
| 193 | return "a run is working on the change" |
| 194 | case StateCooldown: |
| 195 | return fmt.Sprintf("waiting out the cooldown after run %s (attempt %d of %d)", v.RunID, v.Attempts, MaxAttempts) |
| 196 | case StateStopped: |
| 197 | return fmt.Sprintf("stopped after %d resolution runs; resolve it by hand", v.Attempts) |
| 198 | case StateRefused: |
| 199 | return "not dispatched: " + v.Detail |
| 200 | case StateHeld: |
| 201 | return "left alone: " + v.Detail |
| 202 | case StateStale: |
| 203 | return "skipped, stale: " + v.Detail |
| 204 | } |
| 205 | return v.State |
| 206 | } |
| 207 | |
| 208 | // String is the view as klaus status and klaus restack-conflicts print it. |
| 209 | func (v View) String() string { |
| 210 | return fmt.Sprintf("%s v%d: conflict rebasing onto main at %s; %s", v.Name(), v.Version, short(v.TargetTip), v.Summary()) |
| 211 | } |
| 212 | |
| 213 | // Pass reads each repo's restack reports and returns a view of every |
| 214 | // conflict on a change klaus owns: the current conflicts, and the ones it |
| 215 | // acted on whose change still stands at the head it acted on. It reads |
| 216 | // them in listed, a listing already read, as the dashboard's integration |
| 217 | // check reads one for every repo; with none, it lists each repo itself. With |
| 218 | // act, in each repo it first settles the launches the ledger holds pending |
| 219 | // (reconcile) and drops the entries of changes that landed or were |
| 220 | // withdrawn (prune), then dispatches what Decide says to, and records what |
| 221 | // it did in the ledger; without, it only reports, leaving the ledger and |
| 222 | // the valley as they were. A repo the valley can't be asked about is |
| 223 | // skipped. |
| 224 | func Pass(ctx context.Context, d Deps, l *Ledger, repos []Repo, listed *valley.Changes, act bool) []View { |
| 225 | var views []View |
| 226 | for _, r := range repos { |
| 227 | if act { |
| 228 | d.reconcile(ctx, l, r) |
| 229 | } |
| 230 | vr, ok := repoIn(listed, r) |
| 231 | if listed == nil { |
| 232 | vr, ok = listRepo(ctx, d, r) |
| 233 | } |
| 234 | if !ok { |
| 235 | continue |
| 236 | } |
| 237 | if act { |
| 238 | d.prune(l, vr) |
| 239 | } |
| 240 | principal := d.Principal(ctx, r.Dir) |
| 241 | conflicts, clean := Scan(vr, principal) |
| 242 | if act { |
| 243 | for _, k := range clean { |
| 244 | d.reset(ctx, l, r, k) |
| 245 | } |
| 246 | } |
| 247 | seen := make(map[Key]bool) |
| 248 | for _, c := range conflicts { |
| 249 | seen[c.Key] = true |
| 250 | views = append(views, d.handle(ctx, l, r, c, act)) |
| 251 | } |
| 252 | views = append(views, d.actedViews(vr, principal, l, seen, act)...) |
| 253 | } |
| 254 | return views |
| 255 | } |
| 256 | |
| 257 | // reconcile settles the launches the ledger holds pending in repo r: one a |
| 258 | // pass left when it ended before its launch returned, or one whose launch |
| 259 | // failed leaving klaus unsure whether its worker started. A launch whose |
| 260 | // run is recorded is a dispatch. One whose worker klaus can prove gone |
| 261 | // (WorkerGone) ended without a run klaus can vouch for, keeping its |
| 262 | // attempt and its cooldown since a worker may have run; klaus says it |
| 263 | // stopped short. The rest stay pending, their changes busy, for as long as |
| 264 | // klaus can't tell: the passing of time proves nothing. |
| 265 | func (d Deps) reconcile(ctx context.Context, l *Ledger, r Repo) { |
| 266 | for _, e := range l.sorted() { |
| 267 | a := e.Pending() |
| 268 | if e.Repo != r.Name || a == nil { |
| 269 | continue |
| 270 | } |
| 271 | switch { |
| 272 | case d.started(a.RunID): |
| 273 | a.Pending = false |
| 274 | if !d.save(l) { |
| 275 | a.Pending = true |
| 276 | continue |
| 277 | } |
| 278 | d.emitDispatched(e, a) |
| 279 | case d.gone(ctx, r.Dir, a.RunID): |
| 280 | failed := a.Refused |
| 281 | a.Pending = false |
| 282 | a.Refused = fmt.Sprintf("klaus lost sight of its launch of run %s, and no worker of it runs; the attempt still counts", a.RunID) |
| 283 | if failed != "" { |
| 284 | a.Refused = fmt.Sprintf("no worker of run %s runs, and the attempt still counts; %s", a.RunID, failed) |
| 285 | } |
| 286 | if !d.save(l) { |
| 287 | a.Pending, a.Refused = true, failed |
| 288 | continue |
| 289 | } |
| 290 | d.emitStalled(e, a, a.Refused) |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // prune drops the entries of vr's changes that landed or were withdrawn: |
| 296 | // klaus dispatches nothing more for them. An entry with a launch pending |
| 297 | // stays until it is settled, and one whose change vr doesn't list stays. |
| 298 | func (d Deps) prune(l *Ledger, vr valley.Repo) { |
| 299 | live := make(map[string]bool) |
| 300 | listed := make(map[string]bool) |
| 301 | for _, ch := range vr.Changes { |
| 302 | listed[ch.ChangeID] = true |
| 303 | active, ok := activeVersion(ch) |
| 304 | landed := ok && (active.Landing == valley.Landed || active.Landing == valley.LandedRecorded) |
| 305 | if ch.State != valley.StateWithdrawn && !landed { |
| 306 | live[ch.ChangeID] = true |
| 307 | } |
| 308 | } |
| 309 | var dropped []*Entry |
| 310 | for _, e := range l.sorted() { |
| 311 | if e.Repo == vr.Repo && listed[e.ChangeID] && !live[e.ChangeID] && e.Pending() == nil { |
| 312 | l.drop(Key{Repo: e.Repo, ChangeID: e.ChangeID}) |
| 313 | dropped = append(dropped, e) |
| 314 | } |
| 315 | } |
| 316 | if len(dropped) > 0 && !d.save(l) { |
| 317 | for _, e := range dropped { |
| 318 | l.put(e) |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // reset gives a change its attempts back after a clean restack, once per |
| 324 | // clean report, and only while origin still holds that report: the |
| 325 | // listing may have been read before a pass that dispatched on a newer |
| 326 | // conflict report took the ledger, and a report origin no longer holds |
| 327 | // says nothing of the attempts made since. |
| 328 | func (d Deps) reset(ctx context.Context, l *Ledger, r Repo, k Clean) { |
| 329 | e := l.Entry(k.Key) |
| 330 | if e == nil || e.Attempts == 0 && e.Stopped == "" || e.Clean == k.Report || e.Pending() != nil { |
| 331 | return |
| 332 | } |
| 333 | ref := ReportRef(k.Target, k.ChangeID) |
| 334 | refs, err := d.OriginRefs(ctx, r.Dir, ref) |
| 335 | if err != nil || refs[ref] != k.Report { |
| 336 | return |
| 337 | } |
| 338 | attempts, stopped, clean := e.Attempts, e.Stopped, e.Clean |
| 339 | e.Attempts, e.Stopped, e.Clean = 0, "", k.Report |
| 340 | if !d.save(l) { // a reset that isn't saved is made again next pass |
| 341 | e.Attempts, e.Stopped, e.Clean = attempts, stopped, clean |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // listRepo lists a repo, and returns the listing's entry for it. |
| 346 | func listRepo(ctx context.Context, d Deps, r Repo) (valley.Repo, bool) { |
| 347 | l, err := d.List(ctx, r.Dir) |
| 348 | if err != nil { |
| 349 | return valley.Repo{}, false |
| 350 | } |
| 351 | return repoIn(l, r) |
| 352 | } |
| 353 | |
| 354 | // repoIn returns a listing's entry for a repo it could read. |
| 355 | func repoIn(l *valley.Changes, r Repo) (valley.Repo, bool) { |
| 356 | if l == nil { |
| 357 | return valley.Repo{}, false |
| 358 | } |
| 359 | for _, vr := range l.Repos { |
| 360 | if vr.Repo == r.Name && vr.Err() == "" { |
| 361 | return vr, true |
| 362 | } |
| 363 | } |
| 364 | return valley.Repo{}, false |
| 365 | } |
| 366 | |
| 367 | // actedViews returns a view of each change in vr that klaus acted on and |
| 368 | // that has no current conflict (seen), while it is unlanded, not |
| 369 | // withdrawn, and its latest report is one klaus acted on, at the head it |
| 370 | // acted on: after klaus returned it to draft, its report reads historical. |
| 371 | // Once no run is working on such a change and its attempts are spent, it |
| 372 | // is stopped, and with act klaus says so once. |
| 373 | func (d Deps) actedViews(vr valley.Repo, principal string, l *Ledger, seen map[Key]bool, act bool) []View { |
| 374 | var views []View |
| 375 | for _, ch := range vr.Changes { |
| 376 | k := Key{Repo: vr.Repo, ChangeID: ch.ChangeID} |
| 377 | e := l.Entry(k) |
| 378 | if seen[k] || e == nil || ch.Owner != principal || ch.Restack == nil { |
| 379 | continue |
| 380 | } |
| 381 | active, ok := activeVersion(ch) |
| 382 | landed := active.Landing == valley.Landed || active.Landing == valley.LandedRecorded |
| 383 | a := e.actionOnReport(ch.Restack.Commit, active.Head) |
| 384 | if !ok || a == nil || ch.State == valley.StateWithdrawn || landed { |
| 385 | continue |
| 386 | } |
| 387 | v := viewOf(k, ch.Handle, ch.Active, e, a) |
| 388 | if e.Attempts >= MaxAttempts && e.Pending() == nil && !d.Running(k, active.Branch) { |
| 389 | v.State, v.Detail = StateStopped, "" |
| 390 | if act { |
| 391 | d.stop(l, e, a) |
| 392 | } |
| 393 | } |
| 394 | views = append(views, v) |
| 395 | } |
| 396 | return views |
| 397 | } |
| 398 | |
| 399 | // viewOf is the view of what klaus did, a, about one of a change's |
| 400 | // conflicts, e its entry. |
| 401 | func viewOf(k Key, handle string, version int, e *Entry, a *Action) View { |
| 402 | v := View{Key: k, Handle: handle, Version: version, Head: a.Head, TargetTip: a.TargetTip, |
| 403 | RunID: a.RunID, Attempts: e.Attempts, State: StateDispatched} |
| 404 | switch { |
| 405 | case a.Pending: |
| 406 | v.State, v.Detail = StateLaunching, a.Refused |
| 407 | case a.Refused != "": |
| 408 | v.State, v.Detail = StateRefused, a.Refused |
| 409 | case e.Stopped != "": |
| 410 | v.State = StateStopped |
| 411 | } |
| 412 | return v |
| 413 | } |
| 414 | |
| 415 | // stop records that klaus stopped dispatching for a change whose attempts |
| 416 | // are spent, on the conflict a names, and says so once: only once it is |
| 417 | // recorded that it did. |
| 418 | func (d Deps) stop(l *Ledger, e *Entry, a *Action) { |
| 419 | if e.Stopped != "" { |
| 420 | return |
| 421 | } |
| 422 | e.Stopped = d.Now().UTC().Format(time.RFC3339) |
| 423 | if !d.save(l) { |
| 424 | e.Stopped = "" |
| 425 | return |
| 426 | } |
| 427 | d.emitStalled(e, a, fmt.Sprintf("%d resolution runs did not resolve its restack conflicts", e.Attempts)) |
| 428 | } |
| 429 | |
| 430 | // leave records that klaus leaves conflict c alone, and says so once for its |
| 431 | // inputs: only once it is recorded that it did. The coordinator learns of |
| 432 | // it from change:restack-stalled; the change doesn't move unless someone |
| 433 | // steps in. |
| 434 | func (d Deps) leave(l *Ledger, c Conflict) { |
| 435 | e := l.Entry(c.Key) |
| 436 | if e.leftOn(c.inputs()) != nil { |
| 437 | return |
| 438 | } |
| 439 | created := e == nil |
| 440 | if created { |
| 441 | e = &Entry{Repo: c.Repo, ChangeID: c.ChangeID} |
| 442 | l.put(e) |
| 443 | } |
| 444 | prevLeft, prevHandle := e.LeftAlone, e.Handle |
| 445 | e.Handle = c.Handle |
| 446 | e.LeftAlone = append(e.LeftAlone, &Left{At: d.Now().UTC(), Report: c.Report, Head: c.Head, TargetTip: c.TargetTip, Reason: c.HeldReason}) |
| 447 | if len(e.LeftAlone) > MaxActions { |
| 448 | e.LeftAlone = e.LeftAlone[len(e.LeftAlone)-MaxActions:] |
| 449 | } |
| 450 | if !d.save(l) { |
| 451 | e.LeftAlone, e.Handle = prevLeft, prevHandle |
| 452 | if created { |
| 453 | l.drop(c.Key) |
| 454 | } |
| 455 | return |
| 456 | } |
| 457 | d.emitStalled(e, &Action{Report: c.Report, Version: c.Version, Head: c.Head, TargetTip: c.TargetTip}, c.HeldReason) |
| 458 | } |
| 459 | |
| 460 | // handle decides about one conflict and, with act, carries the decision |
| 461 | // out. |
| 462 | func (d Deps) handle(ctx context.Context, l *Ledger, r Repo, c Conflict, act bool) View { |
| 463 | e := l.Entry(c.Key) |
| 464 | v := View{Key: c.Key, Handle: c.Handle, Version: c.Version, Head: c.Head, TargetTip: c.TargetTip} |
| 465 | if e != nil { |
| 466 | v.Attempts = e.Attempts |
| 467 | if last := e.Last(); last != nil { |
| 468 | v.RunID = last.RunID |
| 469 | } |
| 470 | } |
| 471 | switch Decide(d.Now(), c, e, d.Running(c.Key, c.Branch)) { |
| 472 | case Held: |
| 473 | v.State, v.Detail = StateHeld, c.Held |
| 474 | if act { |
| 475 | d.leave(l, c) |
| 476 | } |
| 477 | case Acted: |
| 478 | v = viewOf(c.Key, c.Handle, c.Version, e, e.ActionOn(c.inputs())) |
| 479 | case Busy: |
| 480 | v.State = StateBusy |
| 481 | if a := e.Pending(); a != nil { |
| 482 | v = viewOf(c.Key, c.Handle, c.Version, e, a) |
| 483 | } |
| 484 | case Wait: |
| 485 | v.State = StateCooldown |
| 486 | case Stop: |
| 487 | v.State = StateStopped |
| 488 | if act { |
| 489 | d.stop(l, e, &Action{Report: c.Report, Version: c.Version, Head: c.Head, TargetTip: c.TargetTip}) |
| 490 | } |
| 491 | case Dispatch: |
| 492 | if !act { |
| 493 | v.State = StateDue |
| 494 | break |
| 495 | } |
| 496 | return d.dispatch(ctx, l, r, c) |
| 497 | } |
| 498 | return v |
| 499 | } |
| 500 | |
| 501 | // dispatch reads the change and origin again, returns the change to draft, |
| 502 | // and launches a resolution run, recording what it did. A report whose |
| 503 | // inputs moved is skipped and nothing is recorded: the next pass reads |
| 504 | // whatever replaced it. If the change can't be confirmed a draft, owned by |
| 505 | // klaus at the head and branch it checked, no run launches; and launch |
| 506 | // checks all of it again before it starts a worker. |
| 507 | // |
| 508 | // The ledger is written ahead: the inputs, the attempt and the run's ID, |
| 509 | // pending, are saved before klaus touches the change, and if they can't |
| 510 | // be, it does nothing. An attempt is given back only once klaus knows no |
| 511 | // worker started: it stopped before launching, or launch says it started |
| 512 | // none. A failed save later can then only make klaus do less, never act |
| 513 | // twice on one conflict or run past MaxAttempts, and a pass that ends |
| 514 | // mid-launch leaves the launch for the next to reconcile. So does a launch |
| 515 | // that fails after it may have started its worker, unless klaus can prove |
| 516 | // no worker of it runs (WorkerGone): until it can, the change is busy. |
| 517 | func (d Deps) dispatch(ctx context.Context, l *Ledger, r Repo, c Conflict) View { |
| 518 | v := View{Key: c.Key, Handle: c.Handle, Version: c.Version, Head: c.Head, TargetTip: c.TargetTip} |
| 519 | if e := l.Entry(c.Key); e != nil { |
| 520 | v.Attempts = e.Attempts |
| 521 | } |
| 522 | if why := d.recheck(ctx, r, c); why != "" { |
| 523 | v.State, v.Detail = StateStale, why |
| 524 | return v |
| 525 | } |
| 526 | runID, err := d.NewRunID() |
| 527 | if err != nil { |
| 528 | v.State, v.Detail = StateRefused, "klaus couldn't name the run: "+err.Error() |
| 529 | return v |
| 530 | } |
| 531 | |
| 532 | e := l.Entry(c.Key) |
| 533 | if e == nil { |
| 534 | e = &Entry{Repo: c.Repo, ChangeID: c.ChangeID} |
| 535 | l.put(e) |
| 536 | } |
| 537 | act := &Action{At: d.Now().UTC(), Report: c.Report, Version: c.Version, Head: c.Head, TargetTip: c.TargetTip, |
| 538 | RunID: runID, Pending: true} |
| 539 | prevActions, prevAttempts, prevHandle := e.Actions, e.Attempts, e.Handle |
| 540 | e.Handle = c.Handle |
| 541 | e.Attempts++ // counted up front, and given back once no worker started |
| 542 | e.record(act) |
| 543 | if !d.save(l) { |
| 544 | e.Actions, e.Attempts, e.Handle = prevActions, prevAttempts, prevHandle |
| 545 | v.State, v.Detail = StateRefused, "klaus couldn't record the dispatch in its ledger" |
| 546 | return v |
| 547 | } |
| 548 | // refuse gives the attempt back: no worker started. |
| 549 | refuse := func(why string) View { |
| 550 | e.Attempts-- |
| 551 | act.RunID, act.Pending, act.Refused = "", false, why |
| 552 | d.save(l) |
| 553 | d.emitStalled(e, act, why) |
| 554 | v.State, v.Detail, v.Attempts = StateRefused, why, e.Attempts |
| 555 | return v |
| 556 | } |
| 557 | |
| 558 | // The change must be a draft before a run edits it, so approve |
| 559 | // refuses it meanwhile. |
| 560 | if err := d.Unready(ctx, r.Dir, c.ChangeID); err != nil { |
| 561 | return refuse("could not return the change to draft: " + err.Error()) |
| 562 | } |
| 563 | vr, ok := listRepo(ctx, d, r) |
| 564 | if !ok { |
| 565 | return refuse("could not confirm the change is a draft: the valley couldn't be asked") |
| 566 | } |
| 567 | ch, found := changeIn(vr, c.ChangeID) |
| 568 | active, hasActive := activeVersion(ch) |
| 569 | switch { |
| 570 | case !found: |
| 571 | return refuse("could not confirm the change is a draft: the valley no longer lists it") |
| 572 | case ch.State != valley.StateDraft: |
| 573 | return refuse(fmt.Sprintf("the change is %s after valley unready, not a draft", ch.State)) |
| 574 | case ch.Owner != c.Owner: |
| 575 | return refuse("the change's owner changed while klaus returned it to draft") |
| 576 | case !hasActive || active.Head != c.Head || active.Branch != c.Branch: |
| 577 | return refuse("the change's head moved while klaus returned it to draft") |
| 578 | } |
| 579 | |
| 580 | prompt := Prompt(c) |
| 581 | if prompt == "" { |
| 582 | return refuse("its change ID or heads don't read as klaus expects") |
| 583 | } |
| 584 | err = d.Launch(ctx, Launch{Dir: r.Dir, Project: r.Project, ChangeID: c.ChangeID, Prompt: prompt, |
| 585 | RunID: runID, Owner: c.Owner, Branch: c.Branch, Head: c.Head}) |
| 586 | switch { |
| 587 | case err == nil || d.started(runID): |
| 588 | act.Pending = false |
| 589 | d.save(l) |
| 590 | d.emitDispatched(e, act) |
| 591 | v.State, v.RunID, v.Attempts = StateDispatched, runID, e.Attempts |
| 592 | case errors.Is(err, ErrNotStarted): |
| 593 | return refuse("launch failed, and the change is left a draft: " + firstLine(err.Error())) |
| 594 | default: |
| 595 | // Launch may have started the worker and failed after: the |
| 596 | // attempt and the cooldown stand, and the launch stays pending |
| 597 | // until klaus can prove no worker of it runs. |
| 598 | act.Refused = "launch failed: " + firstLine(err.Error()) |
| 599 | d.save(l) |
| 600 | d.reconcile(ctx, l, r) |
| 601 | v = viewOf(c.Key, c.Handle, c.Version, e, act) |
| 602 | } |
| 603 | return v |
| 604 | } |
| 605 | |
| 606 | // recheck reads the change and origin's refs again, and says why the |
| 607 | // conflict no longer stands as the report says, or "" when it does. |
| 608 | func (d Deps) recheck(ctx context.Context, r Repo, c Conflict) string { |
| 609 | vr, ok := listRepo(ctx, d, r) |
| 610 | if !ok { |
| 611 | return "the valley couldn't be asked again" |
| 612 | } |
| 613 | again, _ := Scan(vr, d.Principal(ctx, r.Dir)) |
| 614 | same := false |
| 615 | for _, a := range again { |
| 616 | if a.Key == c.Key && a.Report == c.Report && a.Head == c.Head && a.TargetTip == c.TargetTip && a.Held == "" { |
| 617 | same = true |
| 618 | } |
| 619 | } |
| 620 | if !same { |
| 621 | return "the valley's view of the change changed" |
| 622 | } |
| 623 | refs, err := d.OriginRefs(ctx, r.Dir, Refs(c)...) |
| 624 | if err != nil { |
| 625 | return err.Error() |
| 626 | } |
| 627 | return Stale(c, refs) |
| 628 | } |
| 629 | |
| 630 | func changeIn(vr valley.Repo, id string) (valley.Change, bool) { |
| 631 | for _, ch := range vr.Changes { |
| 632 | if ch.ChangeID == id { |
| 633 | return ch, true |
| 634 | } |
| 635 | } |
| 636 | return valley.Change{}, false |
| 637 | } |
| 638 | |
| 639 | // save writes the ledger, and reports whether it could. |
| 640 | func (d Deps) save(l *Ledger) bool { |
| 641 | if err := l.save(); err != nil { |
| 642 | slog.Warn("saving the restack ledger", "err", err) |
| 643 | return false |
| 644 | } |
| 645 | return true |
| 646 | } |
| 647 | |
| 648 | func (d Deps) emit(runID, typ string, data map[string]interface{}) { |
| 649 | if d.Emit != nil { |
| 650 | d.Emit(runID, typ, data) |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | // gone reports whether klaus can prove no worker of run runID runs. |
| 655 | func (d Deps) gone(ctx context.Context, dir, runID string) bool { |
| 656 | return runID != "" && d.WorkerGone != nil && d.WorkerGone(ctx, dir, runID) |
| 657 | } |
| 658 | |
| 659 | // started reports whether a run by runID is recorded. |
| 660 | func (d Deps) started(runID string) bool { |
| 661 | return runID != "" && d.Started != nil && d.Started(runID) |
| 662 | } |
| 663 | |
| 664 | // emitDispatched says klaus dispatched a's run, under the run's ID. |
| 665 | func (d Deps) emitDispatched(e *Entry, a *Action) { |
| 666 | d.emit(a.RunID, event.ChangeRestackDispatched, map[string]interface{}{ |
| 667 | "repo": e.Repo, "change_id": e.ChangeID, "handle": e.Handle, "version": a.Version, |
| 668 | "head": a.Head, "target_tip": a.TargetTip, "report": a.Report, |
| 669 | "attempt": e.Attempts, "max_attempts": MaxAttempts, |
| 670 | }) |
| 671 | } |
| 672 | |
| 673 | // emitStalled says klaus stopped short of resolving a change's conflict, |
| 674 | // the one a names. It goes out under the change ID, which no run has. |
| 675 | func (d Deps) emitStalled(e *Entry, a *Action, reason string) { |
| 676 | data := map[string]interface{}{"repo": e.Repo, "change_id": e.ChangeID, "handle": e.Handle, "reason": reason} |
| 677 | if a != nil { |
| 678 | data["version"], data["head"], data["target_tip"], data["report"] = a.Version, a.Head, a.TargetTip, a.Report |
| 679 | if a.RunID != "" { |
| 680 | data["run_id"] = a.RunID |
| 681 | } |
| 682 | } |
| 683 | d.emit(e.ChangeID, event.ChangeRestackStalled, data) |
| 684 | } |
| 685 | |
| 686 | func short(sha string) string { |
| 687 | if len(sha) > 7 { |
| 688 | return sha[:7] |
| 689 | } |
| 690 | return sha |
| 691 | } |
| 692 | |
| 693 | func firstLine(s string) string { |
| 694 | s = strings.TrimSpace(s) |
| 695 | if i := strings.IndexByte(s, '\n'); i >= 0 { |
| 696 | s = s[:i] |
| 697 | } |
| 698 | if r := []rune(s); len(r) > 200 { |
| 699 | s = string(r[:199]) + "…" |
| 700 | } |
| 701 | return s |
| 702 | } |