gunk-dev/the-valley

cleared.go

sourcecaaa5bee5e11main's published tip history
2.4 KiB
1package run
2
3import (
4 "bufio"
5 "encoding/json"
6 "errors"
7 "os"
8 "path/filepath"
9 "time"
10)
11
12// clearedFile is the session's ledger of the runs cleanup removed, one JSON
13// line per run, so the session's spend outlasts their state files.
14const clearedFile = "cleared.jsonl"
15
16type clearedEntry struct {
17 ID string `json:"id"`
18 CostUSD *float64 `json:"cost_usd,omitempty"`
19 DurationMS *int64 `json:"duration_ms,omitempty"`
20 CreatedAt string `json:"created_at,omitempty"`
21}
22
23// Cleared sums the runs cleanup removed from a session.
24type Cleared struct {
25 Runs int
26 CostUSD float64
27 DurationMS int64
28 // FirstCreated is when the earliest of them was created; zero when none
29 // recorded it.
30 FirstCreated time.Time
31 // IDs names them; nil when there are none.
32 IDs map[string]bool
33}
34
35// RecordCleared appends s's cost and duration to the ledger in the session
36// directory dir. Each line is one append, so concurrent cleanups don't
37// interleave; a run recorded twice counts once.
38func RecordCleared(dir string, s *State) error {
39 line, err := json.Marshal(clearedEntry{ID: s.ID, CostUSD: s.CostUSD, DurationMS: s.DurationMS, CreatedAt: s.CreatedAt})
40 if err != nil {
41 return err
42 }
43 f, err := os.OpenFile(filepath.Join(dir, clearedFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
44 if err != nil {
45 return err
46 }
47 if _, err := f.Write(append(line, '\n')); err != nil {
48 f.Close()
49 return err
50 }
51 return f.Close()
52}
53
54// ReadCleared sums the ledger in the session directory dir, leaving out the
55// runs in live, whose state cleanup recorded but failed to remove; zero when
56// there is no ledger.
57func ReadCleared(dir string, live []*State) (Cleared, error) {
58 var c Cleared
59 f, err := os.Open(filepath.Join(dir, clearedFile))
60 if errors.Is(err, os.ErrNotExist) {
61 return c, nil
62 }
63 if err != nil {
64 return c, err
65 }
66 defer f.Close()
67 seen := make(map[string]bool)
68 for _, s := range live {
69 seen[s.ID] = true
70 }
71 sc := bufio.NewScanner(f)
72 for sc.Scan() {
73 var e clearedEntry
74 if json.Unmarshal(sc.Bytes(), &e) != nil || seen[e.ID] {
75 continue
76 }
77 seen[e.ID] = true
78 if c.IDs == nil {
79 c.IDs = make(map[string]bool)
80 }
81 c.IDs[e.ID] = true
82 c.Runs++
83 if e.CostUSD != nil {
84 c.CostUSD += *e.CostUSD
85 }
86 if e.DurationMS != nil {
87 c.DurationMS += *e.DurationMS
88 }
89 if t, err := time.Parse(time.RFC3339, e.CreatedAt); err == nil && (c.FirstCreated.IsZero() || t.Before(c.FirstCreated)) {
90 c.FirstCreated = t
91 }
92 }
93 return c, sc.Err()
94}