gunk-dev/the-valley

cleared.go

sourcecfedff357a41main's published tip history
2.3 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}
32
33// RecordCleared appends s's cost and duration to the ledger in the session
34// directory dir. Each line is one append, so concurrent cleanups don't
35// interleave; a run recorded twice counts once.
36func RecordCleared(dir string, s *State) error {
37 line, err := json.Marshal(clearedEntry{ID: s.ID, CostUSD: s.CostUSD, DurationMS: s.DurationMS, CreatedAt: s.CreatedAt})
38 if err != nil {
39 return err
40 }
41 f, err := os.OpenFile(filepath.Join(dir, clearedFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
42 if err != nil {
43 return err
44 }
45 if _, err := f.Write(append(line, '\n')); err != nil {
46 f.Close()
47 return err
48 }
49 return f.Close()
50}
51
52// ReadCleared sums the ledger in the session directory dir, leaving out the
53// runs in live, whose state cleanup recorded but failed to remove; zero when
54// there is no ledger.
55func ReadCleared(dir string, live []*State) (Cleared, error) {
56 var c Cleared
57 f, err := os.Open(filepath.Join(dir, clearedFile))
58 if errors.Is(err, os.ErrNotExist) {
59 return c, nil
60 }
61 if err != nil {
62 return c, err
63 }
64 defer f.Close()
65 seen := make(map[string]bool)
66 for _, s := range live {
67 seen[s.ID] = true
68 }
69 sc := bufio.NewScanner(f)
70 for sc.Scan() {
71 var e clearedEntry
72 if json.Unmarshal(sc.Bytes(), &e) != nil || seen[e.ID] {
73 continue
74 }
75 seen[e.ID] = true
76 c.Runs++
77 if e.CostUSD != nil {
78 c.CostUSD += *e.CostUSD
79 }
80 if e.DurationMS != nil {
81 c.DurationMS += *e.DurationMS
82 }
83 if t, err := time.Parse(time.RFC3339, e.CreatedAt); err == nil && (c.FirstCreated.IsZero() || t.Before(c.FirstCreated)) {
84 c.FirstCreated = t
85 }
86 }
87 return c, sc.Err()
88}