package http // Spawned dispatch: the same one-call-per-request handler, run by a fixed pool // of worker routines instead of in the connection's domain. // // The pool exists because a spawn is a fork, not a coroutine: a worker is an OS // thread with its own domain and its own arenas, so one spawn per request would // cost a thread per request (measured by tests/netsmoke/spawncost). // // The boundary carries a QUEUE-OWNED RING OF PREALLOCATED SLOTS, handed off by // index. The slot buffer is mapped MAP_SHARED before the workers are spawned, so // the parent writes one message into slot i and sends i; the worker reads the // bytes in place and answers in the same slot, sending i back. One message per // slot, one copy at a named site (chanSlotPutReq / chanSlotPutResp), and no // allocation in the steady state - the shell reuses its own slot for every // request on a connection, so the request body costs no bytes after warm-up. // // A domain is a thread, so the ring's address is the same in both domains; it // is passed to the worker as a spawn argument because a package global is // thread-local and the worker starts with zeroed TLS. // // Why not send the encoded message as a []byte on a chan []byte? That allocates // a fresh slice per message, and the point of the ring is that the steady state // allocates nothing. // // The slot count is sized by MEASURED in-flight concurrency, not by connections // times slots. The shell serves one connection at a time and blocks on the // response, so at most one request is in flight at any instant (measured: a // counter over the pool call sites reported max 1 with one connection); four // slots give the handoff headroom without the "connections times slots" sizing // that got the first ring attempt reverted. // // The router table is read by the workers through the address the shell passes // at spawn: it is built at startup and only read afterwards, so the sharing is // read-only and needs no copy. import ( "errors" "runtime" "unsafe" ) // chanGlobalMux is the table the pool workers read. The shell assigns its own // copy; each worker installs the address it received at spawn. var chanGlobalMux *ChanMux func chanRouteHandler(id int32) (h ChanHandler) { if chanGlobalMux == nil || id < 0 || id >= int32(len(chanGlobalMux.routes)) { return nil } return chanGlobalMux.routes[id].h } // --- the slot ring --- // Slot geometry. slotBytes bounds ONE message (request or response): 1MB, and a // frame that does not fit panics by name rather than truncating. The buffer is // mmap'd shared and lazily faulted, so the committed size is the whole mapping // and the resident size is only the pages a message actually touches. const ( // Four slots, 64KB each. The slot count comes from the measured in-flight // concurrency (one: the shell is serial and blocks on the reply); the slot // SIZE comes from the measured message size - a fixture request is a few // hundred bytes, so 64KB is two orders of magnitude of headroom. It is // deliberately small: the ring is MAP_SHARED and its pages are resident, and // 4 x 1MB made the no-accumulation unit measure the mapping being faulted // rather than the steady state (+2096kB over 400 exchanges against a 2048kB // threshold). A frame that does not fit panics by name. chanSlotCount = int32(4) chanSlotBytes = int32(64 << 10) chanSlotFrame = int32(32) // fixed header words: len, status, route, 3 lens, bodylen, nheaders ) // chanSlotBuf is the shared ring. The shell creates it; each worker // reconstructs the same view from the address it received at spawn. var chanSlotBuf []byte // chanSlotInFlightMax records the largest number of pool calls in flight, the // measurement the slot count is sized from. var chanSlotInFlight int32 var chanSlotInFlightMax int32 // chanSlotBase returns the start offset of slot i. func chanSlotBase(i int32) (off int32) { return i * chanSlotBytes } func chanSlotPutI32(b []byte, off, v int32) { b[off] = byte(v) b[off+1] = byte(v >> 8) b[off+2] = byte(v >> 16) b[off+3] = byte(v >> 24) } func chanSlotGetI32(b []byte, off int32) (v int32) { return int32(b[off]) | int32(b[off+1])<<8 | int32(b[off+2])<<16 | int32(b[off+3])<<24 } // chanSlotPutRaw writes a length prefix and the bytes: one of the two copy sites. func chanSlotPutRaw(b []byte, off int32, s []byte) (next int32) { n := int32(len(s)) chanSlotPutI32(b, off, n) off = off + 4 for i := int32(0); i < n; i++ { b[off+i] = s[i] } return off + n } // chanSlotGetRaw reads a length prefix and copies the bytes into the caller's // arena (the worker decodes into its request arena, which the shell resets). func chanSlotGetRaw(b []byte, off int32) (s []byte, next int32) { n := chanSlotGetI32(b, off) off = off + 4 s = []byte{:n} for i := int32(0); i < n; i++ { s[i] = b[off+i] } return s, off + n } func chanSlotPutHeaders(b []byte, off int32, h Header) (next int32) { off = off n := int32(0) if h != nil { n = int32(len(h)) } chanSlotPutI32(b, off, n) off = off + 4 for k, vv := range h { off = chanSlotPutRaw(b, off, k) chanSlotPutI32(b, off, int32(len(vv))) off = off + 4 for i := int32(0); i < len(vv); i++ { off = chanSlotPutRaw(b, off, vv[i]) } } return off } func chanSlotGetHeaders(b []byte, off int32) (h Header, next int32) { n := chanSlotGetI32(b, off) off = off + 4 if n == 0 { return nil, off } h = Header{} for i := int32(0); i < n; i++ { var k []byte k, off = chanSlotGetRaw(b, off) vn := chanSlotGetI32(b, off) off = off + 4 vv := [][]byte{:vn} for j := int32(0); j < vn; j++ { vv[j], off = chanSlotGetRaw(b, off) } h[k] = vv } return h, off } // chanSlotPutReq is THE request copy: the shell's message into its slot. // chanSlotWindow is a VIEW of one slot in the shared ring. // // A bounded sub-slice (buf[a:b]) allocates and copies in this language, and a // copy is the one thing a shared-memory ring cannot have: the shell writes the // request into its private copy, the worker reads the untouched ring, and // chanSlotGetReq answers "decode failed" for every request. That is what // spawned mode did until round 279 - the manager accepted and read the request, // the four workers were alive and polling, and every frame arrived empty. // unsafe.Add is the only way to name the same bytes without copying them. func chanSlotWindow(base int32) (slot []byte) { if base < 0 || base+chanSlotBytes > int32(len(chanSlotBuf)) { panic("chanpool: slot window out of range") } p := unsafe.Add(unsafe.Pointer(unsafe.SliceData(chanSlotBuf)), uintptr(base)) return unsafe.Slice((*byte)(p), chanSlotBytes) } func chanSlotPutReq(slot []byte, routeID int32, rq *Req) (n int32) { off := chanSlotFrame off = chanSlotPutRaw(slot, off, rq.Method) off = chanSlotPutRaw(slot, off, rq.Path) off = chanSlotPutRaw(slot, off, rq.Proto) off = chanSlotPutRaw(slot, off, rq.Body) off = chanSlotPutHeaders(slot, off, rq.Headers) if off > int32(len(slot)) { panic("chanpool: request frame exceeds the slot") } chanSlotPutI32(slot, 0, off) chanSlotPutI32(slot, 4, 0) chanSlotPutI32(slot, 8, routeID) return off } // chanSlotGetReq decodes a request frame into the worker's request arena. func chanSlotGetReq(slot []byte) (routeID int32, rq *Req, ok bool) { n := chanSlotGetI32(slot, 0) if n <= chanSlotFrame || n > int32(len(slot)) { return -1, nil, false } routeID = chanSlotGetI32(slot, 8) off := chanSlotFrame rq = &Req{} rq.Method, off = chanSlotGetRaw(slot, off) rq.Path, off = chanSlotGetRaw(slot, off) rq.Proto, off = chanSlotGetRaw(slot, off) rq.Body, off = chanSlotGetRaw(slot, off) rq.Headers, off = chanSlotGetHeaders(slot, off) return routeID, rq, true } // chanSlotPutResp is THE response copy: the worker's message into the same slot. func chanSlotPutResp(slot []byte, resp *Resp) (n int32) { off := chanSlotFrame off = chanSlotPutRaw(slot, off, resp.Body) off = chanSlotPutHeaders(slot, off, resp.Headers) if off > int32(len(slot)) { panic("chanpool: response frame exceeds the slot") } chanSlotPutI32(slot, 0, off) chanSlotPutI32(slot, 4, resp.Status) chanSlotPutI32(slot, 8, 0) return off } // chanSlotPutAbort writes a bodyless abort frame with a reason. func chanSlotPutAbort(slot []byte, reason []byte) (n int32) { off := chanSlotFrame off = chanSlotPutRaw(slot, off, reason) chanSlotPutI32(slot, 0, off) chanSlotPutI32(slot, 4, 0) chanSlotPutI32(slot, 8, -1) return off } // chanSlotGetResp decodes a response frame into the shell's request arena. func chanSlotGetResp(slot []byte) (resp *Resp, ok bool) { n := chanSlotGetI32(slot, 0) if n <= chanSlotFrame || n > int32(len(slot)) { return nil, false } status := chanSlotGetI32(slot, 4) off := chanSlotFrame if status == 0 && chanSlotGetI32(slot, 8) == -1 { reason, _ := chanSlotGetRaw(slot, off) chanReportAbort(errors.New(reason)) return nil, false } resp = &Resp{} resp.Status = status resp.Body, off = chanSlotGetRaw(slot, off) resp.Headers, off = chanSlotGetHeaders(slot, off) return resp, true } // chanWorkerLoop is one pool worker. It owns no socket and no connection state: // it decodes a request slot into ITS request arena, makes the route's one // handler call there, writes the response back into the same slot and resets the // arena, so a worker that served a million requests holds no more memory than // one that served one. func chanWorkerLoop(jobs chan int32, results chan int32, slotPtr, muxPtr uintptr) (closed chan struct{}) { // The shell's package globals are not this domain's: package variables are // thread-local and a new domain starts with zeroed TLS. The two addresses // travel as spawn arguments - the ring is process memory and the table is // read-only after startup - and are installed before the first receive. chanSlotBuf = unsafe.Slice((*byte)(unsafe.Pointer(slotPtr)), chanSlotCount*chanSlotBytes) chanGlobalMux = (*ChanMux)(unsafe.Pointer(muxPtr)) prevScope := runtime.SetArenaScope(ArenaScopeRequest) arena := runtime.ArenaAcquire(chanRequestArenaBytes) runtime.SetArenaScope(prevScope) done := false for !done { // EVERY allocation of an iteration belongs to the iteration, so the // request arena is entered before the receive that starts it. The // decode and the handler call were the visible half: with only those // inside, the worker still grew the frame arena it inherited from // spawn - which lives for the life of the process - at ~615B a request // (measured: 50kB after 100 requests, 615kB after 800), and that // overflowed into a chained 64MB region, which the phase-8 // no-accumulation unit saw as +2096kB over its 400 exchanges. The // comment below is the rule: one iteration, one arena boundary. runtime.ManualArenaEnter(arena) // The worker serves its inbox and watches its termination breaker in // the same select: a shutdown must not wait for the next request. var i int32 select { case <-closed: runtime.ManualArenaExit(arena) runtime.ArenaReset(arena) return closed case j := <-jobs: i = j } if i < 0 { runtime.ManualArenaExit(arena) runtime.ArenaReset(arena) break } if i >= chanSlotCount { panic("chanpool: slot index out of range") } slot := chanSlotWindow(chanSlotBase(i)) routeID, rq, ok := chanSlotGetReq(slot) h := chanRouteHandler(routeID) var resp *Resp if ok && h != nil { resp = h.Handle(rq) } if resp == nil { chanSlotPutAbort(slot, []byte("http: channel handler: no route")) } else { chanSlotPutResp(slot, resp) } // Answer before the reset: the shell only ever reads the slot, so it can // take the reply while the worker's arena is still current, and nothing // of the request outlives this line. results <- i runtime.ManualArenaExit(arena) runtime.ArenaReset(arena) // The worker is a request-scope server: drain the deferred compaction // of its own long-lived sovereign receivers at the same boundary the // connection loop uses. runtime.SovDrainCompactions(chanSovDrainBudget) } runtime.ArenaRelease(arena) return closed } // chanPool is a fixed set of workers with their own queues, plus the slot ring // they share with the shell. next rotates so a connection does not always land // on the same worker. type chanPool struct { mux *ChanMux jobs []chan int32 results []chan int32 breakers []chan struct{} next int32 } // closeBreakers ends every worker this pool started. The spawning frame owns // its children: a return from ChanServeTimeout must not leave a domain behind, // which is why the breakers are kept rather than dropped at spawn. func (p *chanPool) closeBreakers() { if p == nil { return } for i := int32(0); i < int32(len(p.breakers)); i++ { close(p.breakers[i]) } p.breakers = nil } func (p *chanPool) pick() (i int32) { i = p.next % int32(len(p.jobs)) p.next = p.next + 1 return i } // call hands one decoded request to a worker through its slot and returns the // response the worker wrote back. The response's slices are decoded into the // CALLER's request arena, so the shell can write them and then free the arena. func (p *chanPool) call(routeID int32, rq *Req) (resp *Resp) { i := p.pick() chanSlotInFlight++ if chanSlotInFlight > chanSlotInFlightMax { chanSlotInFlightMax = chanSlotInFlight } slot := chanSlotWindow(chanSlotBase(i)) chanSlotPutReq(slot, routeID, rq) p.jobs[i] <- i j := <-p.results[i] if j < 0 || j >= chanSlotCount { panic("chanpool: slot index out of range") } out := chanSlotWindow(chanSlotBase(j)) resp, _ = chanSlotGetResp(out) chanSlotInFlight-- return resp } // chanSlotPrefault touches one byte of every page of the slot ring. // // The ring is MAP_SHARED and lazily faulted, so without this its pages are // faulted by the requests that use them: the first few hundred exchanges of a // process pay for the mapping, which reads as per-request retention (+2096kB // over 400 exchanges, against a 2048kB no-accumulation threshold that must not // be widened). A queue-owned ring is taken into service at startup, so its cost // belongs there, before the first request. func chanSlotPrefault() { if len(chanSlotBuf) == 0 { return } page := 4096 for off := 0; off < len(chanSlotBuf); off = off + page { chanSlotBuf[off] = 0 } } // ChanSlotMaxInFlight reports the largest number of pool calls that were ever in // flight, the measurement the slot count is sized from. func ChanSlotMaxInFlight() (n int32) { return chanSlotInFlightMax } // ChanSlotCommittedBytes is what the slot ring reserves up front: the mapping is // MAP_SHARED and lazily faulted, so this is committed address space and the // resident part is only the pages the messages touch. It replaces the 32MB per // direction the spawn rings reserve - that is the transport slope this closes. func ChanSlotCommittedBytes() (n int32) { return chanSlotCount * chanSlotBytes }