summaryrefslogtreecommitdiff
path: root/internal/stats/stats.go
blob: d79025a45c31e19e68934092bea71a415217f9c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Package stats provides a simple, process-safe, on-disk cache of Hexai LLM usage
// statistics shared across all binaries. It appends compact events (ts, provider,
// model, sent, recv) to a JSON file guarded by an advisory file lock, prunes
// entries older than the configured window (default 1h), and computes aggregated
// snapshots for display in logs and tmux status.
package stats

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync/atomic"
	"time"
)

const (
	fileName      = "stats.json"
	lockFileName  = "stats.lock"
	fileVersion   = 1
	defaultWindow = time.Hour
)

var windowSeconds int64 = int64(defaultWindow.Seconds())

var errLockWouldBlock = errors.New("stats: lock would block")

// SetWindow sets the sliding window used for pruning and aggregation.
func SetWindow(d time.Duration) {
	if d < time.Second {
		d = time.Second
	}
	if d > 24*time.Hour {
		d = 24 * time.Hour
	}
	atomic.StoreInt64(&windowSeconds, int64(d.Seconds()))
}

// Window returns the current sliding window.
func Window() time.Duration { return time.Duration(atomic.LoadInt64(&windowSeconds)) * time.Second }

// Event represents a single request/response with sizes.
type Event struct {
	TS       time.Time `json:"ts"`
	Provider string    `json:"provider"`
	Model    string    `json:"model"`
	Sent     int64     `json:"sent"`
	Recv     int64     `json:"recv"`
}

// File is the on-disk JSON structure.
type File struct {
	Version       int       `json:"version"`
	UpdatedAt     time.Time `json:"updated_at"`
	WindowSeconds int       `json:"window_seconds"`
	Events        []Event   `json:"events"`
}

// Counters and Snapshot represent computed aggregates for the current window.
type Counters struct{ Reqs, Sent, Recv int64 }

type ProviderEntry struct {
	Totals Counters
	Models map[string]Counters
}

type Snapshot struct {
	Global    Counters
	Providers map[string]ProviderEntry
	RPM       float64
	Window    time.Duration
}

// ScopeReqs returns the request count for a specific provider+model pair.
// Returns 0 when the provider or model is not present in the snapshot.
func (s Snapshot) ScopeReqs(provider, model string) int64 {
	if pe, ok := s.Providers[provider]; ok {
		if mc, ok2 := pe.Models[model]; ok2 {
			return mc.Reqs
		}
	}
	return 0
}

// ScopeRPM returns the requests-per-minute for a specific provider+model
// pair, derived from ScopeReqs and the snapshot's sliding window.
func (s Snapshot) ScopeRPM(provider, model string) float64 {
	reqs := s.ScopeReqs(provider, model)
	if reqs == 0 {
		return 0
	}
	mins := s.Window.Minutes()
	if mins <= 0 {
		mins = 0.001
	}
	return float64(reqs) / mins
}

// Update appends one event and prunes old entries under lock.
func Update(ctx context.Context, provider, model string, sentBytes, recvBytes int) error {
	dir, err := CacheDir()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return err
	}
	unlock, err := lockStatsFile(ctx, dir)
	if err != nil {
		return err
	}
	defer func() { _ = unlock() }()

	path := filepath.Join(dir, fileName)
	sf := readStatsFile(path)
	now := time.Now()
	win := Window()
	sf.WindowSeconds = int(win.Seconds())
	sf.Events = append(sf.Events, Event{
		TS: now, Provider: provider, Model: model,
		Sent: int64(sentBytes), Recv: int64(recvBytes),
	})
	pruneOldEvents(&sf, now.Add(-win))
	sf.UpdatedAt = now
	return writeStatsFileAtomic(dir, path, &sf)
}

// lockStatsFile acquires an advisory file lock on the stats lock file within dir.
// Returns an unlock function on success.
func lockStatsFile(ctx context.Context, dir string) (func() error, error) {
	lockPath := filepath.Join(dir, lockFileName)
	f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
	if err != nil {
		return nil, err
	}
	unlock, err := acquireFileLock(ctx, f)
	if err != nil {
		_ = f.Close()
		return nil, err
	}
	// Return a combined unlock+close function so the caller only needs one defer.
	return func() error {
		uErr := unlock()
		cErr := f.Close()
		if uErr != nil {
			return uErr
		}
		return cErr
	}, nil
}

// readStatsFile loads the on-disk stats file, returning a fresh File if it is
// missing, corrupt, or has an incompatible version.
func readStatsFile(path string) File {
	var sf File
	if b, err := os.ReadFile(path); err == nil {
		if uerr := json.Unmarshal(b, &sf); uerr != nil {
			fmt.Fprintf(os.Stderr, "stats: corrupt stats file %s: %v, starting fresh\n", path, uerr)
			return File{Version: fileVersion}
		}
	}
	if sf.Version != fileVersion {
		sf = File{Version: fileVersion}
	}
	return sf
}

// pruneOldEvents removes events older than cutoff in-place.
func pruneOldEvents(sf *File, cutoff time.Time) {
	i := 0
	for ; i < len(sf.Events); i++ {
		if !sf.Events[i].TS.Before(cutoff) {
			break
		}
	}
	if i > 0 {
		sf.Events = append([]Event(nil), sf.Events[i:]...)
	}
}

// writeStatsFileAtomic writes sf to path via a temp file + rename for crash safety.
func writeStatsFileAtomic(dir, path string, sf *File) error {
	tmp, err := os.CreateTemp(dir, fileName+".tmp.")
	if err != nil {
		return err
	}
	enc := json.NewEncoder(tmp)
	enc.SetEscapeHTML(false)
	if err := enc.Encode(sf); err != nil {
		_ = tmp.Close()
		_ = os.Remove(tmp.Name())
		return err
	}
	if err := tmp.Sync(); err != nil {
		_ = tmp.Close()
		_ = os.Remove(tmp.Name())
		return err
	}
	if err := tmp.Close(); err != nil {
		_ = os.Remove(tmp.Name())
		return err
	}
	if err := os.Rename(tmp.Name(), path); err != nil {
		_ = os.Remove(tmp.Name())
		return err
	}
	return nil
}

// acquireFileLock spins on tryLockFile until it succeeds, the context is
// cancelled, or an unexpected error occurs. A single timer is reused across
// retries to avoid leaking timers/channels on every loop iteration.
func acquireFileLock(ctx context.Context, f *os.File) (func() error, error) {
	fd := f.Fd()
	retryTimer := time.NewTimer(5 * time.Millisecond)
	defer retryTimer.Stop()
	for {
		err := tryLockFile(fd)
		if err == nil {
			return func() error { return unlockFile(fd) }, nil
		}
		if errors.Is(err, errLockWouldBlock) {
			retryTimer.Reset(5 * time.Millisecond)
			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			case <-retryTimer.C:
			}
			continue
		}
		return nil, err
	}
}

// TakeSnapshot reads the stats file and aggregates events within the stored
// window (falling back to the process-level Window() if the file has none).
// This is a pure read — it does not mutate global state.
func TakeSnapshot() (Snapshot, error) {
	dir, err := CacheDir()
	if err != nil {
		return Snapshot{}, err
	}
	path := filepath.Join(dir, fileName)
	b, err := os.ReadFile(path)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return Snapshot{Providers: map[string]ProviderEntry{}, Window: Window()}, nil
		}
		return Snapshot{}, err
	}
	var sf File
	if err := json.Unmarshal(b, &sf); err != nil {
		return Snapshot{}, err
	}
	win := time.Duration(sf.WindowSeconds) * time.Second
	if win <= 0 {
		win = Window()
	}
	cutoff := time.Now().Add(-win)
	snap := Snapshot{Providers: make(map[string]ProviderEntry), Window: win}
	for _, ev := range sf.Events {
		if ev.TS.Before(cutoff) {
			continue
		}
		snap.Global.Reqs++
		snap.Global.Sent += ev.Sent
		snap.Global.Recv += ev.Recv
		pe := snap.Providers[ev.Provider]
		if pe.Models == nil {
			pe.Models = make(map[string]Counters)
		}
		pe.Totals.Reqs++
		pe.Totals.Sent += ev.Sent
		pe.Totals.Recv += ev.Recv
		mc := pe.Models[ev.Model]
		mc.Reqs++
		mc.Sent += ev.Sent
		mc.Recv += ev.Recv
		pe.Models[ev.Model] = mc
		snap.Providers[ev.Provider] = pe
	}
	mins := win.Minutes()
	if mins <= 0 {
		mins = 0.001
	}
	snap.RPM = float64(snap.Global.Reqs) / mins
	return snap, nil
}

// CacheDir resolves the cache directory for stats.
func CacheDir() (string, error) {
	if x := os.Getenv("XDG_CACHE_HOME"); strings.TrimSpace(x) != "" {
		return filepath.Join(x, "hexai"), nil
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("cannot resolve home: %w", err)
	}
	return filepath.Join(home, ".local", "hexai", "cache"), nil
}

// DebugString returns a compact single-line view of a snapshot (useful for logs).
func (s Snapshot) DebugString() string {
	return "Σ reqs=" + strconv.FormatInt(s.Global.Reqs, 10) + " rpm=" + fmt.Sprintf("%.2f", s.RPM)
}