Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

provider: what answered a request is written to served.json behind it, once in a while, not on every answer

yetonea20d86900d53
diff --git a/internal/cli/signals.go b/internal/cli/signals.go
index f001214d6..adf313216 100644
--- a/internal/cli/signals.go
+++ b/internal/cli/signals.go
@@ -9,6 +9,7 @@ import (
"syscall"
"github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/provider"
)
// endProbesOnSignal: the probes magpie asks a CLI with lead a session of
@@ -39,6 +40,7 @@ func endProbesOnSignal() {
handled := s == os.Interrupt && interrupts.Load() > 0
proc.EndProbes()
if !handled {
+ provider.FlushServed() // a gateway's last answers, noted and not yet written
die(s)
}
}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 30b879463..b5ac19456 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -591,6 +591,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
defer cancel()
srv.Shutdown(c)
s.subscription.abortAll()
+ provider.FlushServed() // what answered last, kept for the next start and the CLI
}()
for {
err := srv.Serve(ln)
diff --git a/internal/provider/served.go b/internal/provider/served.go
index bc26e92da..52a9fabe1 100644
--- a/internal/provider/served.go
+++ b/internal/provider/served.go
@@ -66,6 +66,7 @@ func servedOf(id string) string {
func ours(path string) map[string]time.Time {
if servedAt.path != path {
servedAt.path, servedAt.m, servedAt.by = path, map[string]time.Time{}, map[string]string{}
+ servedFlush.pending = false // what was noted for the other file isn't this one's
}
return servedAt.m
}
@@ -85,7 +86,24 @@ func ServedID(p Provider) string {
return p.ID
}
-// NoteServed records that p just answered a request, at at.
+// servedFlushAfter is how long NoteServed waits before it writes the file:
+// what is noted meanwhile goes in the same write, so a gateway answering
+// many requests a second writes it once in a while, not once a request
+// (a read, a write and a rename on every answer). A crash loses what was
+// noted in that last moment; FlushServed, as the gateway ends, loses
+// nothing.
+var servedFlushAfter = 2 * time.Second
+
+// servedFlush is the write NoteServed has waiting, and the one being made.
+var servedFlush struct {
+ sync.Mutex // one write of the file at a time
+ pending bool // a write is waiting (servedAt held to read or set it)
+ writes uint64 // the writes made, for tests
+}
+
+// NoteServed records that p just answered a request, at at. The file
+// follows within servedFlushAfter (FlushServed): this process's LastServed
+// has it at once.
func NoteServed(p Provider, at time.Time) {
id := ServedID(p)
path := servedPath()
@@ -108,19 +126,49 @@ func NoteServed(p Provider, at time.Time) {
moved = true
servedAt.by[of] = id
}
+ if !servedFlush.pending {
+ servedFlush.pending = true
+ time.AfterFunc(servedFlushAfter, func() { flushServed(path) })
+ }
+}
+
+// FlushServed writes what NoteServed noted and hasn't written yet: the
+// gateway calls it as it ends.
+func FlushServed() { flushServed(servedPath()) }
+
+// flushServed writes what this process noted to the file at path, merged
+// with what the file holds (another gateway's), when path is still the one
+// noted for: what a test noted under a HOME of its own isn't written into
+// the next one's.
+func flushServed(path string) {
+ servedFlush.Lock()
+ defer servedFlush.Unlock()
+ servedAt.Lock()
+ if !servedFlush.pending || servedAt.path != path {
+ servedAt.Unlock()
+ return
+ }
+ servedFlush.pending = false
+ mine := make(map[string]time.Time, len(servedAt.m))
+ for k, t := range servedAt.m {
+ mine[k] = t
+ }
+ servedAt.Unlock()
m := readServed(path)
+ now := time.Now()
for k, t := range mine {
if t.After(m[k]) {
m[k] = t
}
}
for k, t := range m {
- if at.Sub(t) > servedKeep {
+ if now.Sub(t) > servedKeep {
delete(m, k)
}
}
if b, err := json.Marshal(m); err == nil && os.MkdirAll(filepath.Dir(path), 0o700) == nil {
writeFileAtomic(path, b)
+ servedFlush.writes++
}
}
diff --git a/internal/provider/served_test.go b/internal/provider/served_test.go
index b93c12d62..0012e55de 100644
--- a/internal/provider/served_test.go
+++ b/internal/provider/served_test.go
@@ -3,6 +3,7 @@ package provider
import (
"encoding/json"
"os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -24,6 +25,7 @@ func TestQuotasLastServed(t *testing.T) {
NoteServed(Provider{ID: "codex", Account: &Account{Agent: "codex", User: "[email protected]"}}, now.Add(-time.Hour))
NoteServed(Provider{ID: "dk", Key: "sk-other-key-0002"}, now.Add(-time.Minute))
NoteServed(Provider{ID: "solo", Key: "sk-solo"}, now.Add(-2*time.Hour))
+ FlushServed() // as the gateway ending writes it
// the CLI is a process of its own: what it is told is read from the file
servedAt.Lock()
servedAt.m = map[string]time.Time{}
@@ -95,3 +97,82 @@ func TestCardsLastServed(t *testing.T) {
t.Errorf("json %s", b)
}
}
+
+// A request answered isn't a read and a write of served.json: what is
+// noted is written once, within servedFlushAfter, however many requests
+// were answered meanwhile, or as the gateway ends (FlushServed); the file
+// is as it was, merged with what another gateway wrote, and this process
+// tells what it noted at once.
+func TestNoteServedWritesBehind(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ now := time.Now().Truncate(time.Second)
+ // another gateway's, already in the file
+ if err := os.MkdirAll(filepath.Dir(servedPath()), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ other, _ := json.Marshal(map[string]time.Time{"other#k1": now.Add(-time.Hour)})
+ if err := os.WriteFile(servedPath(), other, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ servedFlush.Lock()
+ writes := servedFlush.writes
+ servedFlush.Unlock()
+ key := "dk#" + KeyID("sk-key-0001")
+ for i := range 200 {
+ NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Duration(i)*time.Millisecond))
+ }
+ if b, _ := os.ReadFile(servedPath()); string(b) != string(other) {
+ t.Fatalf("written on a request answered: %s", b)
+ }
+ if at := LastServed()[key]; !at.Equal(now.Add(199 * time.Millisecond)) {
+ t.Fatalf("this process isn't told at once: %v", LastServed())
+ }
+ FlushServed()
+ FlushServed() // nothing new: no write
+ servedFlush.Lock()
+ n := servedFlush.writes - writes
+ servedFlush.Unlock()
+ if n != 1 {
+ t.Fatalf("%d writes for 200 answers", n)
+ }
+ b, err := os.ReadFile(servedPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ var m map[string]time.Time
+ if err := json.Unmarshal(b, &m); err != nil {
+ t.Fatal(err, string(b))
+ }
+ if len(m) != 2 || !m["other#k1"].Equal(now.Add(-time.Hour)) || !m[key].Equal(now.Add(199*time.Millisecond)) {
+ t.Fatalf("file %s", b)
+ }
+ // and by itself, a moment later
+ defer func(d time.Duration) { servedFlushAfter = d }(servedFlushAfter)
+ servedFlushAfter = time.Millisecond
+ NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Second))
+ for deadline := time.Now().Add(10 * time.Second); ; {
+ if b, _ := os.ReadFile(servedPath()); json.Unmarshal(b, &m) == nil && m[key].Equal(now.Add(time.Second)) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("never written")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+// BenchmarkNoteServed is what noting a request answered costs the request.
+func BenchmarkNoteServed(b *testing.B) {
+ home := b.TempDir()
+ b.Setenv("HOME", home)
+ b.Setenv("USERPROFILE", home)
+ b.Setenv("XDG_CONFIG_HOME", b.TempDir())
+ p := Provider{ID: "dk", Key: "sk-key-0001"}
+ for b.Loop() {
+ NoteServed(p, time.Now())
+ }
+ FlushServed()
+}