gui: the Sessions list goes out a row at a time, never held whole (#2278)
writeJSONRows built the whole answer in a buffer to hash it and send it.
Over the owner's full history (16,600 sessions, 5.8 MB list) that buffer
grew to 25 MB, was kept between polls, and was 25 MB of a warm start's
183 MB live heap. Now a first pass encodes each row into one small
buffer for its hash and the answer's tag. What is sent is encoded again,
straight to the ResponseWriter through a 32 KiB bufio.Writer, and a delta
holds only the rows the page hasn't got. The bytes and the tag are the
same as before, so the page's delta and "same" answers don't change.
Run on mote (macOS 27), real history copy (~16,600 session files):
- warm start, 75 s of poll.sh (what an open window asks every 5 s):
- before (v0.1.2382): steady footprint 240-265 MB, live heap 183-193 MB;
- after: steady footprint 216-233 MB, live heap 168-178 MB.
- The phys_footprint peak is about the same (257-267 vs 264-289 MB over
3 interleaved pairs): a poll's own spike still sets it.
- /api/sessions from each binary on the same history: the same tag
06a661d3…, the same sha256 of 5,842,606 bytes, X-Magpie-Same on its
tag, and the full list for an unknown tag.
- TestJSONRowsNotHeldWhole is new: red on the old writeJSONRows (9.5 MB
allocated for a 4.2 MB answer), green now. TestWriteJSONRowsWritesWhatMarshalDid
(bytes and delta) is green.
- go test ./internal/gui: ok except three reds that are already filed.
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949) are red the same way with the old api.go in the same copy.
TestColdTurnsTaken (#4510) was red in the full run and passed 3 of 3
alone.
Not run: the GUI (Playwright) suite. app.js isn't touched and the
answer's bytes are the same.
This commit is contained in:
+64
-59
@@ -5,6 +5,7 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
@@ -2980,10 +2981,6 @@ func keepAnswer(b *bytes.Buffer) {
|
||||
answerBuffers.t.Reset(answerLinger)
|
||||
}
|
||||
|
||||
// rowsSize is the size of the last answer writeJSONRows wrote of each key,
|
||||
// what the next one's buffer is made for.
|
||||
var rowsSize sync.Map
|
||||
|
||||
// writeJSONRows is writeJSONSame for an answer that is a long list, key,
|
||||
// beside the fields of rest: one asked with the tag of a list sent before
|
||||
// that changed since gets X-Magpie-Delta: key, and its list holds only the
|
||||
@@ -2991,6 +2988,13 @@ var rowsSize sync.Map
|
||||
// [from, count] of the list the page has. While an agent works, its
|
||||
// session's row changes every poll, and the Sessions tab read all ~5000
|
||||
// rows (~8 MB) again for it.
|
||||
//
|
||||
// The answer is never held whole. A first pass encodes each row into one
|
||||
// small buffer, for its hash and the answer's tag; what is sent is
|
||||
// encoded again, straight to rw, and in a delta only the rows the page
|
||||
// hasn't got. The whole answer, built in a buffer to hash and send, was
|
||||
// 25 MB of a warm start's 183 MB live heap over a full history (16,600
|
||||
// sessions), kept between polls and grown again by each (#2278).
|
||||
func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, rows []T, rest any) {
|
||||
tail, err := json.Marshal(rest)
|
||||
if err != nil {
|
||||
@@ -2998,63 +3002,42 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
|
||||
return
|
||||
}
|
||||
k, _ := json.Marshal(key)
|
||||
// the rows are written once, into the answer itself: each row's
|
||||
// Marshal, their Join and the answer's buffer were three copies of the
|
||||
// ~8 MB list a poll, and the buffer grew to it from nothing
|
||||
whole := answerBuffer()
|
||||
defer keepAnswer(whole)
|
||||
if n, ok := rowsSize.Load(key); ok {
|
||||
whole.Grow(n.(int) + n.(int)/8)
|
||||
head := append(append([]byte{'{'}, k...), ":["...)
|
||||
end := []byte{']'}
|
||||
if len(tail) > 2 {
|
||||
end = append(append(end, ','), tail[1:]...)
|
||||
} else {
|
||||
end = append(end, '}')
|
||||
}
|
||||
whole.WriteByte('{')
|
||||
whole.Write(k)
|
||||
whole.WriteString(":[")
|
||||
enc := json.NewEncoder(whole)
|
||||
ends := make([]int, len(rows)+1)
|
||||
ends[0] = whole.Len()
|
||||
for i := range rows {
|
||||
end = append(end, '\n')
|
||||
var row bytes.Buffer
|
||||
enc := json.NewEncoder(&row)
|
||||
// encode is row i as Marshal gives it: Encode ends it with a newline
|
||||
encode := func(i int) ([]byte, error) {
|
||||
row.Reset()
|
||||
if err := enc.Encode(rows[i]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return row.Bytes()[:row.Len()-1], nil
|
||||
}
|
||||
whole := sha256.New()
|
||||
whole.Write(head)
|
||||
sums := make([][16]byte, len(rows))
|
||||
for i := range rows {
|
||||
b, err := encode(i)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
// Encode ends the row with a newline: it is the comma after it
|
||||
whole.Bytes()[whole.Len()-1] = ','
|
||||
ends[i+1] = whole.Len()
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
whole.Truncate(whole.Len() - 1)
|
||||
}
|
||||
end := func(b *bytes.Buffer) {
|
||||
b.WriteByte(']')
|
||||
if len(tail) > 2 {
|
||||
b.WriteByte(',')
|
||||
b.Write(tail[1:])
|
||||
} else {
|
||||
b.WriteByte('}')
|
||||
if i > 0 {
|
||||
whole.Write([]byte{','})
|
||||
}
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
end(whole)
|
||||
rowsSize.Store(key, whole.Len())
|
||||
all := whole.Bytes()
|
||||
raw := make([][]byte, len(rows))
|
||||
sums := make([][16]byte, len(rows))
|
||||
for i := range rows {
|
||||
raw[i] = all[ends[i] : ends[i+1]-1]
|
||||
sum := sha256.Sum256(raw[i])
|
||||
whole.Write(b)
|
||||
sum := sha256.Sum256(b)
|
||||
sums[i] = [16]byte(sum[:16])
|
||||
}
|
||||
body := func(items [][]byte) []byte {
|
||||
var b bytes.Buffer
|
||||
b.WriteByte('{')
|
||||
b.Write(k)
|
||||
b.WriteString(":[")
|
||||
b.Write(bytes.Join(items, []byte(",")))
|
||||
end(&b)
|
||||
return b.Bytes()
|
||||
}
|
||||
sum := sha256.Sum256(all)
|
||||
tag := hex.EncodeToString(sum[:16])
|
||||
whole.Write(end)
|
||||
tag := hex.EncodeToString(whole.Sum(nil)[:16])
|
||||
rw.Header().Set("X-Magpie-Tag", tag)
|
||||
had := r.Header.Get("X-Magpie-Had")
|
||||
if had == tag {
|
||||
@@ -3077,19 +3060,38 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
|
||||
}
|
||||
sentRows.Unlock()
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
out := bufio.NewWriterSize(rw, 32<<10)
|
||||
defer out.Flush()
|
||||
out.Write(head)
|
||||
first := true
|
||||
item := func(b []byte) {
|
||||
if !first {
|
||||
out.WriteByte(',')
|
||||
}
|
||||
first = false
|
||||
out.Write(b)
|
||||
}
|
||||
if !ok || had == "" {
|
||||
_, _ = rw.Write(all)
|
||||
for i := range rows {
|
||||
b, err := encode(i)
|
||||
if err != nil {
|
||||
// the first pass encoded it: nothing else changes a row
|
||||
return
|
||||
}
|
||||
item(b)
|
||||
}
|
||||
out.Write(end)
|
||||
return
|
||||
}
|
||||
at := make(map[[16]byte][]int, len(was))
|
||||
for j, s := range was {
|
||||
at[s] = append(at[s], j)
|
||||
}
|
||||
var items [][]byte
|
||||
rw.Header().Set("X-Magpie-Delta", key)
|
||||
from, n := 0, 0
|
||||
run := func() {
|
||||
if n > 0 {
|
||||
items = append(items, []byte("["+strconv.Itoa(from)+","+strconv.Itoa(n)+"]"))
|
||||
item([]byte("[" + strconv.Itoa(from) + "," + strconv.Itoa(n) + "]"))
|
||||
}
|
||||
n = 0
|
||||
}
|
||||
@@ -3097,7 +3099,11 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
|
||||
js := at[s]
|
||||
if len(js) == 0 {
|
||||
run()
|
||||
items = append(items, raw[i])
|
||||
b, err := encode(i)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
item(b)
|
||||
continue
|
||||
}
|
||||
j := js[0]
|
||||
@@ -3110,8 +3116,7 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r
|
||||
from, n = j, 1
|
||||
}
|
||||
run()
|
||||
rw.Header().Set("X-Magpie-Delta", key)
|
||||
_, _ = rw.Write(body(items))
|
||||
out.Write(end)
|
||||
}
|
||||
|
||||
func fail(rw http.ResponseWriter, err error) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
@@ -63,12 +64,26 @@ func TestAnswerBufferKeptForTheNext(t *testing.T) {
|
||||
t.Fatalf("next buffer holds %d, room for %d: not the last answer's", b.Len(), b.Cap())
|
||||
}
|
||||
keepAnswer(b)
|
||||
rows := []rowsBufRow{{Name: string(big)}}
|
||||
writeJSONRows(httptest.NewRecorder(), httptest.NewRequest("GET", "/x", nil), "kept-test", rows, struct{}{})
|
||||
answerBuffers.Lock()
|
||||
n := len(answerBuffers.free)
|
||||
answerBuffers.Unlock()
|
||||
if n == 0 {
|
||||
t.Fatal("writeJSONRows kept no buffer for the next answer")
|
||||
}
|
||||
|
||||
// writeJSONRows holds no answer-sized buffer: the list goes out a row at a
|
||||
// time, and the whole answer was 25 MB of a warm start's live heap (#2278).
|
||||
func TestJSONRowsNotHeldWhole(t *testing.T) {
|
||||
big := string(bytes.Repeat([]byte("x"), 64<<10))
|
||||
rows := make([]rowsBufRow, 64)
|
||||
for i := range rows {
|
||||
rows[i] = rowsBufRow{Name: big, N: float64(i)}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
writeJSONRows(w, httptest.NewRequest("GET", "/x", nil), "rows", rows, struct{}{}) // warm
|
||||
var before, after runtime.MemStats
|
||||
w = httptest.NewRecorder()
|
||||
w.Body.Grow(len(rows)*len(big) + 1<<20) // the recorder's copy isn't magpie's
|
||||
runtime.ReadMemStats(&before)
|
||||
writeJSONRows(w, httptest.NewRequest("GET", "/x", nil), "rows", rows, struct{}{})
|
||||
runtime.ReadMemStats(&after)
|
||||
answer := uint64(w.Body.Len())
|
||||
if got := after.TotalAlloc - before.TotalAlloc; got > answer/4 {
|
||||
t.Fatalf("writeJSONRows allocated %d bytes for a %d-byte answer", got, answer)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user