Skip to content
Myr

server: avoid O(n^2) body accumulation in HTTP listener

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- handleHttpRequest used `body += text` per token, allocating a new backing array on every append (O(n^2) total copy work) - a single ~390 KB POST monopolised the single-threaded server for ~8 s, blocking all other --listen clients - switch to strings.Builder for amortised O(n) Reported with fix by Michal Majchrowicz and Marcin Wyczechowski (AFINE Team).

authored by Junegunn Choi · committed by Junegunn Choi · parent 4b23aa4 · Browse files · 1 file+4 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+4 added−3 removed

  • other:+4 added−3 removed

1 file+4 added−3 removed

modified:src/server.go+4 added-3 removed
151 unmodified lines
152// * --listen w/o net/http: 3.3MB153func (server *httpServer) handleHttpRequest(conn net.Conn) string {154 contentLength := 0155 apiKey := ""156 body := ""156 var bodyBuilder strings.Builder157 answer := func(code string, message string) string {158 message += "\n"159 return code + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)160 }
13 unmodified lines
174 if found >= 0 {175 token := data[:found+len(crlf)]176 return len(token), token, nil177 }178 if atEOF || len(body)+len(data) >= contentLength {178 if atEOF || bodyBuilder.Len()+len(data) >= contentLength {179 return 0, data, bufio.ErrFinalToken180 }181 return 0, nil, nil182 })
34 unmodified lines
217 apiKey = strings.TrimSpace(pair[1])218 }219 }220 case 2: // Request body221 body += text221 bodyBuilder.WriteString(text)222 }223 }224225 if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {
7 unmodified lines
233 }234 return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`)235 }236237 body := bodyBuilder.String()238 if len(body) < contentLength {239 return bad("incomplete request")240 }241 body = body[:contentLength]
36 unmodified lines