| 1 | package pipeline |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "syscall" |
| 13 | "time" |
| 14 | |
| 15 | "the-valley/flow/internal/event" |
| 16 | "the-valley/flow/internal/integration" |
| 17 | "the-valley/flow/internal/valley" |
| 18 | ) |
| 19 | |
| 20 | // ChangeLedgerFile is the change ledger's file name in a session directory. |
| 21 | const ChangeLedgerFile = "change-transitions.json" |
| 22 | |
| 23 | // ChangeLedger is the durable record of what klaus has seen of each valley |
| 24 | // change, keyed by the valley's name for its repo and its change ID. It is |
| 25 | // for a valley change what Ledger is for a PR: it makes each change:* event |
| 26 | // fire once, across dashboard restarts and between dashboards on one |
| 27 | // session, since the valley's listing says only where a change stands now. |
| 28 | type ChangeLedger struct { |
| 29 | mu sync.Mutex |
| 30 | path string |
| 31 | changes map[string]*changeEntry |
| 32 | } |
| 33 | |
| 34 | // changeEntry holds, for one change, each mark the ledger keeps, with when |
| 35 | // it was first seen. |
| 36 | type changeEntry struct { |
| 37 | Version *ChangeMark `json:"version,omitempty"` // the highest version seen, and its head |
| 38 | Approved *ChangeMark `json:"approved,omitempty"` // the version whose integration request was first seen |
| 39 | Landed *ChangeMark `json:"landed,omitempty"` // the version that landed, and its landed commit |
| 40 | Outcome *ChangeMark `json:"outcome,omitempty"` // the last outcome: stale, rejected, failed or uncertain |
| 41 | Withdrawn *ChangeMark `json:"withdrawn,omitempty"` // the version active when the change was withdrawn |
| 42 | Checks *ChangeMark `json:"checks,omitempty"` // the last verdict of a version's checks: passed or failed |
| 43 | } |
| 44 | |
| 45 | // ChangeMark is a mark the ledger keeps for a change. |
| 46 | type ChangeMark struct { |
| 47 | Version int `json:"version"` |
| 48 | Head string `json:"head,omitempty"` |
| 49 | Commit string `json:"commit,omitempty"` // Landed's landed commit |
| 50 | Decision string `json:"decision,omitempty"` // Outcome's decision, or Checks' state |
| 51 | At string `json:"at"` // when it was first seen (RFC3339, with nanoseconds) |
| 52 | } |
| 53 | |
| 54 | // ChangeTransition is a mark a check found that the ledger didn't hold, and |
| 55 | // the event that reports it. |
| 56 | type ChangeTransition struct { |
| 57 | Type string // an event.Change* type |
| 58 | Version valley.Version // the version it concerns |
| 59 | // Commit is the commit the version landed as, for |
| 60 | // event.ChangeIntegrated: its landed_commit, else its head. |
| 61 | Commit string |
| 62 | // Failed names the version's failed checks, for |
| 63 | // event.ChangeChecksFailed and event.ChangeChecksPassed. |
| 64 | Failed []string |
| 65 | } |
| 66 | |
| 67 | // LoadChangeLedger reads the change ledger at path; a missing file is an |
| 68 | // empty ledger. It always returns a usable ledger: if the file can't be read |
| 69 | // the ledger starts empty, the error says why, and the next record rewrites |
| 70 | // the file. |
| 71 | func LoadChangeLedger(path string) (*ChangeLedger, error) { |
| 72 | l := &ChangeLedger{path: path, changes: make(map[string]*changeEntry)} |
| 73 | return l, l.mergeFromDisk() |
| 74 | } |
| 75 | |
| 76 | // changeLedgerKey is a change's key in the ledger. |
| 77 | func changeLedgerKey(repo, changeID string) string { |
| 78 | return repo + "/" + changeID |
| 79 | } |
| 80 | |
| 81 | // outcomeEvents maps an integrator's decision to the event that reports it. |
| 82 | // Uncertain is recorded, and reported by none. |
| 83 | var outcomeEvents = map[string]string{ |
| 84 | "stale": event.ChangeStale, |
| 85 | "rejected": event.ChangeRejected, |
| 86 | "failed": event.ChangeFailed, |
| 87 | } |
| 88 | |
| 89 | // checksEvents maps the state of a version's checks to the event that |
| 90 | // reports it. Pending is reported by none, nor recorded. |
| 91 | var checksEvents = map[string]string{ |
| 92 | valley.ChecksFailed: event.ChangeChecksFailed, |
| 93 | valley.ChecksPassed: event.ChangeChecksPassed, |
| 94 | } |
| 95 | |
| 96 | // Observe records where the valley's listing says change ch, in the repo the |
| 97 | // valley calls repo, stands, and returns the transitions the ledger didn't |
| 98 | // hold, in order: |
| 99 | // |
| 100 | // - change:new-version for each version above the highest the ledger |
| 101 | // holds that own says this session didn't record; |
| 102 | // - change:approved when the active version of a ready change has an |
| 103 | // integration request, and no version at or above it was approved; |
| 104 | // - change:integrated when the valley says the change landed |
| 105 | // (integration.LandedAs), whichever version is active, as a version |
| 106 | // above the last landing the ledger holds: once, and again when a next |
| 107 | // round lands; |
| 108 | // - change:withdrawn once, when the change was withdrawn without landing; |
| 109 | // - change:stale, change:rejected or change:failed when the integrator's |
| 110 | // decision on the active version of a ready change that hasn't landed |
| 111 | // is a new one, or is on a later version than the last; |
| 112 | // - change:checks-failed or change:checks-passed when the checks of the |
| 113 | // active version of a ready change that hasn't landed failed or passed, |
| 114 | // and the last verdict the ledger holds is on an earlier version or |
| 115 | // head, or is the other one. A listing with no checks, or pending |
| 116 | // ones, changes nothing. |
| 117 | // |
| 118 | // A listing whose active version is below the highest the ledger holds was |
| 119 | // read before the one that recorded that version, and reports only a |
| 120 | // landing: its approval, outcome or withdrawal is old news, and changes |
| 121 | // nothing. |
| 122 | // |
| 123 | // A change the ledger holds nothing for is recorded as it stands, and |
| 124 | // returns none: a first look at a session's changes reports no history. |
| 125 | // As with Ledger.record, the file stays locked from reading it to renaming |
| 126 | // its replacement in, so two dashboards never both report a transition. An |
| 127 | // error means the marks are held in memory but couldn't be saved, or were |
| 128 | // saved without the lock. |
| 129 | func (l *ChangeLedger) Observe(repo string, ch valley.Change, own func(valley.Version) bool) ([]ChangeTransition, error) { |
| 130 | l.mu.Lock() |
| 131 | defer l.mu.Unlock() |
| 132 | unlock, lockErr := l.lock() |
| 133 | defer unlock() |
| 134 | loadErr := l.mergeFromDisk() |
| 135 | |
| 136 | key := changeLedgerKey(repo, ch.ChangeID) |
| 137 | e := l.changes[key] |
| 138 | first := e == nil |
| 139 | if first { |
| 140 | e = &changeEntry{} |
| 141 | l.changes[key] = e |
| 142 | } |
| 143 | now := time.Now().UTC().Format(time.RFC3339Nano) |
| 144 | var out []ChangeTransition |
| 145 | changed := false |
| 146 | mark := func(field **ChangeMark, m ChangeMark, t ChangeTransition) { |
| 147 | m.At = now |
| 148 | *field = &m |
| 149 | changed = true |
| 150 | if !first && t.Type != "" { |
| 151 | out = append(out, t) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | versions := append([]valley.Version(nil), ch.Versions...) |
| 156 | sort.SliceStable(versions, func(i, j int) bool { return versions[i].N < versions[j].N }) |
| 157 | for _, v := range versions { |
| 158 | if e.Version != nil && v.N <= e.Version.Version { |
| 159 | continue |
| 160 | } |
| 161 | t := ChangeTransition{Version: v} |
| 162 | if !first && !own(v) { |
| 163 | t.Type = event.ChangeNewVersion |
| 164 | } |
| 165 | mark(&e.Version, ChangeMark{Version: v.N, Head: v.Head}, t) |
| 166 | } |
| 167 | |
| 168 | active, ok := integration.ActiveVersion(ch) |
| 169 | if !ok { |
| 170 | return out, l.saved(changed, lockErr, loadErr) |
| 171 | } |
| 172 | // Only a landing is news from an older listing: a version that landed |
| 173 | // stays landed. |
| 174 | superseded := active.N < e.Version.Version |
| 175 | if !superseded && ch.State == valley.StateReady && active.Request != nil && (e.Approved == nil || e.Approved.Version < active.N) { |
| 176 | mark(&e.Approved, ChangeMark{Version: active.N, Head: active.Head}, |
| 177 | ChangeTransition{Type: event.ChangeApproved, Version: active}) |
| 178 | } |
| 179 | v, isLanded := integration.LandedAs(ch, active) |
| 180 | if isLanded && (e.Landed == nil || e.Landed.Version < v.N) { |
| 181 | commit := v.Head |
| 182 | if v.LandedCommit != nil && *v.LandedCommit != "" { |
| 183 | commit = *v.LandedCommit |
| 184 | } |
| 185 | mark(&e.Landed, ChangeMark{Version: v.N, Head: v.Head, Commit: commit}, |
| 186 | ChangeTransition{Type: event.ChangeIntegrated, Version: v, Commit: commit}) |
| 187 | } |
| 188 | switch { |
| 189 | case isLanded, superseded: |
| 190 | case ch.State == valley.StateWithdrawn: |
| 191 | if e.Withdrawn == nil { |
| 192 | mark(&e.Withdrawn, ChangeMark{Version: active.N, Head: active.Head}, |
| 193 | ChangeTransition{Type: event.ChangeWithdrawn, Version: active}) |
| 194 | } |
| 195 | case ch.State == valley.StateReady: |
| 196 | d := outcomeOf(active) |
| 197 | // A stale decision that only waits for checks is not news, and is |
| 198 | // not recorded: a later stale for another reason still is. |
| 199 | if d == "stale" && integration.StaleReason(ch, active) == integration.Approved { |
| 200 | d = "" |
| 201 | } |
| 202 | if d != "" && (e.Outcome == nil || e.Outcome.Version < active.N || |
| 203 | e.Outcome.Version == active.N && e.Outcome.Decision != d) { |
| 204 | mark(&e.Outcome, ChangeMark{Version: active.N, Head: active.Head, Decision: d}, |
| 205 | ChangeTransition{Type: outcomeEvents[d], Version: active}) |
| 206 | } |
| 207 | if c := active.Checks; c != nil && checksEvents[c.State] != "" && |
| 208 | (e.Checks == nil || e.Checks.Version < active.N || |
| 209 | e.Checks.Version == active.N && (e.Checks.Head != active.Head || e.Checks.Decision != c.State)) { |
| 210 | mark(&e.Checks, ChangeMark{Version: active.N, Head: active.Head, Decision: c.State}, |
| 211 | ChangeTransition{Type: checksEvents[c.State], Version: active, Failed: c.FailedNames()}) |
| 212 | } |
| 213 | } |
| 214 | return out, l.saved(changed, lockErr, loadErr) |
| 215 | } |
| 216 | |
| 217 | // outcomeOf is what the integrator decided on v's request, for a version |
| 218 | // that hasn't landed: stale, rejected or failed; uncertain when the valley |
| 219 | // has no landing evidence for a consumed or failed request, or records a |
| 220 | // decision or landing klaus doesn't know; "" when there is none yet. |
| 221 | func outcomeOf(v valley.Version) string { |
| 222 | switch { |
| 223 | case v.Landing == valley.Uncertain: |
| 224 | return "uncertain" |
| 225 | case v.Outcome != nil: |
| 226 | d := strings.ToLower(v.Outcome.Decision) |
| 227 | if outcomeEvents[d] != "" { |
| 228 | return d |
| 229 | } |
| 230 | return "uncertain" |
| 231 | case v.Landing != valley.NotLanded: |
| 232 | return "uncertain" |
| 233 | } |
| 234 | return "" |
| 235 | } |
| 236 | |
| 237 | // saved writes the ledger when Observe changed it, and joins the errors. |
| 238 | // The caller holds l.mu and the file lock. |
| 239 | func (l *ChangeLedger) saved(changed bool, errs ...error) error { |
| 240 | if changed { |
| 241 | errs = append(errs, l.save()) |
| 242 | } |
| 243 | return errors.Join(errs...) |
| 244 | } |
| 245 | |
| 246 | // lock takes an exclusive lock shared with every process using the ledger |
| 247 | // file, as Ledger.lock does. |
| 248 | func (l *ChangeLedger) lock() (unlock func(), err error) { |
| 249 | f, err := os.OpenFile(l.path+".lock", os.O_CREATE|os.O_RDWR, 0o644) |
| 250 | if err != nil { |
| 251 | return func() {}, err |
| 252 | } |
| 253 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { |
| 254 | f.Close() |
| 255 | return func() {}, fmt.Errorf("locking %s: %w", f.Name(), err) |
| 256 | } |
| 257 | return func() { |
| 258 | syscall.Flock(int(f.Fd()), syscall.LOCK_UN) //nolint:errcheck |
| 259 | f.Close() |
| 260 | }, nil |
| 261 | } |
| 262 | |
| 263 | // mergeFromDisk adds the marks in the ledger file to the ones in memory, |
| 264 | // keeping the later of two: the higher version, or for an outcome on the |
| 265 | // same version, the one seen last. Every write merges the file first, so |
| 266 | // the file is never older than what a ledger holds, and wins a tie. The |
| 267 | // caller holds l.mu and the file lock, except in LoadChangeLedger. |
| 268 | func (l *ChangeLedger) mergeFromDisk() error { |
| 269 | data, err := os.ReadFile(l.path) |
| 270 | if errors.Is(err, os.ErrNotExist) { |
| 271 | return nil |
| 272 | } |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | var disk map[string]*changeEntry |
| 277 | if err := json.Unmarshal(data, &disk); err != nil { |
| 278 | return fmt.Errorf("parsing %s: %w", l.path, err) |
| 279 | } |
| 280 | for key, d := range disk { |
| 281 | if d == nil { |
| 282 | continue |
| 283 | } |
| 284 | e := l.changes[key] |
| 285 | if e == nil { |
| 286 | e = &changeEntry{} |
| 287 | l.changes[key] = e |
| 288 | } |
| 289 | later(&e.Version, d.Version) |
| 290 | later(&e.Approved, d.Approved) |
| 291 | later(&e.Landed, d.Landed) |
| 292 | later(&e.Outcome, d.Outcome) |
| 293 | later(&e.Withdrawn, d.Withdrawn) |
| 294 | later(&e.Checks, d.Checks) |
| 295 | } |
| 296 | return nil |
| 297 | } |
| 298 | |
| 299 | // later sets *m to d unless *m is the later mark. |
| 300 | func later(m **ChangeMark, d *ChangeMark) { |
| 301 | switch { |
| 302 | case d == nil: |
| 303 | case *m == nil, d.Version > (*m).Version, d.Version == (*m).Version && !d.seen().Before((*m).seen()): |
| 304 | *m = d |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | // seen is when the mark was first seen; the zero time if that can't be read. |
| 309 | func (m *ChangeMark) seen() time.Time { |
| 310 | t, _ := time.Parse(time.RFC3339Nano, m.At) |
| 311 | return t |
| 312 | } |
| 313 | |
| 314 | // save writes the ledger through a temporary file in the same directory, so |
| 315 | // a crash mid-write leaves the previous ledger in place. |
| 316 | func (l *ChangeLedger) save() error { |
| 317 | data, err := json.MarshalIndent(l.changes, "", " ") |
| 318 | if err != nil { |
| 319 | return err |
| 320 | } |
| 321 | f, err := os.CreateTemp(filepath.Dir(l.path), ".change-transitions-*") |
| 322 | if err != nil { |
| 323 | return err |
| 324 | } |
| 325 | defer os.Remove(f.Name()) |
| 326 | if _, err := f.Write(append(data, '\n')); err != nil { |
| 327 | f.Close() |
| 328 | return err |
| 329 | } |
| 330 | if err := f.Close(); err != nil { |
| 331 | return err |
| 332 | } |
| 333 | return os.Rename(f.Name(), l.path) |
| 334 | } |