|
| 1 | +// Package tracking provides persistent gain tracking for tok |
| 2 | +// compression calls via a local SQLite database. |
| 3 | +// |
| 4 | +// Each compression event is recorded with timestamp, command name, |
| 5 | +// original/compressed byte and token counts, savings percentage, |
| 6 | +// mode, and model. The tracker exposes aggregate queries for |
| 7 | +// dashboards and budget enforcement. |
| 8 | +// |
| 9 | +// Storage defaults to ~/.tok/tracker.db with WAL mode and a 90-day |
| 10 | +// retention policy (configurable per Tracker instance). |
| 11 | +// |
| 12 | +// Source: rtk-ai/rtk, src/core/tracking.rs. Ported to native Go |
| 13 | +// using modernc.org/sqlite (pure Go, no CGO). |
| 14 | +package tracking |
| 15 | + |
| 16 | +import ( |
| 17 | + "context" |
| 18 | + "database/sql" |
| 19 | + "errors" |
| 20 | + "fmt" |
| 21 | + "path/filepath" |
| 22 | + "sync" |
| 23 | + "time" |
| 24 | + |
| 25 | + _ "modernc.org/sqlite" // pure-Go SQLite driver |
| 26 | +) |
| 27 | + |
| 28 | +// Event is a single compression event recorded by the tracker. |
| 29 | +type Event struct { |
| 30 | + ID int64 |
| 31 | + Timestamp time.Time |
| 32 | + Command string |
| 33 | + OriginalBytes int |
| 34 | + CompressedBytes int |
| 35 | + OriginalTokens int |
| 36 | + CompressedTokens int |
| 37 | + Mode string |
| 38 | + Tier string |
| 39 | + Model string |
| 40 | + // Computed in DB query; not stored. |
| 41 | + SavingsPct float64 |
| 42 | +} |
| 43 | + |
| 44 | +// Tracker is the public type. Construct with New() or NewAt(path). |
| 45 | +type Tracker struct { |
| 46 | + db *sql.DB |
| 47 | + mu sync.Mutex |
| 48 | + retenDays int |
| 49 | + closed bool |
| 50 | +} |
| 51 | + |
| 52 | +// DefaultPath returns the default tracker DB path (~/.tok/tracker.db). |
| 53 | +// Returns the path and a non-nil error only if the home directory |
| 54 | +// cannot be determined. |
| 55 | +func DefaultPath() (string, error) { |
| 56 | + dir, err := homeDir() |
| 57 | + if err != nil { |
| 58 | + return "", err |
| 59 | + } |
| 60 | + return filepath.Join(dir, ".tok", "tracker.db"), nil |
| 61 | +} |
| 62 | + |
| 63 | +// New creates a tracker at the default path. |
| 64 | +func New(ctx context.Context) (*Tracker, error) { |
| 65 | + p, err := DefaultPath() |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + return NewAt(ctx, p) |
| 70 | +} |
| 71 | + |
| 72 | +// NewAt creates a tracker at the given path. The parent directory |
| 73 | +// is created if it does not exist. WAL journal mode is enabled and |
| 74 | +// the schema is created on first call. |
| 75 | +func NewAt(ctx context.Context, path string) (*Tracker, error) { |
| 76 | + if path == "" { |
| 77 | + return nil, errors.New("tracking: empty path") |
| 78 | + } |
| 79 | + if err := mkdirAll(filepath.Dir(path), 0o700); err != nil { |
| 80 | + return nil, fmt.Errorf("tracking: create dir: %w", err) |
| 81 | + } |
| 82 | + db, err := sql.Open("sqlite", path) |
| 83 | + if err != nil { |
| 84 | + return nil, fmt.Errorf("tracking: open db: %w", err) |
| 85 | + } |
| 86 | + // SQLite is single-writer; use a per-connection mutex to serialize |
| 87 | + // writes without serializing reads. |
| 88 | + db.SetMaxOpenConns(1) |
| 89 | + t := &Tracker{db: db, retenDays: 90} |
| 90 | + if err := t.initSchema(ctx); err != nil { |
| 91 | + _ = db.Close() |
| 92 | + return nil, err |
| 93 | + } |
| 94 | + if err := t.enableWAL(ctx); err != nil { |
| 95 | + _ = db.Close() |
| 96 | + return nil, err |
| 97 | + } |
| 98 | + return t, nil |
| 99 | +} |
| 100 | + |
| 101 | +// WithRetention overrides the default 90-day retention period. |
| 102 | +// Must be called before any Record or Aggregate call. |
| 103 | +func (t *Tracker) WithRetention(days int) *Tracker { |
| 104 | + if days > 0 { |
| 105 | + t.retenDays = days |
| 106 | + } |
| 107 | + return t |
| 108 | +} |
| 109 | + |
| 110 | +// initSchema creates the events table if it doesn't exist. Safe to |
| 111 | +// call multiple times. |
| 112 | +func (t *Tracker) initSchema(ctx context.Context) error { |
| 113 | + _, err := t.db.ExecContext(ctx, ` |
| 114 | + CREATE TABLE IF NOT EXISTS events ( |
| 115 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 116 | + ts INTEGER NOT NULL, |
| 117 | + command TEXT NOT NULL DEFAULT '', |
| 118 | + original_bytes INTEGER NOT NULL, |
| 119 | + compressed_bytes INTEGER NOT NULL, |
| 120 | + original_tokens INTEGER NOT NULL, |
| 121 | + compressed_tokens INTEGER NOT NULL, |
| 122 | + mode TEXT NOT NULL DEFAULT '', |
| 123 | + tier TEXT NOT NULL DEFAULT '', |
| 124 | + model TEXT NOT NULL DEFAULT '' |
| 125 | + ); |
| 126 | + CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts); |
| 127 | + CREATE INDEX IF NOT EXISTS idx_events_command ON events(command); |
| 128 | + `) |
| 129 | + if err != nil { |
| 130 | + return fmt.Errorf("tracking: init schema: %w", err) |
| 131 | + } |
| 132 | + return nil |
| 133 | +} |
| 134 | + |
| 135 | +// enableWAL switches the journal mode to WAL for better concurrent |
| 136 | +// read performance. |
| 137 | +func (t *Tracker) enableWAL(ctx context.Context) error { |
| 138 | + _, err := t.db.ExecContext(ctx, `PRAGMA journal_mode=WAL;`) |
| 139 | + if err != nil { |
| 140 | + return fmt.Errorf("tracking: enable WAL: %w", err) |
| 141 | + } |
| 142 | + return nil |
| 143 | +} |
| 144 | + |
| 145 | +// Record adds a new compression event. The ID and SavingsPct fields |
| 146 | +// of ev are ignored; SavingsPct is computed from byte counts. |
| 147 | +func (t *Tracker) Record(ctx context.Context, ev Event) error { |
| 148 | + if t == nil || t.db == nil { |
| 149 | + return errors.New("tracking: nil tracker") |
| 150 | + } |
| 151 | + t.mu.Lock() |
| 152 | + defer t.mu.Unlock() |
| 153 | + if ev.Timestamp.IsZero() { |
| 154 | + ev.Timestamp = time.Now() |
| 155 | + } |
| 156 | + _, err := t.db.ExecContext(ctx, ` |
| 157 | + INSERT INTO events |
| 158 | + (ts, command, original_bytes, compressed_bytes, |
| 159 | + original_tokens, compressed_tokens, mode, tier, model) |
| 160 | + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 161 | + `, |
| 162 | + ev.Timestamp.Unix(), ev.Command, |
| 163 | + ev.OriginalBytes, ev.CompressedBytes, |
| 164 | + ev.OriginalTokens, ev.CompressedTokens, |
| 165 | + ev.Mode, ev.Tier, ev.Model, |
| 166 | + ) |
| 167 | + if err != nil { |
| 168 | + return fmt.Errorf("tracking: record: %w", err) |
| 169 | + } |
| 170 | + return nil |
| 171 | +} |
| 172 | + |
| 173 | +// Aggregate is the result of a Tracker.Aggregate call. |
| 174 | +type Aggregate struct { |
| 175 | + EventCount int |
| 176 | + TotalBytesSaved int |
| 177 | + AvgSavingsPct float64 |
| 178 | + PeriodStart time.Time |
| 179 | + PeriodEnd time.Time |
| 180 | +} |
| 181 | + |
| 182 | +// Aggregate returns aggregate stats over the last `days` days (or |
| 183 | +// the configured retention period if days is 0). Empty result if no |
| 184 | +// events in the window. |
| 185 | +func (t *Tracker) Aggregate(ctx context.Context, days int) (Aggregate, error) { |
| 186 | + if t == nil || t.db == nil { |
| 187 | + return Aggregate{}, errors.New("tracking: nil tracker") |
| 188 | + } |
| 189 | + if days <= 0 { |
| 190 | + days = t.retenDays |
| 191 | + } |
| 192 | + if days <= 0 { |
| 193 | + days = 90 |
| 194 | + } |
| 195 | + since := time.Now().Add(-time.Duration(days) * 24 * time.Hour).Unix() |
| 196 | + |
| 197 | + var agg Aggregate |
| 198 | + row := t.db.QueryRowContext(ctx, ` |
| 199 | + SELECT |
| 200 | + COUNT(*), |
| 201 | + COALESCE(SUM(original_bytes - compressed_bytes), 0), |
| 202 | + COALESCE(AVG( |
| 203 | + CASE WHEN original_bytes = 0 THEN 0 |
| 204 | + ELSE 100.0 * (original_bytes - compressed_bytes) / original_bytes |
| 205 | + END |
| 206 | + ), 0) |
| 207 | + FROM events |
| 208 | + WHERE ts >= ? |
| 209 | + `, since) |
| 210 | + if err := row.Scan(&agg.EventCount, &agg.TotalBytesSaved, &agg.AvgSavingsPct); err != nil { |
| 211 | + return agg, fmt.Errorf("tracking: aggregate: %w", err) |
| 212 | + } |
| 213 | + agg.PeriodStart = time.Unix(since, 0) |
| 214 | + agg.PeriodEnd = time.Now() |
| 215 | + return agg, nil |
| 216 | +} |
| 217 | + |
| 218 | +// Recent returns the most recent n events, newest first. |
| 219 | +func (t *Tracker) Recent(ctx context.Context, n int) ([]Event, error) { |
| 220 | + if t == nil || t.db == nil { |
| 221 | + return nil, errors.New("tracking: nil tracker") |
| 222 | + } |
| 223 | + if n <= 0 { |
| 224 | + n = 10 |
| 225 | + } |
| 226 | + rows, err := t.db.QueryContext(ctx, ` |
| 227 | + SELECT |
| 228 | + id, ts, command, |
| 229 | + original_bytes, compressed_bytes, |
| 230 | + original_tokens, compressed_tokens, |
| 231 | + mode, tier, model |
| 232 | + FROM events |
| 233 | + ORDER BY id DESC |
| 234 | + LIMIT ? |
| 235 | + `, n) |
| 236 | + if err != nil { |
| 237 | + return nil, fmt.Errorf("tracking: recent: %w", err) |
| 238 | + } |
| 239 | + defer rows.Close() |
| 240 | + var out []Event |
| 241 | + for rows.Next() { |
| 242 | + var ev Event |
| 243 | + var ts int64 |
| 244 | + if err := rows.Scan(&ev.ID, &ts, &ev.Command, |
| 245 | + &ev.OriginalBytes, &ev.CompressedBytes, |
| 246 | + &ev.OriginalTokens, &ev.CompressedTokens, |
| 247 | + &ev.Mode, &ev.Tier, &ev.Model); err != nil { |
| 248 | + return nil, err |
| 249 | + } |
| 250 | + ev.Timestamp = time.Unix(ts, 0) |
| 251 | + if ev.OriginalBytes > 0 { |
| 252 | + ev.SavingsPct = 100.0 * float64(ev.OriginalBytes-ev.CompressedBytes) / float64(ev.OriginalBytes) |
| 253 | + } |
| 254 | + out = append(out, ev) |
| 255 | + } |
| 256 | + return out, rows.Err() |
| 257 | +} |
| 258 | + |
| 259 | +// Prune deletes events older than the configured retention period. |
| 260 | +// Returns the number of rows deleted. |
| 261 | +func (t *Tracker) Prune(ctx context.Context) (int64, error) { |
| 262 | + if t == nil || t.db == nil { |
| 263 | + return 0, errors.New("tracking: nil tracker") |
| 264 | + } |
| 265 | + cutoff := time.Now().Add(-time.Duration(t.retenDays) * 24 * time.Hour).Unix() |
| 266 | + res, err := t.db.ExecContext(ctx, `DELETE FROM events WHERE ts < ?`, cutoff) |
| 267 | + if err != nil { |
| 268 | + return 0, fmt.Errorf("tracking: prune: %w", err) |
| 269 | + } |
| 270 | + return res.RowsAffected() |
| 271 | +} |
| 272 | + |
| 273 | +// Close closes the underlying DB. Safe to call multiple times. |
| 274 | +func (t *Tracker) Close() error { |
| 275 | + if t == nil || t.db == nil { |
| 276 | + return nil |
| 277 | + } |
| 278 | + t.mu.Lock() |
| 279 | + defer t.mu.Unlock() |
| 280 | + if t.closed { |
| 281 | + return nil |
| 282 | + } |
| 283 | + t.closed = true |
| 284 | + return t.db.Close() |
| 285 | +} |
0 commit comments