package http // The handler path: one function call per request, in one arena. // // The classic path hands a handler a ResponseWriter and a *Request, so the // handler owns the socket for the duration of the call and the port had to fake // what Go does with closures (HandlerFunc called through a pointer to the func // value; finishServe taking **response to stand in for a deferred closure). // // This path splits it the other way round: // // - the SHELL owns the socket, the framing, the accept loop, the keep-alive // loop and the deadlines. It decodes the request into a Req. // - a HANDLER is one call: `Handle(req *Req) (resp *Resp)`. It is a method on // the application's main type, so the data access lives where the data is. // It does no io, holds no sockets, spawns nothing and keeps no state // between requests. // // Every request is processed inside ONE ARENA that the shell enters and then // resets: the decoded request, everything the handler allocates and the // response it returns all live there, and the whole lot is freed at once when // the call is done. Requests cannot accumulate memory - the only thing that // survives a request is what the application deliberately stores in its own // state (a log entry in its database or file), which is its business, not the // shell's. // // A request that never completes - the client disconnects, a read fails, the // idle deadline expires - never calls the handler and its arena is reset, so // there is nothing to cancel and nothing to leak. // // Dispatch policy is the only thing that changes between the modes: // DispatchInline makes the call in the connection's own domain (no spawn at // all; the deterministic mode), DispatchSpawned hands it to a pool worker that // makes the same call in its own domain and its own request arena. import ( "moxielang.dev/pkg/mxutil" "bufio" "fmt" "io" "net" "os" "strconv" "time" "unsafe" "runtime" ) // The shell and a pool worker exchange one MESSAGE PER SLOT INDEX (chanpool.mx): // the shell writes the whole request into a preallocated shared slot and sends // the index, the worker answers in the same slot and sends the index back. There // is no message-kind stream any more - the int32-per-four-bytes packing that // used to carry one was the workaround for a []byte not surviving a spawn // channel, and that defect is fixed (the work log). const ( DispatchInline = int32(0) DispatchSpawned = int32(1) ) // Arena scope ids for the attribution report (src/runtime/arena_scope.mx): a // retained byte is charged to the phase of request handling that allocated it. // // An arena is tagged ONCE, when it enters a lifetime, and its allocations and // its reclaim are both charged there - that is what makes allocated minus // reclaimed the live bytes of a scope. 0 is deliberately unnamed: anything // charged there was never given a scope, which is a diagnostic, not a bucket. // The runtime names two of its own: ArenaScopeRoot (5) for the domain root, and // this file names 6 for the request arena, whose whole point is that it is // entered and reset once per request. const ( ArenaScopeDefault = int32(0) ArenaScopeDecode = int32(1) ArenaScopeHandler = int32(2) ArenaScopeWrite = int32(3) ArenaScopeConn = int32(4) ArenaScopeRequest = int32(6) ) // chanRequestArenaBytes is the arena each connection (and each pool worker) // acquires for request processing. It is reused for every request on that // connection and reset between them. const chanRequestArenaBytes = uintptr(4 << 20) // chanSovDrainBudget is how many queued sovereign groups the shell compacts at // one request boundary. // // A group whose receiver outlives the request - the connection's bufio.Reader // and bufio.Writer are the two on this path - keeps an allocation map that grows // with every call made on it, and the map is only pruned by compaction. The // runtime queues that compaction at the method boundary where the pressure // appears, and something has to DRAIN it, exactly as a relay's event loop does. // The request boundary is that safe point: no frame of a connection receiver is // live and no sovereign arena is borrowed, because the previous request's call // stack is gone and the arena has been reset. Without a drainer the queued group // is never revisited, its data arena keeps growing regions, and the connection // accumulates memory at a rate that has nothing to do with the request arena - // measured at ~9MB over 1000 requests, in the connection's frame arena. const chanSovDrainBudget = int32(4) // Req is one fully decoded request. The shell built it in the request arena; // the handler reads it and must not keep it. type Req struct { Method string Path string Proto string Headers Header Body []byte } // Resp is the response a handler returns. Its slices live in the request arena // the shell entered for the call, which is why the shell can write the response // after the call returns and then free the arena in one go. type Resp struct { Status int32 Headers Header Body []byte } // ChanHandler is one call per request. The receiver is the application's main type // - that is where its data access lives - and the argument is the decoded // request. type ChanHandler interface { Handle(req *Req) (resp *Resp) } // chanRoute is one row of the router. The router is a plain slice built at // startup and only read afterwards: no tree, no pointer graph, no closures. type chanRoute struct { pattern string h ChanHandler } // ChanMux routes a request path to a handler through a plain table. type ChanMux struct { routes []chanRoute } func NewChanMux() (mux *ChanMux) { return &ChanMux{} } // Handle registers a handler. A pattern ending in "/" matches that subtree // (and "/" matches everything not matched more specifically); any other pattern // matches exactly. The longest matching pattern wins. func (mux *ChanMux) Handle(pat string, h ChanHandler) { mux.routes = mxutil.Ensure(mux.routes, 1) mux.routes = push(mux.routes, chanRoute{pattern: pat, h: h}) } // Match returns the handler for reqPath and its route id, or nil. func (mux *ChanMux) Match(reqPath string) (id int32, h ChanHandler) { return chanMatchRoutes(mux.routes, reqPath) } // chanMatchRoutes is a free function because ChanMux is self-mutating and a // ':=' inside a loop of one of its methods is rejected: loop scratch belongs in // a function with its own frame arena. func chanMatchRoutes(routes []chanRoute, reqPath string) (id int32, h ChanHandler) { best := int32(-1) id = -1 for i := 0; i < len(routes); i++ { r := routes[i] if !chanRouteMatch(r.pattern, reqPath) { continue } if int32(len(r.pattern)) > best { best = int32(len(r.pattern)) id = int32(i) h = r.h } } return id, h } // chanRouteMatch reports whether a registered pattern matches a request path. func chanRouteMatch(pat, reqPath string) (ok bool) { if len(pat) == 0 { return false } if pat[len(pat)-1] == '/' { if len(pat) == 1 { return true } return mxutil.HasPrefix(reqPath, pat) } return pat == reqPath } // chanReadBody reads the whole request body. It is decoded once, into the // request arena, so the handler is a single call and the body is freed with // everything else when that call is done. func chanReadBody(r io.Reader) (payload []byte, drained bool) { buf := []byte{:4096} for { n, err := r.Read(buf) if n > 0 { payload = appendBytes(payload, buf[:n]) } if err != nil { return payload, err == io.EOF } } } func appendBytes(dst, src []byte) (out []byte) { out = mxutil.Ensure(dst, len(src)) for i := 0; i < len(src); i++ { out = push(out, src[i]) } return out } // chanKeepAlive decides whether the connection survives this request. A body // that was not fully read makes the framing unknowable, so it always closes. func chanKeepAlive(req *Request, drained bool) (ok bool) { if !drained { return false } if !req.ProtoAtLeast(1, 1) { return false } if req.Header.Get("Connection") == "close" { return false } return true } // chanWriteResponse writes one response. It runs inside the request arena, so // reading the handler's slices here is safe; the arena is reset after. func chanWriteResponse(bw *bufio.Writer, resp *Resp, keepAlive bool) (ok bool) { if resp == nil { return false } status := resp.Status if status == 0 { status = StatusOK } bw.WriteString("HTTP/1.1 ") bw.WriteString(strconv.Itoa(status)) bw.WriteByte(' ') bw.Write(StatusText(status)) bw.WriteString("\r\n") bw.WriteString("Content-Length: ") bw.WriteString(strconv.Itoa(int32(len(resp.Body)))) bw.WriteString("\r\n") if keepAlive { bw.WriteString("Connection: keep-alive\r\n") } else { bw.WriteString("Connection: close\r\n") } if resp.Headers != nil { for k, vv := range resp.Headers { for _, v := range vv { bw.WriteString(k) bw.WriteString(": ") bw.Write(v) bw.WriteString("\r\n") } } } bw.WriteString("\r\n") if len(resp.Body) > 0 { bw.Write(resp.Body) } return true } // chanServeRequest serves one parsed request: make the one handler call and // write the response. // // It does NOT enter or reset the arena. The request arena is opened and closed // once per request by chanHandleOne, which is the boundary - a second enter and // reset here used to be harmless only because both exits were idempotent. One // boundary is what makes the abort paths (a parse failure, a missing route, a // client that disconnects) and the normal path take the same exit and the same // compaction drain. func chanServeRequest(bw *bufio.Writer, req *Request, routeID int32, h ChanHandler, pool *chanPool) (keepAlive bool) { prevScope := runtime.SetArenaScope(ArenaScopeHandler) rq := &Req{ Method: req.Method, Path: req.URL.Path, Proto: req.Proto, Headers: req.Header, } payload, drained := chanReadBody(req.Body) rq.Body = payload keep := chanKeepAlive(req, drained) var resp *Resp if pool != nil { // The worker decodes the request into ITS request arena and makes the // same single call there; the response it streams back is decoded here, // in this request's arena. resp = pool.call(routeID, rq) } else { resp = h.Handle(rq) } runtime.SetArenaScope(ArenaScopeWrite) wrote := chanWriteResponse(bw, resp, keep) runtime.SetArenaScope(prevScope) return keep && wrote } // ChanServe accepts connections on addr and serves them one at a time, in this // domain: no spawn anywhere. A connection loops requests until it is closed, // which is where keep-alive lives. func ChanServe(addr string, mux *ChanMux) (err error) { return ChanServeMode(addr, mux, DispatchInline, 0) } // ChanServeMode is ChanServe with the dispatch policy named. func ChanServeMode(addr string, mux *ChanMux, mode int32, workers int32) (err error) { return ChanServeTimeout(addr, mux, mode, workers, 0) } // ChanServeTimeout is ChanServeMode with an idle deadline: a connection that // sends nothing for that long is closed. Zero means no deadline, which is what a // test wants; a deployment sets one so a silent client cannot hold the // single-domain loop forever. func ChanServeTimeout(addr string, mux *ChanMux, mode int32, workers int32, idle time.Duration) (err error) { var pool *chanPool if mode == DispatchSpawned { n := workers if n < 1 { n = 1 } // The table and the slot ring are shared by address, not by fork: a // domain is a thread in this process, so an ordinary pointer reaches // the same memory. A package global would not survive the boundary - // package variables are thread-local and a new domain starts with // zeroed TLS - so the two addresses travel as spawn arguments and the // worker installs them in its own copy. The ring is MAP_SHARED and // already faulted, so the shell's writes after the spawn are visible. chanGlobalMux = mux chanSlotBuf = runtime.SharedBuffer(chanSlotCount * chanSlotBytes) chanSlotPrefault() slotPtr := uintptr(unsafe.Pointer(unsafe.SliceData(chanSlotBuf))) muxPtr := uintptr(unsafe.Pointer(mux)) pool = &chanPool{mux: mux} for i := int32(0); i < n; i++ { j := chan int32{} r := chan int32{} pool.jobs = mxutil.Ensure(pool.jobs, 1) pool.jobs = push(pool.jobs, j) pool.results = mxutil.Ensure(pool.results, 1) pool.results = push(pool.results, r) closed := spawn(chanWorkerLoop, j, r, slotPtr, muxPtr) pool.breakers = mxutil.Ensure(pool.breakers, 1) pool.breakers = push(pool.breakers, closed) } } ln, lerr := net.Listen("tcp", addr) if lerr != nil { pool.closeBreakers() return lerr } for { if aerr := serveNextConn(ln, mux, pool, idle); aerr != nil { pool.closeBreakers() return aerr } } } // serveNextConn accepts ONE connection and serves it to the end, in its own // frame. // // This is the same rule as chanHandleOne, one scope up: a connection is one // call whose arena dies when the connection does. Accepting inside the accept // loop instead put the connection object in the LOOP's frame arena, which lives // for the life of the process, and every mutating method on that connection // (Read, Write, Close, the deadlines) then created a sovereign group bound to a // process-lifetime arena. Nothing releases such a group, so each connection left // its groups and their arenas behind: measured as six immortal groups and // ~0.4MB per connection, independent of how many requests the connection served. // The connection object is also RELOCATED into the accepting frame at every // iteration, so the loop's own arena grew per connection as well. func serveNextConn(ln net.Listener, mux *ChanMux, pool *chanPool, idle time.Duration) (err error) { c, aerr := ln.Accept() if aerr != nil { return aerr } serveChanConn(c, mux, pool, idle) return nil } // serveChanConn is the shell: it owns the socket for the life of the // connection and calls chanHandleOne once per request. Nothing per-request // survives here except the keep-alive decision. func serveChanConn(c net.Conn, mux *ChanMux, pool *chanPool, idle time.Duration) { br := bufio.NewReader(c) bw := bufio.NewWriter(c) // One request arena for this connection, reused request after request. // ArenaReset is what makes "requests do not accumulate memory" true: the // arena's offset goes back to the start and its extra regions are unmapped. // Tag the arena BEFORE it is acquired: ArenaAcquire is where an arena's // lifetime starts, so that is where its scope is stamped, and every byte it // ever allocates or reclaims is then charged to the request phase instead of // to whatever scope happened to be current at reset time. prevScope := runtime.SetArenaScope(ArenaScopeRequest) arena := runtime.ArenaAcquire(chanRequestArenaBytes) runtime.SetArenaScope(prevScope) keep := true for keep { keep = chanHandleOne(c, br, bw, mux, pool, arena, idle) bw.Flush() // A scope boundary also ends the per-request garbage of the scopes that // survive it: drain the deferred compaction of the connection's own // sovereign receivers here, where nothing of the request is live. runtime.SovDrainCompactions(chanSovDrainBudget) } runtime.ArenaRelease(arena) c.Close() } // chanHandleOne is ONE request, start to finish, in its own frame: read it, // route it, decode it into the request arena, make the one handler call, write // the response. Everything it allocates OUTSIDE the request arena dies with // this call - which matters, because the parsed Request is relocated into the // caller's frame at return: with the loop inlined into the connection function // that frame lived as long as the connection, and every request's Request // (headers and all) accumulated there at ~13kB a request. A request is one // function call, and its memory goes with it. // chanHandleOne is the request's ONE arena boundary: decode, handler call, // response write, and then the single exit every path shares - the reset, the // sovereign-group teardown it performs (src/runtime/alloc.mx arenaReleaseGroups) // and, in the caller's loop, the compaction drain. // // The Header map is born in this arena, so its owner arena is the one this call // resets - the map's own answer about whose lifetime its buckets belong to is // then correct and the buckets are freed with the request. func chanHandleOne(c net.Conn, br *bufio.Reader, bw *bufio.Writer, mux *ChanMux, pool *chanPool, arena *runtime.Arena, idle time.Duration) (keep bool) { runtime.ManualArenaEnter(arena) keep = chanHandleInner(c, br, bw, mux, pool, arena, idle) runtime.ManualArenaExit(arena) runtime.ArenaReset(arena) return keep } func chanHandleInner(c net.Conn, br *bufio.Reader, bw *bufio.Writer, mux *ChanMux, pool *chanPool, arena *runtime.Arena, idle time.Duration) (keep bool) { if idle > 0 { c.SetReadDeadline(time.Now().Add(idle)) } prevScope := runtime.SetArenaScope(ArenaScopeDecode) req, rerr := readRequest(br) runtime.SetArenaScope(prevScope) if rerr != nil { if rerr == io.EOF || rerr == io.ErrUnexpectedEOF { return false } // A parse failure is the client's, not the handler's: answer 400 and // close, because the framing is no longer known to be sound. chanWritePlain(bw, StatusBadRequest) return false } if idle > 0 { c.SetWriteDeadline(time.Now().Add(idle)) } id, h := mux.Match(req.URL.Path) if h == nil { chanWritePlain(bw, StatusNotFound) return false } return chanServeRequest(bw, req, id, h, pool) } // chanWritePlain writes a bodyless status response, for the shell's own errors. func chanWritePlain(bw *bufio.Writer, status int32) { bw.WriteString("HTTP/1.1 ") bw.WriteString(strconv.Itoa(status)) bw.WriteByte(' ') bw.Write(StatusText(status)) bw.WriteString("\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") } var errChanNoRoute error // chanReportAbort says why an exchange produced no response. A closed // connection is not a diagnosis. func chanReportAbort(cause error) { fmt.Fprintf(os.Stderr, "http: channel handler aborted: %v\n", cause) }