today, 7d and 30d begin at a local midnight, so a caller wanting "the
last few hours" just after midnight had to take 7d's CSV, seven days of
rows for one. `magpie usage [--csv [--account <name>]] --last 24h` (any
Go duration, 90m) or `--days 1.5` now reads a window that began that
long ago; the presets are unchanged.
From fcy222fcy's branch (usage-rolling-window, 60472c661): a rolling
window is a period "last:<dur>" (usage.LastOf / Period.Last) that Since,
Known, shown and the chart's timeline answer for, so the ledger, Direct
and the summary read the same window.
Review fixes on top:
- a summary of a rolling window is worked out each time, like a picked
range: kept, its start didn't move with the clock while the log
stayed the same (reachable through the web API's ?period=last:24h);
- the CSV export's file name has no colon from "last:24h0m0s", which
Windows refuses;
- `--last 24h 7d` is refused rather than silently taking --last;
- --days refuses NaN, Inf and over a century;
- the help line and docs/reference.md name the flags.
Run: new TestRollingWindowIsNotKeptStale fails with the cache fix taken
out ("an hour later: 1 calls, want 0"); TestCSVStamp fails without the
colon fix ("magpie-requests-last:24h0m0s-2026-09-30");
TestUsageRollingWindowRejectsJunk fails without the preset/--days
checks; TestUsageRollingWindow and the new ...WithAccount fail (3 rows,
want 2) with Since moved back. go test -tags nogui ./internal/usage/...
./internal/cli/... ./internal/usageapi/... ./internal/gui/... in a
sandbox HOME: ok. gofmt -l clean; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows; go build darwin, linux nogui, windows.
Real use: the built binary on a sandbox HOME with a generated 50,000-call
7-day usage.jsonl: --csv 7d 47,233 rows / 6.97 MB; today 4,376; --last
24h 7,140 / 1.05 MB; --last 90m 444; --days 1.5 10,712; --account me@x
--last 24h 3,570 (that account's half); oldest row of each at the
window's start.
Not tried: the full go test ./... suite; the process still parses the
whole usage.jsonl into its in-memory index on each run (as every period
does), so the cut is in rows decoded and written, not bytes read.
Co-authored-by: fchengyan <3181088318@qq.com>
120 lines
4.2 KiB
Go
120 lines
4.2 KiB
Go
package usage
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"fmt"
|
|
"slices"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
const summaryCacheSessions = 1024
|
|
|
|
type summaryEntry struct {
|
|
version uint64
|
|
meta string
|
|
// value keeps the top summaryCacheSessions sessions only, of its
|
|
// SessionCount
|
|
value Summary
|
|
}
|
|
|
|
var summaries struct {
|
|
sync.Mutex
|
|
entries map[Period]summaryEntry
|
|
worked int // how many summaries were worked out, for the tests
|
|
}
|
|
|
|
func indexedSummary(p Period, now time.Time) Summary { return topSummary(p, now, -1) }
|
|
|
|
// SummarizeTop is Summarize with only the top n sessions by tokens (all of
|
|
// them for n < 0); SessionCount says how many the period has. It is what a page that
|
|
// shows a few of them or none asks for: a summary of more than
|
|
// summaryCacheSessions sessions is kept with those only, and Summarize, which
|
|
// gives every one, works it out again each time. Over a long history
|
|
// (Vantiboo1ean, ~750k requests in ~84k sessions) that was every refresh of
|
|
// the Usage page and the TUI, and the page was sent all 84k.
|
|
func SummarizeTop(p Period, n int) Summary { return topSummary(p, Clock(), n) }
|
|
|
|
func topSummary(p Period, now time.Time, n int) Summary {
|
|
p = p.shown()
|
|
snapshot := readLogSnapshot()
|
|
work := func() Summary {
|
|
summaries.Lock()
|
|
summaries.worked++
|
|
summaries.Unlock()
|
|
return summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) })
|
|
}
|
|
if p.IsRange() || p.Last() > 0 {
|
|
// a picked range is read afresh each time, so ranges never pile up
|
|
// in the cache (#1492), and so is a rolling window, whose start
|
|
// moves with the clock though the log hasn't changed (#2075)
|
|
return topOf(work(), n)
|
|
}
|
|
meta := usagePriceCacheKey(now)
|
|
summaries.Lock()
|
|
old, ok := summaries.entries[p]
|
|
summaries.Unlock()
|
|
if ok && old.version == snapshot.version && old.meta == meta && (n >= 0 && n <= len(old.value.Sessions) || old.value.SessionCount == len(old.value.Sessions)) {
|
|
return topOf(cloneSummary(old.value), n)
|
|
}
|
|
value := work()
|
|
// the cache keeps a copy with the top sessions only; the answer has as
|
|
// many as asked
|
|
kept := value
|
|
kept.Sessions = kept.Sessions[:min(len(kept.Sessions), summaryCacheSessions)]
|
|
kept = cloneSummary(kept)
|
|
summaries.Lock()
|
|
if summaries.entries == nil {
|
|
summaries.entries = map[Period]summaryEntry{}
|
|
}
|
|
if previous := summaries.entries[p]; previous.version <= snapshot.version {
|
|
summaries.entries[p] = summaryEntry{snapshot.version, meta, kept}
|
|
}
|
|
summaries.Unlock()
|
|
return topOf(value, n)
|
|
}
|
|
|
|
// topOf is s with its top n sessions (all for n < 0).
|
|
func topOf(s Summary, n int) Summary {
|
|
if n >= 0 && len(s.Sessions) > n {
|
|
s.Sessions = s.Sessions[:n:n]
|
|
}
|
|
return s
|
|
}
|
|
|
|
// The exported result remains owned by its caller.
|
|
func cloneSummary(s Summary) Summary {
|
|
s.Series = slices.Clone(s.Series)
|
|
s.Agents = slices.Clone(s.Agents)
|
|
s.Models = slices.Clone(s.Models)
|
|
s.ProviderKeys = slices.Clone(s.ProviderKeys)
|
|
s.Accounts = slices.Clone(s.Accounts)
|
|
s.CallerKeys = slices.Clone(s.CallerKeys)
|
|
s.Sessions = slices.Clone(s.Sessions)
|
|
return s
|
|
}
|
|
|
|
// usagePriceCacheKey invalidates priced views when local prices or provider feeds change.
|
|
func usagePriceCacheKey(now time.Time) string {
|
|
_, offset := now.Zone()
|
|
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path()), statKey(catalog.CachePath()), statKey(catalog.LivePath("antigravity")), now.Format("2006-01-02"), now.Location(), offset)
|
|
// Sign-ins and plugin lists can change independently of providers.json.
|
|
// Their identity and price feeds affect both grouping and historical costs.
|
|
h := sha256.New()
|
|
prices, _ := json.Marshal(settings.Load().ModelPrices)
|
|
aliases, _ := json.Marshal(provider.Renamed())
|
|
fmt.Fprint(h, string(prices), string(aliases))
|
|
for _, current := range provider.All() {
|
|
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
|
|
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
|
|
}
|
|
meta += fmt.Sprintf("|%x", h.Sum(nil))
|
|
// and the clients the user counts as agents (#1958)
|
|
return meta + "|" + clientAgentsKey()
|
|
}
|