diff --git a/internal/gateway/history.go b/internal/gateway/history.go index e091a1882..2ba50cab7 100644 --- a/internal/gateway/history.go +++ b/internal/gateway/history.go @@ -22,6 +22,7 @@ import ( "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/steady" "github.com/yetone/magpie/internal/usage" ) @@ -85,6 +86,18 @@ func saveRoute(r Route) { // pruneHistory gzips the days that are over, and drops the days older than // historyDays, then the oldest until what is left fits historyBytes. func pruneHistory(dir string, now time.Time) { + // a .gz.tmp left by a magpie stopped before renaming it (gzipFile) goes + // once it is an hour old: a younger one may be another magpie's, still + // being written + es, _ := os.ReadDir(dir) + for _, e := range es { + if !strings.HasSuffix(e.Name(), ".jsonl.gz.tmp") { + continue + } + if fi, err := e.Info(); err == nil && now.Sub(fi.ModTime()) > time.Hour { + os.Remove(filepath.Join(dir, e.Name())) + } + } today := now.Local().Format(dayForm) for _, d := range historyFiles(dir) { if d.day < today && !strings.HasSuffix(d.path, ".gz") { @@ -107,20 +120,98 @@ func pruneHistory(dir string, now time.Time) { } } +// gzipFile gzips a day's file into its .gz. A day gzipped already keeps its +// .gz, the file's routes going after its own as a gzip member of their own +// (read back as one stream): a route that began before midnight and was done +// after the first prune past it is written to its day's file again. A route +// in the .gz already, from a file added and left behind (magpie stopped +// before removing it), isn't added again. A .gz cut short, or ending in a +// route cut short (an older magpie stopped, or the disk filled, as it or its +// file was written), is written anew from its whole routes and the file's +// when the file has a route to add: after the break the file's routes +// couldn't be read, and after a route cut short the first of them would join +// it. A last route whole but for its newline is kept. The .gz is read a route +// at a time, never held whole unzipped; it is replaced whole, never seen half +// written, and the file goes once its routes are in. A .gz that can't be read +// from disk is left as it is, and the file with it, for a later prune. func gzipFile(path string) { b, err := os.ReadFile(path) if err != nil { return } - var buf bytes.Buffer - z := gzip.NewWriter(&buf) - z.Write(b) - if z.Close() != nil || os.WriteFile(path+".gz", buf.Bytes(), 0o600) != nil { + old, err := os.ReadFile(path + ".gz") + if err != nil && !os.IsNotExist(err) { return } + // the file's routes, each true once the .gz is seen to have it: a set + // built from the file, a few routes, not from the whole day + in := map[string]bool{} + whole := true // the .gz, if there is one, can have routes go after it + if len(old) > 0 { + for l := range bytes.Lines(b) { + in[string(bytes.TrimSpace(l))] = false + } + whole = gzRoutes(old, func(l []byte) { + if _, ok := in[string(l)]; ok { + in[string(l)] = true + } + }) + } + buf := new(bytes.Buffer) + if whole { + buf = bytes.NewBuffer(old) + } + z := gzip.NewWriter(buf) + nl := []byte{'\n'} + add := func(l []byte) { + z.Write(l) + z.Write(nl) + } + if !whole { + gzRoutes(old, add) // written anew, its whole routes first + } + added := false + for l := range bytes.Lines(b) { + if l = bytes.TrimSpace(l); len(l) > 0 && !in[string(l)] { + add(l) + added = true + } + } + if added { + tmp := path + ".gz.tmp" + if z.Close() != nil || os.WriteFile(tmp, buf.Bytes(), 0o600) != nil || steady.Rename(tmp, path+".gz") != nil { + os.Remove(tmp) + return + } + } os.Remove(path) } +// gzRoutes calls f with each route of a day's .gz in turn, a last route +// whole but for its newline among them and one cut short left out. It says +// whether the .gz read to its end, its last route ending in a newline: what +// a gzip member added after it needs to be read. +func gzRoutes(gz []byte, f func([]byte)) bool { + z, err := gzip.NewReader(bytes.NewReader(gz)) + if err != nil { + return false + } + r := bufio.NewReader(z) + for { + line, err := r.ReadBytes('\n') + l := bytes.TrimSpace(line) + if err != nil { + if len(l) > 0 && json.Valid(l) { + f(l) + } + return err == io.EOF && len(l) == 0 + } + if len(l) > 0 { + f(l) + } + } +} + type dayFile struct { day, path string size int64 @@ -184,7 +275,11 @@ func History(day string) (days []HistoryDay, routes []Route, cut bool) { history.counts[d.path] = c } if n := c.n; n > 0 { - days = append([]HistoryDay{{d.day, n}}, days...) + if len(days) > 0 && days[0].Day == d.day { + days[0].Requests += n // a late route's file beside the day's .gz + } else { + days = append([]HistoryDay{{d.day, n}}, days...) + } } } sort.SliceStable(routes, func(i, j int) bool { return routes[i].Time.Before(routes[j].Time) }) diff --git a/internal/gateway/history_test.go b/internal/gateway/history_test.go index 6933dba12..f78ba036b 100644 --- a/internal/gateway/history_test.go +++ b/internal/gateway/history_test.go @@ -1,9 +1,14 @@ package gateway import ( + "bytes" + "compress/gzip" "encoding/json" + "io" "os" "path/filepath" + "slices" + "strconv" "strings" "testing" "time" @@ -79,6 +84,202 @@ func TestHistoryKeepsDaysAndDropsOld(t *testing.T) { } } +// A route that began on a day gzipped already, its reply streamed past +// midnight and past that hour's prune, is kept with the day's other +// routes: its file is added to the day's .gz, not written over it, and the +// day is listed once with all of them, before and after. Its file added and +// left behind (magpie stopped before removing it) adds none of them again, +// however often it is left, and late routes written to it in between. +func TestHistoryKeepsALateRouteWithItsDay(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := historyNoon(t) + y, m, d := now.AddDate(0, 0, -1).Date() + yday := time.Date(y, m, d, 23, 59, 0, 0, time.Local) + before := yday.AddDate(0, 0, -1) + day, dir := yday.Format(dayForm), HistoryDir() + late := filepath.Join(dir, day+".jsonl") + kept := func(when string, ids ...int64) { + t.Helper() + want := []HistoryDay{{day, len(ids)}, {before.Format(dayForm), 1}} + days, rs, _ := History(day) + var got []int64 + for _, r := range rs { + got = append(got, r.ID) + } + if !slices.Equal(days, want) || !slices.Equal(got, ids) { + t.Errorf("%s: days %+v, routes %v; want %+v, routes %v", when, days, got, want, ids) + } + if days, _, _ := History(""); !slices.Equal(days, want) { + t.Errorf("%s: days live %+v; want %+v", when, days, want) + } + for _, id := range ids { + if _, ok := HistoryRoute(id, yday); !ok { + t.Errorf("%s: route %d not found", when, id) + } + } + } + prune := func() { + t.Helper() + pruneHistory(dir, now) + if _, err := os.Stat(late); !os.IsNotExist(err) { + t.Errorf("the late file is still there: %v", err) + } + } + saveRoute(Route{ID: 9, Time: before, Model: "z", Done: true}) + saveRoute(Route{ID: 1, Time: yday, Model: "a", Done: true}) + prune() + saveRoute(Route{ID: 2, Time: yday.Add(10 * time.Second), Model: "b", Done: true}) // done after the prune + kept("beside the day's .gz", 1, 2) + left, err := os.ReadFile(late) + if err != nil { + t.Fatal(err) + } + prune() + kept("added to the day's .gz", 1, 2) + os.WriteFile(late, left, 0o600) + prune() + kept("left behind", 1, 2) + ids := []int64{1, 2, 3, 4} + for _, id := range ids[2:] { + os.WriteFile(late, left, 0o600) + saveRoute(Route{ID: id, Time: yday.Add(time.Duration(id) * 10 * time.Second), Model: "c", Done: true}) + if left, err = os.ReadFile(late); err != nil { + t.Fatal(err) + } + prune() + kept("left behind, a late route written to it since", ids[:id]...) + } +} + +// A day's .gz cut short, by an older magpie stopped (or a disk filled) while +// writing it in place, or by a route cut short in the file it was gzipped +// from, is written anew from the whole routes it has and its file's: after +// the break none of the file's routes could be read, and after a route cut +// short the first of them would join it. A last route whole but for its +// newline is kept. +func TestHistoryKeepsADayCutShort(t *testing.T) { + route := func(id int) string { return `{"id":` + strconv.Itoa(id) + `,"model":"m"}` + "\n" } + for _, c := range []struct { + name string + gz func(z *gzip.Writer) // writes the .gz as it was left + file string + ids []int64 + }{ + // gzipped in place from its file, all three routes, and stopped + // after the first and a half + {"stopped while written in place", func(z *gzip.Writer) { + z.Write([]byte(route(1) + route(2)[:9])) + z.Flush() + }, route(1) + route(2) + route(3), []int64{1, 2, 3}}, + // gzipped whole from a file whose second route was cut short, and a + // late route written to the file since + {"its file cut short", func(z *gzip.Writer) { + z.Write([]byte(route(1) + route(2)[:9])) + z.Close() + }, route(3), []int64{1, 3}}, + // gzipped whole from a file whose last route was written without its + // newline, and a late route written to the file since + {"its last route without its newline", func(z *gzip.Writer) { + z.Write([]byte(route(1) + strings.TrimSuffix(route(2), "\n"))) + z.Close() + }, route(3), []int64{1, 2, 3}}, + } { + t.Run(c.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now() + day, dir := now.AddDate(0, 0, -1).Format(dayForm), HistoryDir() + path := filepath.Join(dir, day+".jsonl") + os.MkdirAll(dir, 0o700) + var gz bytes.Buffer + c.gz(gzip.NewWriter(&gz)) + os.WriteFile(path+".gz", gz.Bytes(), 0o600) + os.WriteFile(path, []byte(c.file), 0o600) + pruneHistory(dir, now) + days, rs, _ := History(day) + var got []int64 + for _, r := range rs { + got = append(got, r.ID) + } + if len(days) != 1 || days[0] != (HistoryDay{day, len(c.ids)}) || !slices.Equal(got, c.ids) { + t.Errorf("days %+v, routes %v; want %s with %v", days, got, day, c.ids) + } + b, _ := os.ReadFile(path + ".gz") + z, err := gzip.NewReader(bytes.NewReader(b)) + if err == nil { + _, err = io.Copy(io.Discard, z) + } + if err != nil { + t.Errorf("the .gz isn't whole: %v", err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("the file is still there: %v", err) + } + }) + } +} + +// A day's .gz.tmp left by a magpie stopped before renaming it over the .gz +// goes at a prune once it is an hour old. A younger one, maybe another +// magpie's still being written, stays. +func TestHistoryDropsALeftGzTmp(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now() + dir := HistoryDir() + os.MkdirAll(dir, 0o700) + left := filepath.Join(dir, now.AddDate(0, 0, -2).Format(dayForm)+".jsonl.gz.tmp") + young := filepath.Join(dir, now.AddDate(0, 0, -1).Format(dayForm)+".jsonl.gz.tmp") + os.WriteFile(left, []byte("\x1f\x8b\x08"), 0o600) + os.WriteFile(young, []byte("\x1f\x8b\x08"), 0o600) + then := now.Add(-time.Hour - time.Minute) + if err := os.Chtimes(left, then, then); err != nil { + t.Fatal(err) + } + pruneHistory(dir, now) + if _, err := os.Stat(left); !os.IsNotExist(err) { + t.Errorf("the .gz.tmp left over an hour ago is still there: %v", err) + } + if _, err := os.Stat(young); err != nil { + t.Errorf("a .gz.tmp written just now is gone: %v", err) + } +} + +// A day's .gz that can't be read (left by magpie run as another user, say) +// is unknown, not empty: it isn't written over from the day's file, and the +// file stays for a prune that can read the .gz. +func TestHistoryLeavesADayItCantRead(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now() + day, dir := now.AddDate(0, 0, -1).Format(dayForm), HistoryDir() + path := filepath.Join(dir, day+".jsonl") + os.MkdirAll(dir, 0o700) + var gz bytes.Buffer + z := gzip.NewWriter(&gz) + z.Write([]byte(`{"id":1,"model":"m"}` + "\n")) + z.Close() + os.WriteFile(path+".gz", gz.Bytes(), 0o600) + os.WriteFile(path, []byte(`{"id":2,"model":"m"}`+"\n"), 0o600) + if err := os.Chmod(path+".gz", 0); err != nil { + t.Fatal(err) + } + if _, err := os.ReadFile(path + ".gz"); err == nil { + t.Skip("a file at mode 0 still reads here: root, Windows, or a file system without Unix permissions") + } + pruneHistory(dir, now) + if _, err := os.Stat(path); err != nil { + t.Errorf("the file is gone with the .gz unread: %v", err) + } + os.Chmod(path+".gz", 0o600) + pruneHistory(dir, now) + days, rs, _ := History(day) + var got []int64 + for _, r := range rs { + got = append(got, r.ID) + } + if want := []int64{1, 2}; len(days) != 1 || days[0] != (HistoryDay{day, 2}) || !slices.Equal(got, want) { + t.Errorf("read again: days %+v, routes %v; want %s with %v", days, got, day, want) + } +} + func TestRouteUsageCompactAndLegacyJSON(t *testing.T) { // Ignore fields that full ledger records wrote into earlier route history. var old Route