gunk-dev/the-valley

ledger.go

source4cbb5ec9c5dbmain's published tip history
9.0 KiB
1package restack
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "sort"
10 "syscall"
11 "time"
12)
13
14// LedgerFile is the ledger's file name in a session directory.
15const LedgerFile = "restack-dispatches.json"
16
17// Entry is what klaus did about one change's restack conflicts.
18type Entry struct {
19 Repo string `json:"repo"`
20 ChangeID string `json:"change_id"`
21 Handle string `json:"handle,omitempty"`
22 // Attempts counts the resolution runs dispatched since the change last
23 // restacked cleanly, including a launch that may have started a run.
24 Attempts int `json:"attempts"`
25 // Actions are what klaus did on each set of inputs it acted on,
26 // whatever came of it, oldest first: klaus acts once on each, so a
27 // conflict that comes back to inputs it acted on before isn't tried
28 // again, and shows what came of them then. It keeps the latest
29 // MaxActions.
30 Actions []*Action `json:"actions,omitempty"`
31 // LeftAlone are the sets of inputs klaus said it leaves alone (held),
32 // oldest first, so it says so once for each. They are no action: they
33 // count no attempt and don't stop a later pass dispatching on the same
34 // inputs should the conflict stop being held. It keeps the latest
35 // MaxActions.
36 LeftAlone []*Left `json:"left_alone,omitempty"`
37 // Clean is the report commit of the last clean restack that gave the
38 // change its attempts back, so one report resets them once.
39 Clean string `json:"clean,omitempty"`
40 // Stopped is when klaus stopped dispatching for the change, its
41 // attempts spent (RFC3339); "" while it hasn't.
42 Stopped string `json:"stopped,omitempty"`
43
44 // A ledger written before Actions was kept holds its latest action in
45 // "last", and every set of inputs acted on in "consumed"; LoadLedger
46 // moves them into Actions.
47 OldLast *Action `json:"last,omitempty"`
48 OldConsumed []Inputs `json:"consumed,omitempty"`
49}
50
51// Left is a conflict klaus left alone, and why, on one set of inputs.
52type Left struct {
53 At time.Time `json:"at"`
54 Report string `json:"report"`
55 Head string `json:"head"`
56 TargetTip string `json:"target_tip"`
57 Reason string `json:"reason"`
58}
59
60// leftOn is the record of leaving the inputs alone, or nil.
61func (e *Entry) leftOn(in Inputs) *Left {
62 if e == nil {
63 return nil
64 }
65 for _, x := range e.LeftAlone {
66 if (Inputs{Head: x.Head, TargetTip: x.TargetTip}) == in {
67 return x
68 }
69 }
70 return nil
71}
72
73// MaxActions is how many actions the ledger keeps for one change, its
74// latest: the inputs of older ones may be acted on again. With an entry
75// only for each change klaus acted on that hasn't landed or been
76// withdrawn, that bounds the ledger.
77const MaxActions = 16
78
79// Inputs are what a resolution run is dispatched on: the change's head and
80// the target's tip. The repo and change are the entry's.
81type Inputs struct {
82 Head string `json:"head"`
83 TargetTip string `json:"target_tip"`
84}
85
86// Last is the latest action, or nil for none.
87func (e *Entry) Last() *Action {
88 if e == nil || len(e.Actions) == 0 {
89 return nil
90 }
91 return e.Actions[len(e.Actions)-1]
92}
93
94// ActionOn is the action on the inputs, or nil when klaus didn't act on
95// them, or no longer remembers it did.
96func (e *Entry) ActionOn(in Inputs) *Action {
97 if e == nil {
98 return nil
99 }
100 for _, a := range e.Actions {
101 if a.inputs() == in {
102 return a
103 }
104 }
105 return nil
106}
107
108// Pending is the action whose launch klaus can't yet settle, or nil.
109func (e *Entry) Pending() *Action {
110 if e == nil {
111 return nil
112 }
113 for _, a := range e.Actions {
114 if a.Pending {
115 return a
116 }
117 }
118 return nil
119}
120
121// record adds an action on inputs klaus hasn't acted on, dropping the
122// oldest settled ones past MaxActions.
123func (e *Entry) record(a *Action) {
124 e.Actions = append(e.Actions, a)
125 for i := 0; len(e.Actions) > MaxActions && i < len(e.Actions); {
126 if e.Actions[i].Pending {
127 i++
128 continue
129 }
130 e.Actions = append(e.Actions[:i:i], e.Actions[i+1:]...)
131 }
132}
133
134// migrate moves what a ledger written before Actions holds into Actions:
135// each set of inputs it consumed, oldest first, and its last action, with
136// what came of it. Of the others it knows only that klaus acted on them.
137func (e *Entry) migrate() {
138 if e.OldLast == nil && len(e.OldConsumed) == 0 {
139 return
140 }
141 var old []*Action
142 for _, in := range e.OldConsumed {
143 if e.ActionOn(in) == nil && (e.OldLast == nil || e.OldLast.inputs() != in) {
144 old = append(old, &Action{Head: in.Head, TargetTip: in.TargetTip, Refused: "flow acted on these inputs before it kept what came of it"})
145 }
146 }
147 if e.OldLast != nil && e.ActionOn(e.OldLast.inputs()) == nil {
148 old = append(old, e.OldLast)
149 }
150 actions := e.Actions
151 e.Actions, e.OldLast, e.OldConsumed = nil, nil, nil
152 for _, a := range append(old, actions...) {
153 e.record(a)
154 }
155}
156
157// Action is what klaus did about one conflict: the report and the inputs it
158// acted on, and the run it launched or why it launched none.
159type Action struct {
160 At time.Time `json:"at"`
161 Report string `json:"report"`
162 Version int `json:"version,omitempty"`
163 Head string `json:"head"`
164 TargetTip string `json:"target_tip"`
165 // RunID is the run klaus launched, or may have: klaus names the run
166 // before it launches it. "" once it knows no worker started.
167 RunID string `json:"run_id,omitempty"`
168 // Pending is set from before klaus launches RunID until it knows
169 // whether the run started: its run is recorded, or klaus proved no
170 // worker of it runs (Deps.WorkerGone). A pass that finds it set finds
171 // the launch in flight, one that failed leaving klaus unsure, or the
172 // pass that started it gone before it could tell (reconcile).
173 Pending bool `json:"pending,omitempty"`
174 // Refused says why no run, or no run klaus can vouch for, came of it;
175 // on a pending launch, why klaus can't yet settle it.
176 Refused string `json:"refused,omitempty"`
177}
178
179func (a *Action) inputs() Inputs { return Inputs{Head: a.Head, TargetTip: a.TargetTip} }
180
181// Ledger is the session's record of resolution runs, by change. It outlives
182// the dashboard, so cooldowns and attempt counts survive a restart, and a
183// pass run by hand sees what the dashboard's did. It is bounded: a pass
184// drops a change's entry once the change lands or is withdrawn (prune),
185// and an entry keeps MaxActions actions.
186type Ledger struct {
187 path string // "" keeps it in memory
188 entries map[string]*Entry
189}
190
191// NewLedger returns an empty ledger kept in memory.
192func NewLedger() *Ledger { return &Ledger{entries: make(map[string]*Entry)} }
193
194// LoadLedger reads the ledger in a session directory, moving what an older
195// klaus wrote into the entries' Actions; a missing file is an empty
196// ledger.
197func LoadLedger(dir string) (*Ledger, error) {
198 l := &Ledger{path: filepath.Join(dir, LedgerFile), entries: make(map[string]*Entry)}
199 data, err := os.ReadFile(l.path)
200 if errors.Is(err, os.ErrNotExist) {
201 return l, nil
202 }
203 if err != nil {
204 return l, err
205 }
206 if err := json.Unmarshal(data, &l.entries); err != nil {
207 return l, fmt.Errorf("parsing %s: %w", l.path, err)
208 }
209 for _, e := range l.entries {
210 e.migrate()
211 }
212 return l, nil
213}
214
215// Lock takes an exclusive lock on a session directory's ledger, held by
216// one pass at a time across processes, so the dashboard and a pass run by
217// hand never both dispatch for a conflict.
218func Lock(dir string) (unlock func(), err error) {
219 f, err := os.OpenFile(filepath.Join(dir, LedgerFile+".lock"), os.O_CREATE|os.O_RDWR, 0o644)
220 if err != nil {
221 return nil, err
222 }
223 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
224 f.Close()
225 return nil, fmt.Errorf("locking %s: %w", f.Name(), err)
226 }
227 return func() {
228 syscall.Flock(int(f.Fd()), syscall.LOCK_UN) //nolint:errcheck
229 f.Close()
230 }, nil
231}
232
233// Entry returns the entry of a change, or nil for none.
234func (l *Ledger) Entry(k Key) *Entry { return l.entries[k.String()] }
235
236// sorted returns the entries in key order.
237func (l *Ledger) sorted() []*Entry {
238 keys := make([]string, 0, len(l.entries))
239 for k := range l.entries {
240 keys = append(keys, k)
241 }
242 sort.Strings(keys)
243 out := make([]*Entry, len(keys))
244 for i, k := range keys {
245 out[i] = l.entries[k]
246 }
247 return out
248}
249
250// drop removes a change's entry.
251func (l *Ledger) drop(k Key) { delete(l.entries, k.String()) }
252
253// put stores an entry.
254func (l *Ledger) put(e *Entry) {
255 l.entries[Key{Repo: e.Repo, ChangeID: e.ChangeID}.String()] = e
256}
257
258// save writes the ledger through a temporary file, so a crash mid-write
259// leaves the previous one in place.
260func (l *Ledger) save() error {
261 if l.path == "" {
262 return nil
263 }
264 data, err := json.MarshalIndent(l.entries, "", " ")
265 if err != nil {
266 return err
267 }
268 f, err := os.CreateTemp(filepath.Dir(l.path), ".restack-dispatches-*")
269 if err != nil {
270 return err
271 }
272 defer os.Remove(f.Name())
273 if _, err := f.Write(append(data, '\n')); err != nil {
274 f.Close()
275 return err
276 }
277 if err := f.Close(); err != nil {
278 return err
279 }
280 return os.Rename(f.Name(), l.path)
281}
282
283// actionOnReport is the latest action on a report, at a head, or nil.
284func (e *Entry) actionOnReport(report, head string) *Action {
285 for i := len(e.Actions) - 1; i >= 0; i-- {
286 if a := e.Actions[i]; a.Report == report && a.Head == head {
287 return a
288 }
289 }
290 return nil
291}