1 package http
2 3 // The handler path: one function call per request, in one arena.
4 //
5 // The classic path hands a handler a ResponseWriter and a *Request, so the
6 // handler owns the socket for the duration of the call and the port had to fake
7 // what Go does with closures (HandlerFunc called through a pointer to the func
8 // value; finishServe taking **response to stand in for a deferred closure).
9 //
10 // This path splits it the other way round:
11 //
12 // - the SHELL owns the socket, the framing, the accept loop, the keep-alive
13 // loop and the deadlines. It decodes the request into a Req.
14 // - a HANDLER is one call: `Handle(req *Req) (resp *Resp)`. It is a method on
15 // the application's main type, so the data access lives where the data is.
16 // It does no io, holds no sockets, spawns nothing and keeps no state
17 // between requests.
18 //
19 // Every request is processed inside ONE ARENA that the shell enters and then
20 // resets: the decoded request, everything the handler allocates and the
21 // response it returns all live there, and the whole lot is freed at once when
22 // the call is done. Requests cannot accumulate memory - the only thing that
23 // survives a request is what the application deliberately stores in its own
24 // state (a log entry in its database or file), which is its business, not the
25 // shell's.
26 //
27 // A request that never completes - the client disconnects, a read fails, the
28 // idle deadline expires - never calls the handler and its arena is reset, so
29 // there is nothing to cancel and nothing to leak.
30 //
31 // Dispatch policy is the only thing that changes between the modes:
32 // DispatchInline makes the call in the connection's own domain (no spawn at
33 // all; the deterministic mode), DispatchSpawned hands it to a pool worker that
34 // makes the same call in its own domain and its own request arena.
35 36 import (
37 "moxielang.dev/pkg/mxutil"
38 "bufio"
39 "fmt"
40 "io"
41 "net"
42 "os"
43 "strconv"
44 "time"
45 "unsafe"
46 47 "runtime"
48 )
49 50 // The shell and a pool worker exchange one MESSAGE PER SLOT INDEX (chanpool.mx):
51 // the shell writes the whole request into a preallocated shared slot and sends
52 // the index, the worker answers in the same slot and sends the index back. There
53 // is no message-kind stream any more - the int32-per-four-bytes packing that
54 // used to carry one was the workaround for a []byte not surviving a spawn
55 // channel, and that defect is fixed (the work log).
56 57 const (
58 DispatchInline = int32(0)
59 DispatchSpawned = int32(1)
60 )
61 62 // Arena scope ids for the attribution report (src/runtime/arena_scope.mx): a
63 // retained byte is charged to the phase of request handling that allocated it.
64 //
65 // An arena is tagged ONCE, when it enters a lifetime, and its allocations and
66 // its reclaim are both charged there - that is what makes allocated minus
67 // reclaimed the live bytes of a scope. 0 is deliberately unnamed: anything
68 // charged there was never given a scope, which is a diagnostic, not a bucket.
69 // The runtime names two of its own: ArenaScopeRoot (5) for the domain root, and
70 // this file names 6 for the request arena, whose whole point is that it is
71 // entered and reset once per request.
72 const (
73 ArenaScopeDefault = int32(0)
74 ArenaScopeDecode = int32(1)
75 ArenaScopeHandler = int32(2)
76 ArenaScopeWrite = int32(3)
77 ArenaScopeConn = int32(4)
78 ArenaScopeRequest = int32(6)
79 )
80 81 // chanRequestArenaBytes is the arena each connection (and each pool worker)
82 // acquires for request processing. It is reused for every request on that
83 // connection and reset between them.
84 const chanRequestArenaBytes = uintptr(4 << 20)
85 86 // chanSovDrainBudget is how many queued sovereign groups the shell compacts at
87 // one request boundary.
88 //
89 // A group whose receiver outlives the request - the connection's bufio.Reader
90 // and bufio.Writer are the two on this path - keeps an allocation map that grows
91 // with every call made on it, and the map is only pruned by compaction. The
92 // runtime queues that compaction at the method boundary where the pressure
93 // appears, and something has to DRAIN it, exactly as a relay's event loop does.
94 // The request boundary is that safe point: no frame of a connection receiver is
95 // live and no sovereign arena is borrowed, because the previous request's call
96 // stack is gone and the arena has been reset. Without a drainer the queued group
97 // is never revisited, its data arena keeps growing regions, and the connection
98 // accumulates memory at a rate that has nothing to do with the request arena -
99 // measured at ~9MB over 1000 requests, in the connection's frame arena.
100 const chanSovDrainBudget = int32(4)
101 102 // Req is one fully decoded request. The shell built it in the request arena;
103 // the handler reads it and must not keep it.
104 type Req struct {
105 Method string
106 Path string
107 Proto string
108 Headers Header
109 Body []byte
110 }
111 112 // Resp is the response a handler returns. Its slices live in the request arena
113 // the shell entered for the call, which is why the shell can write the response
114 // after the call returns and then free the arena in one go.
115 type Resp struct {
116 Status int32
117 Headers Header
118 Body []byte
119 }
120 121 // ChanHandler is one call per request. The receiver is the application's main type
122 // - that is where its data access lives - and the argument is the decoded
123 // request.
124 type ChanHandler interface {
125 Handle(req *Req) (resp *Resp)
126 }
127 128 // chanRoute is one row of the router. The router is a plain slice built at
129 // startup and only read afterwards: no tree, no pointer graph, no closures.
130 type chanRoute struct {
131 pattern string
132 h ChanHandler
133 }
134 135 // ChanMux routes a request path to a handler through a plain table.
136 type ChanMux struct {
137 routes []chanRoute
138 }
139 140 func NewChanMux() (mux *ChanMux) {
141 return &ChanMux{}
142 }
143 144 // Handle registers a handler. A pattern ending in "/" matches that subtree
145 // (and "/" matches everything not matched more specifically); any other pattern
146 // matches exactly. The longest matching pattern wins.
147 func (mux *ChanMux) Handle(pat string, h ChanHandler) {
148 mux.routes = mxutil.Ensure(mux.routes, 1)
149 mux.routes = push(mux.routes, chanRoute{pattern: pat, h: h})
150 }
151 152 // Match returns the handler for reqPath and its route id, or nil.
153 func (mux *ChanMux) Match(reqPath string) (id int32, h ChanHandler) {
154 return chanMatchRoutes(mux.routes, reqPath)
155 }
156 157 // chanMatchRoutes is a free function because ChanMux is self-mutating and a
158 // ':=' inside a loop of one of its methods is rejected: loop scratch belongs in
159 // a function with its own frame arena.
160 func chanMatchRoutes(routes []chanRoute, reqPath string) (id int32, h ChanHandler) {
161 best := int32(-1)
162 id = -1
163 for i := 0; i < len(routes); i++ {
164 r := routes[i]
165 if !chanRouteMatch(r.pattern, reqPath) {
166 continue
167 }
168 if int32(len(r.pattern)) > best {
169 best = int32(len(r.pattern))
170 id = int32(i)
171 h = r.h
172 }
173 }
174 return id, h
175 }
176 177 // chanRouteMatch reports whether a registered pattern matches a request path.
178 func chanRouteMatch(pat, reqPath string) (ok bool) {
179 if len(pat) == 0 {
180 return false
181 }
182 if pat[len(pat)-1] == '/' {
183 if len(pat) == 1 {
184 return true
185 }
186 return mxutil.HasPrefix(reqPath, pat)
187 }
188 return pat == reqPath
189 }
190 191 // chanReadBody reads the whole request body. It is decoded once, into the
192 // request arena, so the handler is a single call and the body is freed with
193 // everything else when that call is done.
194 func chanReadBody(r io.Reader) (payload []byte, drained bool) {
195 buf := []byte{:4096}
196 for {
197 n, err := r.Read(buf)
198 if n > 0 {
199 payload = appendBytes(payload, buf[:n])
200 }
201 if err != nil {
202 return payload, err == io.EOF
203 }
204 }
205 }
206 207 func appendBytes(dst, src []byte) (out []byte) {
208 out = mxutil.Ensure(dst, len(src))
209 for i := 0; i < len(src); i++ {
210 out = push(out, src[i])
211 }
212 return out
213 }
214 215 // chanKeepAlive decides whether the connection survives this request. A body
216 // that was not fully read makes the framing unknowable, so it always closes.
217 func chanKeepAlive(req *Request, drained bool) (ok bool) {
218 if !drained {
219 return false
220 }
221 if !req.ProtoAtLeast(1, 1) {
222 return false
223 }
224 if req.Header.Get("Connection") == "close" {
225 return false
226 }
227 return true
228 }
229 230 // chanWriteResponse writes one response. It runs inside the request arena, so
231 // reading the handler's slices here is safe; the arena is reset after.
232 func chanWriteResponse(bw *bufio.Writer, resp *Resp, keepAlive bool) (ok bool) {
233 if resp == nil {
234 return false
235 }
236 status := resp.Status
237 if status == 0 {
238 status = StatusOK
239 }
240 bw.WriteString("HTTP/1.1 ")
241 bw.WriteString(strconv.Itoa(status))
242 bw.WriteByte(' ')
243 bw.Write(StatusText(status))
244 bw.WriteString("\r\n")
245 bw.WriteString("Content-Length: ")
246 bw.WriteString(strconv.Itoa(int32(len(resp.Body))))
247 bw.WriteString("\r\n")
248 if keepAlive {
249 bw.WriteString("Connection: keep-alive\r\n")
250 } else {
251 bw.WriteString("Connection: close\r\n")
252 }
253 if resp.Headers != nil {
254 for k, vv := range resp.Headers {
255 for _, v := range vv {
256 bw.WriteString(k)
257 bw.WriteString(": ")
258 bw.Write(v)
259 bw.WriteString("\r\n")
260 }
261 }
262 }
263 bw.WriteString("\r\n")
264 if len(resp.Body) > 0 {
265 bw.Write(resp.Body)
266 }
267 return true
268 }
269 270 // chanServeRequest serves one parsed request: make the one handler call and
271 // write the response.
272 //
273 // It does NOT enter or reset the arena. The request arena is opened and closed
274 // once per request by chanHandleOne, which is the boundary - a second enter and
275 // reset here used to be harmless only because both exits were idempotent. One
276 // boundary is what makes the abort paths (a parse failure, a missing route, a
277 // client that disconnects) and the normal path take the same exit and the same
278 // compaction drain.
279 func chanServeRequest(bw *bufio.Writer, req *Request, routeID int32, h ChanHandler, pool *chanPool) (keepAlive bool) {
280 prevScope := runtime.SetArenaScope(ArenaScopeHandler)
281 282 rq := &Req{
283 Method: req.Method,
284 Path: req.URL.Path,
285 Proto: req.Proto,
286 Headers: req.Header,
287 }
288 payload, drained := chanReadBody(req.Body)
289 rq.Body = payload
290 keep := chanKeepAlive(req, drained)
291 292 var resp *Resp
293 if pool != nil {
294 // The worker decodes the request into ITS request arena and makes the
295 // same single call there; the response it streams back is decoded here,
296 // in this request's arena.
297 resp = pool.call(routeID, rq)
298 } else {
299 resp = h.Handle(rq)
300 }
301 runtime.SetArenaScope(ArenaScopeWrite)
302 wrote := chanWriteResponse(bw, resp, keep)
303 runtime.SetArenaScope(prevScope)
304 return keep && wrote
305 }
306 307 // ChanServe accepts connections on addr and serves them one at a time, in this
308 // domain: no spawn anywhere. A connection loops requests until it is closed,
309 // which is where keep-alive lives.
310 func ChanServe(addr string, mux *ChanMux) (err error) {
311 return ChanServeMode(addr, mux, DispatchInline, 0)
312 }
313 314 // ChanServeMode is ChanServe with the dispatch policy named.
315 func ChanServeMode(addr string, mux *ChanMux, mode int32, workers int32) (err error) {
316 return ChanServeTimeout(addr, mux, mode, workers, 0)
317 }
318 319 // ChanServeTimeout is ChanServeMode with an idle deadline: a connection that
320 // sends nothing for that long is closed. Zero means no deadline, which is what a
321 // test wants; a deployment sets one so a silent client cannot hold the
322 // single-domain loop forever.
323 func ChanServeTimeout(addr string, mux *ChanMux, mode int32, workers int32, idle time.Duration) (err error) {
324 var pool *chanPool
325 if mode == DispatchSpawned {
326 n := workers
327 if n < 1 {
328 n = 1
329 }
330 // The table and the slot ring are shared by address, not by fork: a
331 // domain is a thread in this process, so an ordinary pointer reaches
332 // the same memory. A package global would not survive the boundary -
333 // package variables are thread-local and a new domain starts with
334 // zeroed TLS - so the two addresses travel as spawn arguments and the
335 // worker installs them in its own copy. The ring is MAP_SHARED and
336 // already faulted, so the shell's writes after the spawn are visible.
337 chanGlobalMux = mux
338 chanSlotBuf = runtime.SharedBuffer(chanSlotCount * chanSlotBytes)
339 chanSlotPrefault()
340 slotPtr := uintptr(unsafe.Pointer(unsafe.SliceData(chanSlotBuf)))
341 muxPtr := uintptr(unsafe.Pointer(mux))
342 pool = &chanPool{mux: mux}
343 for i := int32(0); i < n; i++ {
344 j := chan int32{}
345 r := chan int32{}
346 pool.jobs = mxutil.Ensure(pool.jobs, 1)
347 pool.jobs = push(pool.jobs, j)
348 pool.results = mxutil.Ensure(pool.results, 1)
349 pool.results = push(pool.results, r)
350 closed := spawn(chanWorkerLoop, j, r, slotPtr, muxPtr)
351 pool.breakers = mxutil.Ensure(pool.breakers, 1)
352 pool.breakers = push(pool.breakers, closed)
353 }
354 }
355 ln, lerr := net.Listen("tcp", addr)
356 if lerr != nil {
357 pool.closeBreakers()
358 return lerr
359 }
360 for {
361 if aerr := serveNextConn(ln, mux, pool, idle); aerr != nil {
362 pool.closeBreakers()
363 return aerr
364 }
365 }
366 }
367 368 // serveNextConn accepts ONE connection and serves it to the end, in its own
369 // frame.
370 //
371 // This is the same rule as chanHandleOne, one scope up: a connection is one
372 // call whose arena dies when the connection does. Accepting inside the accept
373 // loop instead put the connection object in the LOOP's frame arena, which lives
374 // for the life of the process, and every mutating method on that connection
375 // (Read, Write, Close, the deadlines) then created a sovereign group bound to a
376 // process-lifetime arena. Nothing releases such a group, so each connection left
377 // its groups and their arenas behind: measured as six immortal groups and
378 // ~0.4MB per connection, independent of how many requests the connection served.
379 // The connection object is also RELOCATED into the accepting frame at every
380 // iteration, so the loop's own arena grew per connection as well.
381 func serveNextConn(ln net.Listener, mux *ChanMux, pool *chanPool, idle time.Duration) (err error) {
382 c, aerr := ln.Accept()
383 if aerr != nil {
384 return aerr
385 }
386 serveChanConn(c, mux, pool, idle)
387 return nil
388 }
389 390 // serveChanConn is the shell: it owns the socket for the life of the
391 // connection and calls chanHandleOne once per request. Nothing per-request
392 // survives here except the keep-alive decision.
393 func serveChanConn(c net.Conn, mux *ChanMux, pool *chanPool, idle time.Duration) {
394 br := bufio.NewReader(c)
395 bw := bufio.NewWriter(c)
396 // One request arena for this connection, reused request after request.
397 // ArenaReset is what makes "requests do not accumulate memory" true: the
398 // arena's offset goes back to the start and its extra regions are unmapped.
399 // Tag the arena BEFORE it is acquired: ArenaAcquire is where an arena's
400 // lifetime starts, so that is where its scope is stamped, and every byte it
401 // ever allocates or reclaims is then charged to the request phase instead of
402 // to whatever scope happened to be current at reset time.
403 prevScope := runtime.SetArenaScope(ArenaScopeRequest)
404 arena := runtime.ArenaAcquire(chanRequestArenaBytes)
405 runtime.SetArenaScope(prevScope)
406 keep := true
407 for keep {
408 keep = chanHandleOne(c, br, bw, mux, pool, arena, idle)
409 bw.Flush()
410 // A scope boundary also ends the per-request garbage of the scopes that
411 // survive it: drain the deferred compaction of the connection's own
412 // sovereign receivers here, where nothing of the request is live.
413 runtime.SovDrainCompactions(chanSovDrainBudget)
414 }
415 runtime.ArenaRelease(arena)
416 c.Close()
417 }
418 419 // chanHandleOne is ONE request, start to finish, in its own frame: read it,
420 // route it, decode it into the request arena, make the one handler call, write
421 // the response. Everything it allocates OUTSIDE the request arena dies with
422 // this call - which matters, because the parsed Request is relocated into the
423 // caller's frame at return: with the loop inlined into the connection function
424 // that frame lived as long as the connection, and every request's Request
425 // (headers and all) accumulated there at ~13kB a request. A request is one
426 // function call, and its memory goes with it.
427 // chanHandleOne is the request's ONE arena boundary: decode, handler call,
428 // response write, and then the single exit every path shares - the reset, the
429 // sovereign-group teardown it performs (src/runtime/alloc.mx arenaReleaseGroups)
430 // and, in the caller's loop, the compaction drain.
431 //
432 // The Header map is born in this arena, so its owner arena is the one this call
433 // resets - the map's own answer about whose lifetime its buckets belong to is
434 // then correct and the buckets are freed with the request.
435 func chanHandleOne(c net.Conn, br *bufio.Reader, bw *bufio.Writer, mux *ChanMux, pool *chanPool, arena *runtime.Arena, idle time.Duration) (keep bool) {
436 runtime.ManualArenaEnter(arena)
437 keep = chanHandleInner(c, br, bw, mux, pool, arena, idle)
438 runtime.ManualArenaExit(arena)
439 runtime.ArenaReset(arena)
440 return keep
441 }
442 443 func chanHandleInner(c net.Conn, br *bufio.Reader, bw *bufio.Writer, mux *ChanMux, pool *chanPool, arena *runtime.Arena, idle time.Duration) (keep bool) {
444 if idle > 0 {
445 c.SetReadDeadline(time.Now().Add(idle))
446 }
447 prevScope := runtime.SetArenaScope(ArenaScopeDecode)
448 req, rerr := readRequest(br)
449 runtime.SetArenaScope(prevScope)
450 if rerr != nil {
451 if rerr == io.EOF || rerr == io.ErrUnexpectedEOF {
452 return false
453 }
454 // A parse failure is the client's, not the handler's: answer 400 and
455 // close, because the framing is no longer known to be sound.
456 chanWritePlain(bw, StatusBadRequest)
457 return false
458 }
459 if idle > 0 {
460 c.SetWriteDeadline(time.Now().Add(idle))
461 }
462 id, h := mux.Match(req.URL.Path)
463 if h == nil {
464 chanWritePlain(bw, StatusNotFound)
465 return false
466 }
467 return chanServeRequest(bw, req, id, h, pool)
468 }
469 470 // chanWritePlain writes a bodyless status response, for the shell's own errors.
471 func chanWritePlain(bw *bufio.Writer, status int32) {
472 bw.WriteString("HTTP/1.1 ")
473 bw.WriteString(strconv.Itoa(status))
474 bw.WriteByte(' ')
475 bw.Write(StatusText(status))
476 bw.WriteString("\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
477 }
478 479 var errChanNoRoute error
480 481 // chanReportAbort says why an exchange produced no response. A closed
482 // connection is not a diagnosis.
483 func chanReportAbort(cause error) {
484 fmt.Fprintf(os.Stderr, "http: channel handler aborted: %v\n", cause)
485 }
486