Files
magpie/internal/gui/providerswrite.go
T
yetone 573b21f4b0 gui: the Providers answer is written a provider at a time
Each poll encoded /api/providers whole, growing json's buffer to the
answer's size once the GC had emptied its pool. writeProvidersJSON
writes the same bytes with each provider's row encoded alone, as
writeStateJSON does for agents; every handler that answered
writeJSON(rw, providersState()) uses it.

Real accounts (sandbox copy of the owner's HOME, network blocked), 40
polls, bb478f0e5 (mshare) vs this tree (mall):
  the providers write 37.7 MB (writeJSON, cum) -> 13.6 MB
  (writeProvidersJSON, cum)
  /api/providers equal but for `fetched` and `lapsed` (a refused
  refresh in the blocked sandbox); /api/state and drift identical

TestProvidersWrittenAsEncoded: the bytes are json.Encoder's for a big
answer, an empty list and none. TestProvidersWriteGrowsNoBufferItsSize:
under half the answer's size allocated per write. Broken by hand on
mote (writeJSON put back): "writing a 549015-byte answer allocated
2101096 bytes, want under half its size".

Run on mote at this tree: gofmt; go vet darwin and windows; the new
tests with TestStateWritten* 3/3 ok; go test ./internal/gui: the known
reds #4514, #3949 and TestColdTurnsTaken (#4510). GOOS=linux go vet of
internal/gui can't run here (Wails' Linux files need cgo; WSL has no
gtk4/webkitgtk-6.0); this change has no OS-specific code.
Not run: the full ./... suite.
2026-11-01 06:16:35 +08:00

45 lines
1.2 KiB
Go

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')
}