diff --git a/internal/gui/providers.go b/internal/gui/providers.go index f50456195..cc84d2909 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1190,7 +1190,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } s := providersState() - writeJSON(rw, s) + writeProvidersJSON(rw, s) keepProviders(s) }) // Recent-call bodies are read only when their row is opened, not with @@ -1232,7 +1232,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } - writeJSON(rw, providersState()) + writeProvidersJSON(rw, providersState()) }) // a picture for a provider, picked in the editor: kept by content before // the provider is saved, which then points at it. The page sends it as @@ -2371,7 +2371,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { http.NotFound(rw, r) return } - writeJSON(rw, providersState()) + writeProvidersJSON(rw, providersState()) }) // The Codex desktop app left on the model list before a change (the // Agents row's Restart): quit it and open it again. @@ -2593,7 +2593,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } - writeJSON(rw, providersState()) + writeProvidersJSON(rw, providersState()) }) mux.HandleFunc("POST /api/stepfun/{id}/signout", func(rw http.ResponseWriter, r *http.Request) { id, _, ok := stepfunOf(rw, r) @@ -2604,7 +2604,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } - writeJSON(rw, providersState()) + writeProvidersJSON(rw, providersState()) }) // the page copies through here first: in the app's window the // clipboard API is refused or missing, depending on the system diff --git a/internal/gui/providerswrite.go b/internal/gui/providerswrite.go new file mode 100644 index 000000000..7d4456c10 --- /dev/null +++ b/internal/gui/providerswrite.go @@ -0,0 +1,44 @@ +package gui + +import ( + "bufio" + "bytes" + "encoding/json" + "net/http" +) + +// providersNull is how a providersJSON with no providers begins: +// Providers is its first field. +const providersNull = `{"providers":null` + +// writeProvidersJSON writes s to rw as writeJSON does, each provider's row +// encoded alone. Encoding the answer whole grew a buffer to its size each +// poll: 27 MB of what forty polls of the Providers page allocated with +// real accounts. +func writeProvidersJSON(rw http.ResponseWriter, s providersJSON) { + rows := s.Providers + s.Providers = nil + tail, err := json.Marshal(s) + if rows == nil || err != nil || !bytes.HasPrefix(tail, []byte(providersNull)) { + s.Providers = rows + writeJSON(rw, s) + return + } + rw.Header().Set("Content-Type", "application/json") + out := bufio.NewWriterSize(rw, 32<<10) + defer out.Flush() + _, _ = out.WriteString(`{"providers":[`) + enc := json.NewEncoder(lineless{out}) + for i := range rows { + if i > 0 { + _ = out.WriteByte(',') + } + // a pointer, so a method on *T is used as it is in the slice + if enc.Encode(&rows[i]) != nil { + return + } + } + _ = out.WriteByte(']') + _, _ = out.Write(tail[len(providersNull):]) + _ = out.WriteByte('\n') +} diff --git a/internal/gui/providerswrite_test.go b/internal/gui/providerswrite_test.go new file mode 100644 index 000000000..2cb16501a --- /dev/null +++ b/internal/gui/providerswrite_test.go @@ -0,0 +1,70 @@ +package gui + +import ( + "bytes" + "encoding/json" + "fmt" + "runtime" + "testing" +) + +// bigProviders is an answer the size real accounts give the Providers +// page: many providers, each with a long model list. +func bigProviders() providersJSON { + var s providersJSON + for p := range 30 { + row := providerJSON{ID: fmt.Sprintf("p%d", p), Name: "Provider & two", Chat: "https://api.example.com/v1"} + for m := range 200 { + row.Models = append(row.Models, modelJSON{ID: fmt.Sprintf("model-%d", m), Name: fmt.Sprintf("Model %d", m), Efforts: []string{"low", "high"}}) + } + s.Providers = append(s.Providers, row) + } + s.Presets = []presetJSON{} + s.CodexApp = "someone" + s.Movable = []string{"x"} + return s +} + +// The answer is written as writeJSON wrote it, with no providers too. +func TestProvidersWrittenAsEncoded(t *testing.T) { + for _, s := range []providersJSON{bigProviders(), {Providers: []providerJSON{}}, {}} { + w := &sinkWriter{keep: true} + writeProvidersJSON(w, s) + var want bytes.Buffer + if err := json.NewEncoder(&want).Encode(s); err != nil { + t.Fatal(err) + } + if !bytes.Equal(w.body.Bytes(), want.Bytes()) { + t.Fatalf("the answer was written as\n%.300s\nwant\n%.300s", w.body.Bytes(), want.Bytes()) + } + if ct := w.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("Content-Type %q", ct) + } + } +} + +// Each poll of the Providers page encoded the answer whole, growing a +// buffer to its size: 27 MB of what forty polls allocated. Each provider +// is encoded alone now. +func TestProvidersWriteGrowsNoBufferItsSize(t *testing.T) { + s := bigProviders() + w := &sinkWriter{} + writeProvidersJSON(w, s) // json's encoders, warmed + size := w.n + const runs = 5 + var all uint64 + for range runs { + // polls are seconds apart, and a GC between them empties the + // buffers json pools (twice: a pool keeps a GC's victims once) + runtime.GC() + runtime.GC() + var m0, m1 runtime.MemStats + runtime.ReadMemStats(&m0) + writeProvidersJSON(&sinkWriter{}, s) + runtime.ReadMemStats(&m1) + all += m1.TotalAlloc - m0.TotalAlloc + } + if per := int(all) / runs; per > size/2 { + t.Fatalf("writing a %d-byte answer allocated %d bytes, want under half its size", size, per) + } +}