diff --git a/internal/gui/api.go b/internal/gui/api.go index 3fba60521..9963c0efe 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -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) { diff --git a/internal/gui/stats_answer_test.go b/internal/gui/stats_answer_test.go index 23b4b0ac1..ae761814f 100644 --- a/internal/gui/stats_answer_test.go +++ b/internal/gui/stats_answer_test.go @@ -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) } }