Files
magpie/internal/usage/shared.go
T
yetone e00fbdbbc7 usage: times and days follow the viewer's time zone, not the server's (Outvi V, Discord)
Outvi V reads a remote magpie through `magpie web`. The Usage page
bucketed calls by the server's days and hours, so a call at 9:00 in
UTC+8 showed under 1:00.

What changed:
- The Usage page (plugins/usage/page.js) names its browser's IANA zone
  in ?tz= on /api/usage, /api/usage/requests, /api/usage/heatmap, the
  CSV link and the export.
- usage.Zone turns the name into one cached *time.Location per name, so
  a Filter holding it stays a comparable cache key. An empty or unknown
  name, or a zone that keeps this computer's clock, is time.Local, so
  the desktop page, the tray and the TUI see no change and share caches.
- Filter.Zone carries the zone. Today/7d/30d, the chart's hour and day
  buckets and labels, the Day filter and the heatmap's days are all
  read in it (Clock().In(zone)). The summary cache is keyed by period
  and zone, and the request-page cache by the reader's date.
- Shared days from other computers are read with a 2-day margin, not
  1, since two zones can be 26h apart.
- Limit and quota resets are unchanged. The gateway's
  /v1/magpie/usage stays on the computer's zone.

Run at e435b8867 + this change:
- gofmt -l and go vet on internal/usage, internal/usageapi and
  internal/gui: darwin, GOOS=linux -tags nogui, and GOOS=windows. The
  vet ran before the new _test files were added.
- go test ./internal/usage ./internal/usageapi and
  -tags nogui ./internal/gui: ok with TZ=UTC and with
  TZ=Asia/Shanghai.
- New tests:
  - TestUsageReadsTheViewersZone and TestZoneNames (internal/usage).
  - TestUsageRoutesReadTheViewersZone (internal/gui) asks the routes
    with ?tz= naming a zone other than the server's.
  - Each holds usage.Clock and checks the hour label, today's
    membership, the Day filter, the week chart's day label and the
    heatmap's days. With no ?tz=, the server's days are kept.

Broken by hand:
- Clock().In(zone) / Clock().In(f.loc()) back to Clock(): red in both
  zones (Summary, Requests, ledger, heatmap, /api/usage,
  /api/usage/requests, /api/usage/heatmap).
- The Day filter read in time.Local: red under TZ=UTC.
- The summary's and chart's bucketing in time.Local: the week-day label
  check goes red under TZ=UTC. Under TZ=Asia/Shanghai the chosen
  moment falls on one date in both zones, so it can't tell there.
Each was restored after.

Not tried:
- A Playwright GUI test with timezoneId in Chromium and WebKit was
  not written. The GUI suite and usage-stale-answer.test.cjs (which got
  a usageZoneQ stub) were not run: the disk was at ~350 MB free.
- TestCoreScriptBudget was not run again after the change. app.js is
  untouched, and page.js is a plugin page outside the core budget.
- A real remote `magpie web` from another zone, and the Windows box.
- Siblings left alone:
  - The Sessions tab buckets by the server's days and hours in its
    cached rollups, and its "By hour" card labels them with the
    browser's zone name.
  - The Routing history's day files are the server's days.
  These need issues of their own.
2026-10-23 10:54:27 +08:00

301 lines
8.1 KiB
Go

package usage
// Shared usage (#542): with WebDAV or S3 sync on, each computer puts the
// calls its Usage page lists on the server, a file a day, under an id of
// its own, and brings the others' down to usage-others beside usage.jsonl.
// The Usage page adds them to this computer's, each row saying which
// computer it was made on. What goes is what the ledger shows of a call —
// times, tokens, models, providers, status — never a request's content.
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/lastgood"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
// ThisComputer is the Filter.Computer of the calls made here.
const ThisComputer = "this"
// SharedDays is how many days of calls a computer keeps on the server.
const SharedDays = 90
// SharedDay is one computer's calls of one day, as it puts them on the server.
type SharedDay struct {
Computer string `json:"computer"` // its id
Name string `json:"name"` // what it is called, its host name
Day string `json:"day"` // 2006-01-02, the day where it is
Calls []SharedCall `json:"calls"`
}
// SharedCall is a call as the ledger has it: Source "log" for one read from
// an agent's session file.
type SharedCall struct {
Record
Source string `json:"source,omitempty"`
}
func dir() string { return filepath.Dir(provider.Path()) }
// OthersDir is where the other computers' days are kept: one folder each.
func OthersDir() string { return filepath.Join(dir(), "usage-others") }
// computerFile is usage-computer.json.
type computerFile struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
}
// Computer is this computer's id and name, the id made the first time and
// kept in usage-computer.json, which no backup or sync carries.
func Computer() (id, name string) {
p := filepath.Join(dir(), "usage-computer.json")
var c computerFile
if b, err := os.ReadFile(p); err == nil {
json.Unmarshal(b, &c)
}
if !validID(c.ID) {
b := make([]byte, 8)
rand.Read(b)
c.ID = hex.EncodeToString(b)
os.MkdirAll(dir(), 0o755)
// a file that doesn't parse held this computer's id, the one its
// synced days are under: it is kept aside before a new id goes
// over it, and not written over when it can't be
if j, err := json.Marshal(c); err == nil && lastgood.KeepUnparsed(p, lastgood.Into[computerFile]) == nil {
edit.WriteAtomic(p, j)
}
}
name = c.Name
if name == "" {
name, _ = os.Hostname()
name = strings.TrimSuffix(name, ".local")
}
if name == "" {
name = c.ID
}
return c.ID, name
}
func validID(id string) bool {
if len(id) < 8 || len(id) > 64 {
return false
}
for _, r := range id {
if !('0' <= r && r <= '9' || 'a' <= r && r <= 'f') {
return false
}
}
return true
}
// ValidComputer is whether id can be another computer's id: a folder name
// and a file name's first part, nothing else.
func ValidComputer(id string) bool { return validID(id) }
// OwnDays are this computer's calls since the day of since, by day, as the
// Usage page lists them: a call another magpie passed on here is left to
// that computer, which counts it itself, and where the request archive
// keeps a call is this computer's own.
func OwnDays(since time.Time) map[string][]SharedCall {
reader := LogCalls
if reader == nil {
reader = sessions.Calls
}
rows, _, _, _ := ledgerWith(since, Filter{}, gatewayRecords(since.Add(-24*time.Hour)), reader(since))
out := map[string][]SharedCall{}
for i := len(rows) - 1; i >= 0; i-- { // oldest first
r := rows[i]
if r.Via != "" {
continue
}
r.Archive, r.Computer = "", ""
if len(r.Error) > 300 {
r.Error = r.Error[:300]
}
day := r.Time.Local().Format(time.DateOnly)
out[day] = append(out[day], SharedCall{Record: r.Record, Source: r.Source})
}
return out
}
// sharedFile is where another computer's day is kept here.
func sharedFile(computer, day string) string {
return filepath.Join(OthersDir(), computer, day+".json")
}
// KeepShared keeps another computer's day here, over the one kept before.
func KeepShared(d SharedDay) error {
if !validID(d.Computer) {
return os.ErrInvalid
}
if _, err := time.Parse(time.DateOnly, d.Day); err != nil {
return err
}
b, err := json.Marshal(d)
if err != nil {
return err
}
f := sharedFile(d.Computer, d.Day)
if err := os.MkdirAll(filepath.Dir(f), 0o700); err != nil {
return err
}
if err := edit.WriteAtomic(f, b); err != nil {
return err
}
if d.Name != "" && d.Day >= latestDay(d.Computer) {
edit.WriteAtomic(nameFile(d.Computer), []byte(d.Name))
}
return os.Chmod(f, 0o600)
}
// nameFile keeps what another computer is called, as its latest day says.
func nameFile(computer string) string { return filepath.Join(OthersDir(), computer, "name") }
func latestDay(computer string) string {
days, _ := os.ReadDir(filepath.Join(OthersDir(), computer))
last := ""
for _, d := range days {
if day, ok := strings.CutSuffix(d.Name(), ".json"); ok && day > last {
last = day
}
}
return last
}
// sharedNames are the other computers kept here, by id, and what each is called.
func sharedNames() map[string]string {
out := map[string]string{}
kept := SharedKept()
if len(kept) == 0 {
return out
}
self, _ := Computer()
for _, k := range kept {
c, _, _ := strings.Cut(k, "/")
if c == self || out[c] != "" {
continue
}
name, _ := os.ReadFile(nameFile(c))
out[c] = strings.TrimSpace(string(name))
if out[c] == "" {
out[c] = c
}
}
return out
}
// SharedKept are the other computers' days kept here, as "<id>/<day>".
func SharedKept() []string {
var out []string
cs, _ := os.ReadDir(OthersDir())
for _, c := range cs {
if !c.IsDir() {
continue
}
days, _ := os.ReadDir(filepath.Join(OthersDir(), c.Name()))
for _, d := range days {
if day, ok := strings.CutSuffix(d.Name(), ".json"); ok {
out = append(out, c.Name()+"/"+day)
}
}
}
slices.Sort(out)
return out
}
// DropShared lets another computer's day go, and its folder with its last.
func DropShared(computer, day string) {
if !validID(computer) {
return
}
os.Remove(sharedFile(computer, day))
if latestDay(computer) == "" {
os.Remove(nameFile(computer))
os.Remove(filepath.Join(OthersDir(), computer))
}
}
// DropAllShared lets every other computer's usage go: sync, or its sharing
// of usage, was turned off.
func DropAllShared() { os.RemoveAll(OthersDir()) }
// sharedSource is one kept day, for the request page to read when it changed.
type sharedSource struct {
path, computer, day string
size int64
mod time.Time
}
// sharedSources are the days kept from day since on (all for zero), and
// whether any is kept at all, of any day; this computer's id is never among them.
func sharedSources(since time.Time) (out []sharedSource, some bool) {
kept := SharedKept()
if len(kept) == 0 {
return nil, false
}
self, _ := Computer()
from := ""
// A day's calls began where it was a day, and since is the reader's
// day, which can begin up to 26 hours from that computer's (UTC-12 and
// UTC+14): two days before.
if !since.IsZero() {
from = since.AddDate(0, 0, -2).Format(time.DateOnly)
}
for _, k := range kept {
c, day, _ := strings.Cut(k, "/")
if c == self || !validID(c) {
continue
}
some = true
if day < from {
continue
}
p := sharedFile(c, day)
fi, err := os.Stat(p)
if err != nil {
continue
}
out = append(out, sharedSource{path: p, computer: c, day: day, size: fi.Size(), mod: fi.ModTime()})
}
return out, some
}
func readShared(p string) (SharedDay, bool) {
var d SharedDay
b, err := os.ReadFile(p)
if err != nil || json.Unmarshal(b, &d) != nil {
return d, false
}
return d, true
}
// sharedRecords are the other computers' calls since since, each with its
// computer.
func sharedRecords(since time.Time) (calls []SharedCall) {
srcs, _ := sharedSources(since)
for _, s := range srcs {
d, ok := readShared(s.path)
if !ok {
continue
}
for _, c := range d.Calls {
if !since.IsZero() && c.Time.Before(since) {
continue
}
c.Computer = s.computer
calls = append(calls, c)
}
}
return calls
}