marshalBody marshalled every item of a translated request's list (the
messages, the input items) and kept the bytes, so it could size the body
exactly before copying them in: at the body's peak the written items
were a whole copy of the conversation beside the body. Past bodyKept
(4 MiB) of kept items, an item is now only measured, encoded through a
json.Encoder into a writer that only counts, and
once the body is made it is encoded again straight into it, then let go
when its list is spent. A body under 4 MiB is written as before, with no
second encoding; a larger one pays its encoding once more (on mote the
47 MiB case of TestMarshalBodyAllocatesTwoBodies went 0.09 -> 0.11 s
for both marshals together). The bytes are json.Marshal's either way.
Measured on mote, scratch harness (not committed): a 45 MiB Codex
conversation sent Responses -> Chat through the gateway, GOGC=10,
HeapInuse sampled every 2 ms, 3 runs each, base heap 54 MiB:
425a61322 (before 8eb7f5565): peak 302, 301, 301 MiB
8eb7f5565 (spent list): peak 278, 271, 273 MiB
this change: peak 264, 263, 263 MiB
marshalBody of the 47 MiB test body allocates 52 MiB, was 98 MiB.
Tests: TestMarshalBodyAllocatesTwoBodies now holds marshalBody to 1.5x
the body (was 2.5x); red on the old code, which allocated 98 MiB for
47. TestMarshalBodyIsJSONMarshal runs every body, and every value
json.Marshal refuses, with everything kept, with every item measured
(bodyKept 0) and with the first kept and the rest measured (1).
Run at the pushed head (mote): GOOS=linux/windows/darwin go vet -tags
nogui ./internal/gateway/: ok. go test -count=1 -timeout 45m
./internal/gateway/: ok (465.1s)
Not tried: a real upstream; the bytes sent are unchanged.